content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
indexWords = list()
def PreviousWord(_list, _word):
if _list[_list.index(_word)-1] :
return _list[_list.index(_word)-1]
else:
return
phrase = str(input())
phraseList = phrase.split(" ")
length = len(phraseList)
for item in phraseList :
item = item.strip()
if phrase != "" :
for i in range(1, length-1) :
lengthOfWord = len(phraseList[i])
if phraseList[i][0].isupper() :
if PreviousWord(phraseList, phraseList[i])[-1] != "." :
if phraseList[i][-1]=="." or phraseList[i][-1]=="," :
indexWords.append(i + 1)
indexWords.append(phraseList[i][: lengthOfWord-1])
elif phraseList[i][-1]== "]" and phraseList[i][-2]== "'" :
indexWords.append(i + 1)
indexWords.append(phraseList[i][: lengthOfWord-2])
else :
indexWords.append(i + 1)
indexWords.append(phraseList[i])
else:
print("None")
lengthOfIndexWord = len(indexWords)
if lengthOfIndexWord == 0 :
print("None")
else:
for i in range(0, lengthOfIndexWord//2):
print("%i:%s" %(indexWords[2*i],indexWords[(2*i)+1])) | index_words = list()
def previous_word(_list, _word):
if _list[_list.index(_word) - 1]:
return _list[_list.index(_word) - 1]
else:
return
phrase = str(input())
phrase_list = phrase.split(' ')
length = len(phraseList)
for item in phraseList:
item = item.strip()
if phrase != '':
for i in range(1, length - 1):
length_of_word = len(phraseList[i])
if phraseList[i][0].isupper():
if previous_word(phraseList, phraseList[i])[-1] != '.':
if phraseList[i][-1] == '.' or phraseList[i][-1] == ',':
indexWords.append(i + 1)
indexWords.append(phraseList[i][:lengthOfWord - 1])
elif phraseList[i][-1] == ']' and phraseList[i][-2] == "'":
indexWords.append(i + 1)
indexWords.append(phraseList[i][:lengthOfWord - 2])
else:
indexWords.append(i + 1)
indexWords.append(phraseList[i])
else:
print('None')
length_of_index_word = len(indexWords)
if lengthOfIndexWord == 0:
print('None')
else:
for i in range(0, lengthOfIndexWord // 2):
print('%i:%s' % (indexWords[2 * i], indexWords[2 * i + 1])) |
city_country = {}
for _ in range(int(input())):
country, *cities = input().split()
for city in cities:
city_country[city] = country
for _ in range(int(input())):
print(city_country[input()]) | city_country = {}
for _ in range(int(input())):
(country, *cities) = input().split()
for city in cities:
city_country[city] = country
for _ in range(int(input())):
print(city_country[input()]) |
nume1 = int(input("Digite um numero"))
nume2 = int(input("Digite um numero"))
nume3 = int(input("Digite um numero"))
nume4 = int(input("Digite um numero"))
nume5 = int(input("Digite um numero"))
table = [nume1,nume2,nume3,nume4,nume5]
tableM = (float((nume1 + nume2 + nume3 + nume4 + nume5)))
print(float(tableM)) | nume1 = int(input('Digite um numero'))
nume2 = int(input('Digite um numero'))
nume3 = int(input('Digite um numero'))
nume4 = int(input('Digite um numero'))
nume5 = int(input('Digite um numero'))
table = [nume1, nume2, nume3, nume4, nume5]
table_m = float(nume1 + nume2 + nume3 + nume4 + nume5)
print(float(tableM)) |
class Solution:
def combinationSum(self, candidates, target):
def lookup(candidates, index, target, combine, result):
if target == 0:
result.append(combine)
return
if index >= len(candidates) and target > 0:
return
if target >= candidates[index]:
lookup(candidates, index, target - candidates[index], list(combine) + [candidates[index]], result)
lookup(candidates, index + 1, target, list(combine), result)
sorted(candidates)
result = []
lookup(candidates, 0, target, [], result)
return result
s = Solution()
print(s.combinationSum([2,3,6,7], 7))
print(s.combinationSum([2,3,5], 8))
| class Solution:
def combination_sum(self, candidates, target):
def lookup(candidates, index, target, combine, result):
if target == 0:
result.append(combine)
return
if index >= len(candidates) and target > 0:
return
if target >= candidates[index]:
lookup(candidates, index, target - candidates[index], list(combine) + [candidates[index]], result)
lookup(candidates, index + 1, target, list(combine), result)
sorted(candidates)
result = []
lookup(candidates, 0, target, [], result)
return result
s = solution()
print(s.combinationSum([2, 3, 6, 7], 7))
print(s.combinationSum([2, 3, 5], 8)) |
# version of the graw package
__version__ = "0.1.0"
| __version__ = '0.1.0' |
'''
@author Gabriel Flores
Checks the primality of an integer.
'''
def is_prime(x):
'''
Checks the primality of an integer.
'''
sqrt = int(x ** (1/2))
for i in range(2, sqrt, 1):
if x % i == 0:
return False
return True
def main():
try:
print("\n\n")
a = int(input(" Enter an integer to check if it is prime: "))
if is_prime(a):
print("\n ",a,"is a prime number.\n")
else:
print("\n ",a,"is not a prime number.\n")
except ValueError as e:
print("\n\n Please enter a valid choice.\n")
if __name__ == "__main__":
main() | """
@author Gabriel Flores
Checks the primality of an integer.
"""
def is_prime(x):
"""
Checks the primality of an integer.
"""
sqrt = int(x ** (1 / 2))
for i in range(2, sqrt, 1):
if x % i == 0:
return False
return True
def main():
try:
print('\n\n')
a = int(input(' Enter an integer to check if it is prime: '))
if is_prime(a):
print('\n ', a, 'is a prime number.\n')
else:
print('\n ', a, 'is not a prime number.\n')
except ValueError as e:
print('\n\n Please enter a valid choice.\n')
if __name__ == '__main__':
main() |
"""
Created by akiselev on 2019-06-14
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.
Input Format
The first line contains a single integer
, the number of test cases.
For each test case, there are lines.
The first line of each test case contains , the number of cubes.
The second line contains
space separated integers, denoting the sideLengths of each cube in that order.
Constraints
Output Format
For each test case, output a single line containing either "Yes" or "No" without the quotes.
Sample Input
2
6
4 3 2 1 3 4
3
1 3 2
Sample Output
Yes
No
"""
for T in range(int(input())):
n = int(input())
cubes_h = list(map(int, input().split()))
i = 0
while i < n - 1 and cubes_h[i] >= cubes_h[i+1]:
i += 1
while i < n - 1 and cubes_h[i] <= cubes_h[i+1]:
i += 1
print("Yes" if i == n - 1 else "No")
| """
Created by akiselev on 2019-06-14
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.
Input Format
The first line contains a single integer
, the number of test cases.
For each test case, there are lines.
The first line of each test case contains , the number of cubes.
The second line contains
space separated integers, denoting the sideLengths of each cube in that order.
Constraints
Output Format
For each test case, output a single line containing either "Yes" or "No" without the quotes.
Sample Input
2
6
4 3 2 1 3 4
3
1 3 2
Sample Output
Yes
No
"""
for t in range(int(input())):
n = int(input())
cubes_h = list(map(int, input().split()))
i = 0
while i < n - 1 and cubes_h[i] >= cubes_h[i + 1]:
i += 1
while i < n - 1 and cubes_h[i] <= cubes_h[i + 1]:
i += 1
print('Yes' if i == n - 1 else 'No') |
def fibonacci_iterative(n):
previous = 0
current = 1
for i in range(n - 1):
current_old = current
current = previous + current
previous = current_old
return current
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1)
| def fibonacci_iterative(n):
previous = 0
current = 1
for i in range(n - 1):
current_old = current
current = previous + current
previous = current_old
return current
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1) |
__all__ = [
'session',
'event',
'profile',
'consent',
'segment',
'source',
'rule',
'entity'
]
| __all__ = ['session', 'event', 'profile', 'consent', 'segment', 'source', 'rule', 'entity'] |
def global_alignment(seq1, seq2, score_matrix, penalty):
len1, len2 = len(seq1), len(seq2)
s = [[0] * (len2 + 1) for i in range(len1 + 1)]
backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)]
for i in range(1, len1 + 1):
s[i][0] = - i * penalty
for j in range(1, len2 + 1):
s[0][j] = - j * penalty
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
score_list = [s[i - 1][j] - penalty, s[i][j - 1] - penalty,
s[i - 1][j - 1] + score_matrix[seq1[i - 1], seq2[j - 1]]]
s[i][j] = max(score_list)
backtrack[i][j] = score_list.index(s[i][j])
indel_insert = lambda seq, i: seq[:i] + '-' + seq[i:]
align1, align2 = seq1, seq2
a, b = len1, len2
max_score = str(s[a][b])
while a * b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = indel_insert(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = indel_insert(align1, a)
else:
a -= 1
b -= 1
for i in range(a):
align2 = indel_insert(align2, 0)
for j in range(b):
align1 = indel_insert(align1, 0)
return max_score, align1, align2
def mid_column_score(v, w, score_matrix, penalty):
s = [[i * j * penalty for i in range(-1, 1)] for j in range(len(v) + 1)]
s[0][1] = -penalty
backtrack = [0] * (len(v) + 1)
for j in range(1, len(w) // 2 + 1):
for i in range(0, len(v) + 1):
if i == 0:
s[i][1] = -j * penalty
else:
scores = [s[i - 1][0] + score_matrix[v[i - 1], w[j - 1]], s[i][0] - penalty, s[i - 1][1] - penalty]
s[i][1] = max(scores)
backtrack[i] = scores.index(s[i][1])
if j != len(w) // 2:
s = [[row[1]] * 2 for row in s]
return [i[1] for i in s], backtrack
def mid_edge(v, w, score_matrix, penalty):
source = mid_column_score(v, w, score_matrix, penalty)[0]
mid_to_sink, backtrack = list(map(lambda l: l[::-1], mid_column_score(v[::-1], w[::-1] + ['', '$'][
len(w) % 2 == 1 and len(w) > 1], score_matrix, penalty)))
scores = list(map(sum, zip(source, mid_to_sink)))
max_mid = max(range(len(scores)), key = lambda i: scores[i])
if max_mid == len(scores) - 1:
next_node = (max_mid, len(w) // 2 + 1)
else:
next_node = [(max_mid + 1, len(w) // 2 + 1), (max_mid, len(w) // 2 + 1), (max_mid + 1, len(w) // 2), ][
backtrack[max_mid]]
return (max_mid, len(w) // 2), next_node
def linear_space_alignment(top, bottom, left, right, score_matrix):
v = seq1
w = seq2
if left == right:
return [v[top:bottom], '-' * (bottom - top)]
elif top == bottom:
return ['-' * (right - left), w[left:right]]
elif bottom - top == 1 or right - left == 1:
return global_alignment(v[top:bottom], w[left:right], score_matrix, penalty)[1:]
else:
mid_node, next_node = mid_edge(v[top:bottom], w[left:right], score_matrix, penalty)
mid_node = tuple(map(sum, zip(mid_node, [top, left])))
next_node = tuple(map(sum, zip(next_node, [top, left])))
current = [['-', v[mid_node[0] % len(v)]][next_node[0] - mid_node[0]],
['-', w[mid_node[1] % len(w)]][next_node[1] - mid_node[1]]]
a = linear_space_alignment(top, mid_node[0], left, mid_node[1], score_matrix)
b = linear_space_alignment(next_node[0], bottom, next_node[1], right, score_matrix)
return [a[i] + current[i] + b[i] for i in range(2)]
def linear_space_global_alignment(v, w, score_matrix, penalty):
align1, align2 = linear_space_alignment(0, len(v), 0, len(w), score_matrix)
p = []
for i in zip(align1, align2):
if '-' in i:
p.append(-penalty)
else:
p.append(score_matrix[i])
score = sum(p)
return str(score), align1, align2
if __name__ == '__main__':
with open('input.txt') as f:
seq1 = f.readline().strip()
seq2 = f.readline().strip()
with open('BLOSUM62.txt') as f1:
lines = [line.strip().split() for line in f1.readlines()]
matrix = {(i[0], i[1]): int(i[2]) for i in lines}
penalty = 5
alignment = '\n'.join(linear_space_global_alignment(seq1, seq2, matrix, penalty))
print(alignment)
| def global_alignment(seq1, seq2, score_matrix, penalty):
(len1, len2) = (len(seq1), len(seq2))
s = [[0] * (len2 + 1) for i in range(len1 + 1)]
backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)]
for i in range(1, len1 + 1):
s[i][0] = -i * penalty
for j in range(1, len2 + 1):
s[0][j] = -j * penalty
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
score_list = [s[i - 1][j] - penalty, s[i][j - 1] - penalty, s[i - 1][j - 1] + score_matrix[seq1[i - 1], seq2[j - 1]]]
s[i][j] = max(score_list)
backtrack[i][j] = score_list.index(s[i][j])
indel_insert = lambda seq, i: seq[:i] + '-' + seq[i:]
(align1, align2) = (seq1, seq2)
(a, b) = (len1, len2)
max_score = str(s[a][b])
while a * b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = indel_insert(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = indel_insert(align1, a)
else:
a -= 1
b -= 1
for i in range(a):
align2 = indel_insert(align2, 0)
for j in range(b):
align1 = indel_insert(align1, 0)
return (max_score, align1, align2)
def mid_column_score(v, w, score_matrix, penalty):
s = [[i * j * penalty for i in range(-1, 1)] for j in range(len(v) + 1)]
s[0][1] = -penalty
backtrack = [0] * (len(v) + 1)
for j in range(1, len(w) // 2 + 1):
for i in range(0, len(v) + 1):
if i == 0:
s[i][1] = -j * penalty
else:
scores = [s[i - 1][0] + score_matrix[v[i - 1], w[j - 1]], s[i][0] - penalty, s[i - 1][1] - penalty]
s[i][1] = max(scores)
backtrack[i] = scores.index(s[i][1])
if j != len(w) // 2:
s = [[row[1]] * 2 for row in s]
return ([i[1] for i in s], backtrack)
def mid_edge(v, w, score_matrix, penalty):
source = mid_column_score(v, w, score_matrix, penalty)[0]
(mid_to_sink, backtrack) = list(map(lambda l: l[::-1], mid_column_score(v[::-1], w[::-1] + ['', '$'][len(w) % 2 == 1 and len(w) > 1], score_matrix, penalty)))
scores = list(map(sum, zip(source, mid_to_sink)))
max_mid = max(range(len(scores)), key=lambda i: scores[i])
if max_mid == len(scores) - 1:
next_node = (max_mid, len(w) // 2 + 1)
else:
next_node = [(max_mid + 1, len(w) // 2 + 1), (max_mid, len(w) // 2 + 1), (max_mid + 1, len(w) // 2)][backtrack[max_mid]]
return ((max_mid, len(w) // 2), next_node)
def linear_space_alignment(top, bottom, left, right, score_matrix):
v = seq1
w = seq2
if left == right:
return [v[top:bottom], '-' * (bottom - top)]
elif top == bottom:
return ['-' * (right - left), w[left:right]]
elif bottom - top == 1 or right - left == 1:
return global_alignment(v[top:bottom], w[left:right], score_matrix, penalty)[1:]
else:
(mid_node, next_node) = mid_edge(v[top:bottom], w[left:right], score_matrix, penalty)
mid_node = tuple(map(sum, zip(mid_node, [top, left])))
next_node = tuple(map(sum, zip(next_node, [top, left])))
current = [['-', v[mid_node[0] % len(v)]][next_node[0] - mid_node[0]], ['-', w[mid_node[1] % len(w)]][next_node[1] - mid_node[1]]]
a = linear_space_alignment(top, mid_node[0], left, mid_node[1], score_matrix)
b = linear_space_alignment(next_node[0], bottom, next_node[1], right, score_matrix)
return [a[i] + current[i] + b[i] for i in range(2)]
def linear_space_global_alignment(v, w, score_matrix, penalty):
(align1, align2) = linear_space_alignment(0, len(v), 0, len(w), score_matrix)
p = []
for i in zip(align1, align2):
if '-' in i:
p.append(-penalty)
else:
p.append(score_matrix[i])
score = sum(p)
return (str(score), align1, align2)
if __name__ == '__main__':
with open('input.txt') as f:
seq1 = f.readline().strip()
seq2 = f.readline().strip()
with open('BLOSUM62.txt') as f1:
lines = [line.strip().split() for line in f1.readlines()]
matrix = {(i[0], i[1]): int(i[2]) for i in lines}
penalty = 5
alignment = '\n'.join(linear_space_global_alignment(seq1, seq2, matrix, penalty))
print(alignment) |
def main(file: str) -> None:
depth = 0
distance = 0
aim = 0
with open(f"{file}.in") as f:
for line in f.readlines():
line = line.rstrip().split(" ")
command = line[0]
unit = int(line[1])
if command == "forward":
distance += unit
depth += aim * unit
elif command == "down":
aim += unit
else:
aim -= unit
print(f"{file}: {depth * distance}")
if __name__ == "__main__":
main("test")
main("puzzle")
| def main(file: str) -> None:
depth = 0
distance = 0
aim = 0
with open(f'{file}.in') as f:
for line in f.readlines():
line = line.rstrip().split(' ')
command = line[0]
unit = int(line[1])
if command == 'forward':
distance += unit
depth += aim * unit
elif command == 'down':
aim += unit
else:
aim -= unit
print(f'{file}: {depth * distance}')
if __name__ == '__main__':
main('test')
main('puzzle') |
# coding=utf8
class MetaSingleton(type):
def __init__(cls, *args):
type.__init__(cls, *args)
cls.instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = type.__call__(cls, *args, **kwargs)
return cls.instance
| class Metasingleton(type):
def __init__(cls, *args):
type.__init__(cls, *args)
cls.instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = type.__call__(cls, *args, **kwargs)
return cls.instance |
how_many_snakes = 1
snake_string = """
Welcome to Python3!
____
/ . .\\
\\ ---<
\\ /
__________/ /
-=:___________/
<3, Juno
"""
print(snake_string * how_many_snakes) | how_many_snakes = 1
snake_string = '\nWelcome to Python3!\n\n ____\n / . .\\\n \\ ---<\n \\ /\n __________/ /\n-=:___________/\n\n<3, Juno\n'
print(snake_string * how_many_snakes) |
class Person:
olhos = 2
def __init__(self, *children, name=None, year=0):
self.year = year
self.name = name
self.children = list(children)
def cumprimentar(self):
return 'Hello'
@staticmethod
def metodo_estatico():
return 123
@classmethod
def metodo_classe(cls):
return f'{cls} - {cls.olhos}'
if __name__ == '__main__':
p = Person()
eu = Person(name='marcio')
wes = Person(eu, name='Wesley')
print(p.cumprimentar())
print(p.year) # Atributo de instancia
print(p.name) # Atributo de dados
for filhos in wes.children:
print(filhos.year)
p.sobre = 'eu'
print(p.sobre)
del p.sobre
print(p.__dict__)
print(p.olhos)
print(eu.olhos)
print(p.metodo_estatico(), eu.metodo_estatico())
print(p.metodo_classe(), eu.metodo_classe())
| class Person:
olhos = 2
def __init__(self, *children, name=None, year=0):
self.year = year
self.name = name
self.children = list(children)
def cumprimentar(self):
return 'Hello'
@staticmethod
def metodo_estatico():
return 123
@classmethod
def metodo_classe(cls):
return f'{cls} - {cls.olhos}'
if __name__ == '__main__':
p = person()
eu = person(name='marcio')
wes = person(eu, name='Wesley')
print(p.cumprimentar())
print(p.year)
print(p.name)
for filhos in wes.children:
print(filhos.year)
p.sobre = 'eu'
print(p.sobre)
del p.sobre
print(p.__dict__)
print(p.olhos)
print(eu.olhos)
print(p.metodo_estatico(), eu.metodo_estatico())
print(p.metodo_classe(), eu.metodo_classe()) |
class Animal:
def __init__(self):
self.name = ""
self.weight = 0
self.sound = ""
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setWeight(self, weight):
self.weight = weight
def getWeight(self):
return self.weight
def setSound(self, sound):
self.sound = sound
def getSound(self):
return self.sound
| class Animal:
def __init__(self):
self.name = ''
self.weight = 0
self.sound = ''
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_weight(self, weight):
self.weight = weight
def get_weight(self):
return self.weight
def set_sound(self, sound):
self.sound = sound
def get_sound(self):
return self.sound |
#!/usr/bin/python3
lines = open("inputs/07.in", "r").readlines()
for i,line in enumerate(lines):
lines[i] = line.split("\n")[0]
l = lines.copy();
wires = {}
def func_set(p, i):
if p[0].isdigit():
wires[p[2]] = int(p[0])
lines.pop(i)
elif p[0] in wires.keys():
wires[p[2]] = wires[p[0]]
lines.pop(i)
def func_and(p, i):
if p[0].isdigit() and p[2] in wires.keys():
wires[p[4]] = int(p[0]) & wires[p[2]]
lines.pop(i)
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] & wires[p[2]]
lines.pop(i)
def func_or(p, i):
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] | wires[p[2]]
lines.pop(i)
def func_rshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] >> int(p[2])
lines.pop(i)
def func_lshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] << int(p[2])
lines.pop(i)
def func_not(p, i):
if p[1] in wires.keys():
wires[p[3]] = 65535 - wires[p[1]]
lines.pop(i)
def run():
i = 0
while len(lines) > 0:
parts = lines[i].split(" ")
if "AND" in parts:
func_and(parts, i)
elif "NOT" in parts:
func_not(parts, i)
elif "RSHIFT" in parts:
func_rshift(parts, i)
elif "LSHIFT" in parts:
func_lshift(parts, i)
elif "OR" in parts:
func_or(parts, i)
else:
func_set(parts, i)
i += 1
if i >= len(lines):
i = 0
run()
print("Part 1: " + str(wires["a"]))
lines = l
wires = {"b": wires["a"]}
run()
print("Part 2: " + str(wires["a"]))
| lines = open('inputs/07.in', 'r').readlines()
for (i, line) in enumerate(lines):
lines[i] = line.split('\n')[0]
l = lines.copy()
wires = {}
def func_set(p, i):
if p[0].isdigit():
wires[p[2]] = int(p[0])
lines.pop(i)
elif p[0] in wires.keys():
wires[p[2]] = wires[p[0]]
lines.pop(i)
def func_and(p, i):
if p[0].isdigit() and p[2] in wires.keys():
wires[p[4]] = int(p[0]) & wires[p[2]]
lines.pop(i)
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] & wires[p[2]]
lines.pop(i)
def func_or(p, i):
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] | wires[p[2]]
lines.pop(i)
def func_rshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] >> int(p[2])
lines.pop(i)
def func_lshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] << int(p[2])
lines.pop(i)
def func_not(p, i):
if p[1] in wires.keys():
wires[p[3]] = 65535 - wires[p[1]]
lines.pop(i)
def run():
i = 0
while len(lines) > 0:
parts = lines[i].split(' ')
if 'AND' in parts:
func_and(parts, i)
elif 'NOT' in parts:
func_not(parts, i)
elif 'RSHIFT' in parts:
func_rshift(parts, i)
elif 'LSHIFT' in parts:
func_lshift(parts, i)
elif 'OR' in parts:
func_or(parts, i)
else:
func_set(parts, i)
i += 1
if i >= len(lines):
i = 0
run()
print('Part 1: ' + str(wires['a']))
lines = l
wires = {'b': wires['a']}
run()
print('Part 2: ' + str(wires['a'])) |
#Variables
#Working with build 2234
saberPort = "/dev/ttyUSB0"
#Initializing Motorcontroller
saber = Runtime.start("saber", "Sabertooth")
saber.connect(saberPort)
sleep(1)
#Initializing Joystick
joystick = Runtime.start("joystick","Joystick")
print(joystick.getControllers())
python.subscribe("joystick","publishJoystickInput")
joystick.setController(0)
for x in range(0,100):
print("power", x)
saber.driveForwardMotor1(x)
sleep(0.5)
for x in range(100,-1,-1):
print("power", x)
saber.driveForwardMotor1(x)
sleep(0.5)
| saber_port = '/dev/ttyUSB0'
saber = Runtime.start('saber', 'Sabertooth')
saber.connect(saberPort)
sleep(1)
joystick = Runtime.start('joystick', 'Joystick')
print(joystick.getControllers())
python.subscribe('joystick', 'publishJoystickInput')
joystick.setController(0)
for x in range(0, 100):
print('power', x)
saber.driveForwardMotor1(x)
sleep(0.5)
for x in range(100, -1, -1):
print('power', x)
saber.driveForwardMotor1(x)
sleep(0.5) |
# Author: Guilherme Aldeia
# Contact: guilherme.aldeia@ufabc.edu.br
# Version: 1.0.0
# Last modified: 08-20-2021 by Guilherme Aldeia
"""
Simple exception that is raised by explainers when they don't support local
or global explanations, or when they are not model agnostic. This should be
catched and handled in the experiments.
"""
class NotApplicableException(Exception):
def __init__(self, message=""):
self.message = message | """
Simple exception that is raised by explainers when they don't support local
or global explanations, or when they are not model agnostic. This should be
catched and handled in the experiments.
"""
class Notapplicableexception(Exception):
def __init__(self, message=''):
self.message = message |
# ASSIGNMENT 3
"""
During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3).
Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10.
The committee needs a program that will allow managing the list of scores and establishing the winners.
Write a program that implements the functionalities exemplified below:
(A) Add the result of a new participant (add, insert)
(B) Modify scores (remove, remove between two postion, replace the score obtained by a certain participant at a
certain problem with other score obtained by other participant)
(C) Display participants whose score has different properties. """
def get(list, position):
""" The function will extract a certain element from a list."""
return list[int(position)]
def set(list, element, position):
""" The functin will set a certain element from a list.
:param list: [ ['2', '4', '8'], ['3', '5', '6'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'] ]
:param element: ['5', '8', '9']
:param position: 1
:return: [ ['2', '4', '8'], ['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10']
"""
list.insert(int(position), element)
list.remove(get(list, int(position) + 1))
def make_a_list(sentence):
""" The function will make a list containing the given scores P1, P2 and P3 that are found in the command."""
list_one_score = []
for i in range(1, 4):
list_one_score.append(sentence[i])
return list_one_score
def add_scores(list, sentence):
""" The function will add to the principal list (with all the scores of all the participants) a list with the
scores of just one participant.
"""
list.append(make_a_list(sentence))
def insert_scores(list, sentence, position):
""" The function will insert in a given position to the principal list (with all the scores of all the participants)
a list with the scores of just one participant
"""
list.insert(int(position), make_a_list(sentence))
def remove_one_part(list, position):
""" The function will set the scores of the participant at a given position to 0.
So that, the participant <position> score P1=P2=P3= 0. """
nul_element = ['0', '0', '0']
set(list, nul_element, position)
def remove_more_part(list, first_position, last_position):
""" The function will set the scores of all the participants between the first position and last position to 0.
For all the participants between <first_position> and <last_position>, P1=P1=P3= 0 """
nul_element = ['0', '0', '0']
for i in range(int(first_position), int(last_position) + 1):
set(list, nul_element, i)
def remove(list, cmd):
if len(cmd) == 2: # The command is remove <position>
remove_one_part(list, get(cmd, 1))
elif len(cmd) == 4: # The command is remove <first pos> to <last pos>
remove_more_part(list, get(cmd, 1), get(cmd, 3))
def replace(list, problem, new_score):
""" The function will replace a score obtained by a participant at a specific problem with a new score.
List represents the list with the scores of a participant, where <problem> ( P1/P2/P3 ) will recive a new score
"""
set(list, new_score, int(problem[1]) - 1)
def calc_average(list):
""" The function will calculate the average of all the integers from a list ( it will calculate the sum of al the
integers, and then it will divide the sum by the value of the len of tne list)
:param list: [ '2', '4', '3' ]
:return: 3
"""
result = 0
for i in range(0, len(list)):
result = result + int(get(list, i))
return result / len(list)
def average_score_lesser(list, number):
""" The function will display all the participants with an average score lesser than the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return:['10', '4', '6'], ['9', '3', '2']
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) < number:
l.append(get(list, i))
return l
def average_score_equal(list, number):
""" The function will display all the participants with an average score equal with the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 8
:return:['7', '8', '9']
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) == number:
l.append(get(list, i))
return l
def average_score_greater(list, number):
""" The function will return a list with all the participants with an average score greater than the given number.
:param list: [['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return: [['10', '10', '10'], ['7', '8', '9']]
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) > number:
l.append(get(list, i))
return l
def list_sorted(list):
""" The function will return a list with participants sorted in decreasing order of average score
:param list: [['5', '8', '9'], ['10', '4', '6'], ['10', '10', '10'], ['7', '8', '9'], ['10', '2', '9']]
:return: [['10', '10', '10'], , ['7', '8', '9'], ['5', '8', '9'], ['10', '2', '9'], ['10', '4', '6']]
"""
l = []
for i in range(0, len(list)):
get(list, i).insert(0, calc_average(get(list, i)))
l.append(get(list, i))
l.sort(reverse=True)
for i in range(0, len(l)):
get(l, i)
get(l, i).remove(get(get(l, i), 0))
return l
def list(list, cmd):
if len(cmd) == 1:
l = list
elif get(cmd, 1) == 'sorted':
l = list_sorted(list)
elif get(cmd, 1) == '<':
l = average_score_lesser(list, int(get(cmd, 2)))
elif get(cmd, 1) == '=':
l = average_score_equal(list, int(get(cmd, 2)))
elif get(cmd, 1) == '>':
l = average_score_greater(list, int(get(cmd, 2)))
print(l)
def print_menu():
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>',
'remove <position>', 'remove <start position> to <end position>',
'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
print("The possible comands are:")
print(*commands, sep="\n")
def run_menu():
list_participants_scores = [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9'],
['8', '9', '10'], ['10', '2', '9'], ['2', '4', '6'], ['8', '2', '1'], ['0', '8', '4']]
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>',
'remove <position>', 'remove <start position> to <end position>',
'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
while True:
comand = input()
comand_splited = comand.split()
first_word = get(comand_splited, 0)
if first_word == 'add': # The command is add P1, P2, P3
add_scores(list_participants_scores, comand_splited)
elif first_word == 'insert': # The command is insert [P1, P2, P3] at position
insert_scores(list_participants_scores, comand_splited, comand_splited[5])
elif first_word == 'remove':
remove(list_participants_scores, comand_splited)
elif first_word == 'replace': # The command is replace <old score> P1/P2/P3 with <new score>
replace(get(list_participants_scores, int(get(comand_splited, 1))), get(comand_splited, 2),
(get(comand_splited, 4)))
elif first_word == 'list':
(list(list_participants_scores, comand_splited))
else:
print("Wrong command")
break
if __name__ == '__main__':
print_menu()
run_menu()
| """
During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3).
Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10.
The committee needs a program that will allow managing the list of scores and establishing the winners.
Write a program that implements the functionalities exemplified below:
(A) Add the result of a new participant (add, insert)
(B) Modify scores (remove, remove between two postion, replace the score obtained by a certain participant at a
certain problem with other score obtained by other participant)
(C) Display participants whose score has different properties. """
def get(list, position):
""" The function will extract a certain element from a list."""
return list[int(position)]
def set(list, element, position):
""" The functin will set a certain element from a list.
:param list: [ ['2', '4', '8'], ['3', '5', '6'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'] ]
:param element: ['5', '8', '9']
:param position: 1
:return: [ ['2', '4', '8'], ['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10']
"""
list.insert(int(position), element)
list.remove(get(list, int(position) + 1))
def make_a_list(sentence):
""" The function will make a list containing the given scores P1, P2 and P3 that are found in the command."""
list_one_score = []
for i in range(1, 4):
list_one_score.append(sentence[i])
return list_one_score
def add_scores(list, sentence):
""" The function will add to the principal list (with all the scores of all the participants) a list with the
scores of just one participant.
"""
list.append(make_a_list(sentence))
def insert_scores(list, sentence, position):
""" The function will insert in a given position to the principal list (with all the scores of all the participants)
a list with the scores of just one participant
"""
list.insert(int(position), make_a_list(sentence))
def remove_one_part(list, position):
""" The function will set the scores of the participant at a given position to 0.
So that, the participant <position> score P1=P2=P3= 0. """
nul_element = ['0', '0', '0']
set(list, nul_element, position)
def remove_more_part(list, first_position, last_position):
""" The function will set the scores of all the participants between the first position and last position to 0.
For all the participants between <first_position> and <last_position>, P1=P1=P3= 0 """
nul_element = ['0', '0', '0']
for i in range(int(first_position), int(last_position) + 1):
set(list, nul_element, i)
def remove(list, cmd):
if len(cmd) == 2:
remove_one_part(list, get(cmd, 1))
elif len(cmd) == 4:
remove_more_part(list, get(cmd, 1), get(cmd, 3))
def replace(list, problem, new_score):
""" The function will replace a score obtained by a participant at a specific problem with a new score.
List represents the list with the scores of a participant, where <problem> ( P1/P2/P3 ) will recive a new score
"""
set(list, new_score, int(problem[1]) - 1)
def calc_average(list):
""" The function will calculate the average of all the integers from a list ( it will calculate the sum of al the
integers, and then it will divide the sum by the value of the len of tne list)
:param list: [ '2', '4', '3' ]
:return: 3
"""
result = 0
for i in range(0, len(list)):
result = result + int(get(list, i))
return result / len(list)
def average_score_lesser(list, number):
""" The function will display all the participants with an average score lesser than the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return:['10', '4', '6'], ['9', '3', '2']
"""
l = []
for i in range(0, len(list)):
if calc_average(get(list, i)) < number:
l.append(get(list, i))
return l
def average_score_equal(list, number):
""" The function will display all the participants with an average score equal with the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 8
:return:['7', '8', '9']
"""
l = []
for i in range(0, len(list)):
if calc_average(get(list, i)) == number:
l.append(get(list, i))
return l
def average_score_greater(list, number):
""" The function will return a list with all the participants with an average score greater than the given number.
:param list: [['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return: [['10', '10', '10'], ['7', '8', '9']]
"""
l = []
for i in range(0, len(list)):
if calc_average(get(list, i)) > number:
l.append(get(list, i))
return l
def list_sorted(list):
""" The function will return a list with participants sorted in decreasing order of average score
:param list: [['5', '8', '9'], ['10', '4', '6'], ['10', '10', '10'], ['7', '8', '9'], ['10', '2', '9']]
:return: [['10', '10', '10'], , ['7', '8', '9'], ['5', '8', '9'], ['10', '2', '9'], ['10', '4', '6']]
"""
l = []
for i in range(0, len(list)):
get(list, i).insert(0, calc_average(get(list, i)))
l.append(get(list, i))
l.sort(reverse=True)
for i in range(0, len(l)):
get(l, i)
get(l, i).remove(get(get(l, i), 0))
return l
def list(list, cmd):
if len(cmd) == 1:
l = list
elif get(cmd, 1) == 'sorted':
l = list_sorted(list)
elif get(cmd, 1) == '<':
l = average_score_lesser(list, int(get(cmd, 2)))
elif get(cmd, 1) == '=':
l = average_score_equal(list, int(get(cmd, 2)))
elif get(cmd, 1) == '>':
l = average_score_greater(list, int(get(cmd, 2)))
print(l)
def print_menu():
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>', 'remove <position>', 'remove <start position> to <end position>', 'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
print('The possible comands are:')
print(*commands, sep='\n')
def run_menu():
list_participants_scores = [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9'], ['8', '9', '10'], ['10', '2', '9'], ['2', '4', '6'], ['8', '2', '1'], ['0', '8', '4']]
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>', 'remove <position>', 'remove <start position> to <end position>', 'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
while True:
comand = input()
comand_splited = comand.split()
first_word = get(comand_splited, 0)
if first_word == 'add':
add_scores(list_participants_scores, comand_splited)
elif first_word == 'insert':
insert_scores(list_participants_scores, comand_splited, comand_splited[5])
elif first_word == 'remove':
remove(list_participants_scores, comand_splited)
elif first_word == 'replace':
replace(get(list_participants_scores, int(get(comand_splited, 1))), get(comand_splited, 2), get(comand_splited, 4))
elif first_word == 'list':
list(list_participants_scores, comand_splited)
else:
print('Wrong command')
break
if __name__ == '__main__':
print_menu()
run_menu() |
#===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================
load("@onedal//dev/bazel:repos.bzl", "repos")
micromkl_repo = repos.prebuilt_libs_repo_rule(
includes = [
"include",
"%{os}/include",
],
libs = [
"%{os}/lib/intel64/libdaal_mkl_thread.a",
"%{os}/lib/intel64/libdaal_mkl_sequential.a",
"%{os}/lib/intel64/libdaal_vmlipp_core.a",
],
build_template = "@onedal//dev/bazel/deps:micromkl.tpl.BUILD",
)
micromkl_dpc_repo = repos.prebuilt_libs_repo_rule(
includes = [
"include",
],
libs = [
"lib/intel64/libdaal_sycl.a",
],
build_template = "@onedal//dev/bazel/deps:micromkldpc.tpl.BUILD",
)
| load('@onedal//dev/bazel:repos.bzl', 'repos')
micromkl_repo = repos.prebuilt_libs_repo_rule(includes=['include', '%{os}/include'], libs=['%{os}/lib/intel64/libdaal_mkl_thread.a', '%{os}/lib/intel64/libdaal_mkl_sequential.a', '%{os}/lib/intel64/libdaal_vmlipp_core.a'], build_template='@onedal//dev/bazel/deps:micromkl.tpl.BUILD')
micromkl_dpc_repo = repos.prebuilt_libs_repo_rule(includes=['include'], libs=['lib/intel64/libdaal_sycl.a'], build_template='@onedal//dev/bazel/deps:micromkldpc.tpl.BUILD') |
guests=int(input())
reservations=set([])
while guests!=0:
reservationCode=input()
reservations.add(reservationCode)
guests-=1
while True:
r=input()
if r!="END":
reservations.discard(r)
else:
print(len(reservations))
VIPS=[]; Regulars=[]
for e in reservations:
if e[0].isnumeric():
VIPS.append(e)
else:
Regulars.append(e)
VIPS.sort(); Regulars.sort()
for k in VIPS:
print(k)
for k in Regulars:
print(k)
break | guests = int(input())
reservations = set([])
while guests != 0:
reservation_code = input()
reservations.add(reservationCode)
guests -= 1
while True:
r = input()
if r != 'END':
reservations.discard(r)
else:
print(len(reservations))
vips = []
regulars = []
for e in reservations:
if e[0].isnumeric():
VIPS.append(e)
else:
Regulars.append(e)
VIPS.sort()
Regulars.sort()
for k in VIPS:
print(k)
for k in Regulars:
print(k)
break |
class TestClass:
def __init__(self, list, name):
self.list = list
self.name = name
def func1():
print("func1 print something")
def func2():
print("func2 print something")
integer = 8
return integer
def func3():
print("func3 print something")
s = "func3"
return s
def func4():
print("func4 print something")
listIntegers = [1,2,3,4,5]
return listIntegers
def func5():
print("func5 print something")
listStrings = ["a","b","c","d","e"]
return listStrings
print("Hello World")
# test = TestClass()
| class Testclass:
def __init__(self, list, name):
self.list = list
self.name = name
def func1():
print('func1 print something')
def func2():
print('func2 print something')
integer = 8
return integer
def func3():
print('func3 print something')
s = 'func3'
return s
def func4():
print('func4 print something')
list_integers = [1, 2, 3, 4, 5]
return listIntegers
def func5():
print('func5 print something')
list_strings = ['a', 'b', 'c', 'd', 'e']
return listStrings
print('Hello World') |
# // ###########################################################################
# // Queries
# // ###########################################################################
# -> get a single cell of a df (use `iloc` with `row` + `col` as arguments)
df.iloc[0]['staticContextId']
# -> get one column as a list
allFunctionNames = staticContexts[['displayName']].to_numpy().flatten().tolist()
# -> get all rows that match a condition
callLinked = staticTraces[~staticTraces['callId'].isin([0])]
# -> exclude columns
df.drop(['A', 'B'], axis=1)
# -> complex queries
staticTraces.query(f'callId == {callId} or resultCallId == {callId}')
# -> join queries (several examples)
# https://stackoverflow.com/a/40869861
df.set_index('key').join(other.set_index('key'))
B.query('client_id not in @A.client_id')
B[~B.client_id.isin(A.client_id)]
# merging dfs
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
pd.merge(df1, df2, on=['A', 'B'])
df1.merge(df2, left_on='lkey', right_on='rkey')
# // ###########################################################################
# // Display
# // ###########################################################################
# -> display a groupby object (https://stackoverflow.com/questions/22691010/how-to-print-a-groupby-object)
groups = df.groupby('A')
for key, item in groups:
group = groups.get_group(key)
display(group)
# .to_numpy().flatten().tolist() | df.iloc[0]['staticContextId']
all_function_names = staticContexts[['displayName']].to_numpy().flatten().tolist()
call_linked = staticTraces[~staticTraces['callId'].isin([0])]
df.drop(['A', 'B'], axis=1)
staticTraces.query(f'callId == {callId} or resultCallId == {callId}')
df.set_index('key').join(other.set_index('key'))
B.query('client_id not in @A.client_id')
B[~B.client_id.isin(A.client_id)]
pd.merge(df1, df2, on=['A', 'B'])
df1.merge(df2, left_on='lkey', right_on='rkey')
groups = df.groupby('A')
for (key, item) in groups:
group = groups.get_group(key)
display(group) |
"""Module to help guess whether a file is binary or text.
Requirements:
Python 2.7+
Recommended:
Python 3
"""
def is_binary_file(fname):
"""Attempt to guess if 'fname' is a binary file heuristically.
This algorithm has many flaws. Use with caution.
It assumes that if a part of the file has NUL bytes
or has more control characters than text characters,
it is a binary file.
Additionally, an ASCII compatible character set is assumed.
Returns True if 'fname' appears to be a binary file.
"""
with open(fname, 'rb') as fh:
chunk = fh.read(1024)
if not chunk: # Empty file
return False
if b'\x00' in chunk: # Has NUL bytes
return True
ncontrol = control_char_count(chunk)
ntext = len(chunk) - ncontrol
return ncontrol > ntext
def is_control_char(c):
"""Return True if 'c' is a control character.
c is considered a control character if
it is outside of the extended ASCII set or
has a code below 32 with some exclusions.
An ASCII compatible character set is assumed.
"""
charcode = 0
# The following assignment
# should make this module compatible with
# at least Python 2.7 (tested on 2.7.9).
try:
charcode = ord(c)
except TypeError:
charcode = c
excludes = ("\t", "\r", "\n")
if charcode in [ord(char) for char in excludes]:
return False
return (charcode < 32 or
charcode > 255)
def control_char_count(data):
"""Return the count of control characters in 'data'."""
n = 0
for c in data:
if is_control_char(c):
n += 1
return n
| """Module to help guess whether a file is binary or text.
Requirements:
Python 2.7+
Recommended:
Python 3
"""
def is_binary_file(fname):
"""Attempt to guess if 'fname' is a binary file heuristically.
This algorithm has many flaws. Use with caution.
It assumes that if a part of the file has NUL bytes
or has more control characters than text characters,
it is a binary file.
Additionally, an ASCII compatible character set is assumed.
Returns True if 'fname' appears to be a binary file.
"""
with open(fname, 'rb') as fh:
chunk = fh.read(1024)
if not chunk:
return False
if b'\x00' in chunk:
return True
ncontrol = control_char_count(chunk)
ntext = len(chunk) - ncontrol
return ncontrol > ntext
def is_control_char(c):
"""Return True if 'c' is a control character.
c is considered a control character if
it is outside of the extended ASCII set or
has a code below 32 with some exclusions.
An ASCII compatible character set is assumed.
"""
charcode = 0
try:
charcode = ord(c)
except TypeError:
charcode = c
excludes = ('\t', '\r', '\n')
if charcode in [ord(char) for char in excludes]:
return False
return charcode < 32 or charcode > 255
def control_char_count(data):
"""Return the count of control characters in 'data'."""
n = 0
for c in data:
if is_control_char(c):
n += 1
return n |
def climbingLeaderboard(ranked, player):
ranked = sorted(list(set(ranked)), reverse=True)
ranks = []
# print(ranked)
for i in range(len(player)):
bi = 0
bs = len(ranked) - 1
index = 0
while (bi <= bs):
mid = (bi+bs) // 2
if (ranked[mid] > player[i]):
index = mid
bi = mid + 1
else:
bs = mid - 1
if (ranked[index] > player[i]):
index += 1
index += 1
ranks.append(index)
return ranks
| def climbing_leaderboard(ranked, player):
ranked = sorted(list(set(ranked)), reverse=True)
ranks = []
for i in range(len(player)):
bi = 0
bs = len(ranked) - 1
index = 0
while bi <= bs:
mid = (bi + bs) // 2
if ranked[mid] > player[i]:
index = mid
bi = mid + 1
else:
bs = mid - 1
if ranked[index] > player[i]:
index += 1
index += 1
ranks.append(index)
return ranks |
class Auth():
def __init__(self, client):
self.client = client
def get_profiles(self):
return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results']
def get_groups(self):
return self.client.get('/auth/api/groups/')
def get_group_map(self):
return {group['id']: group['name'] for group in self.get_groups()}
def activate_profile(self, pk):
return self.client.put('/auth/api/profiles/%d/activate/' % pk, {})
def update_profile_attributes(self, pk, attributes):
return self.client.patch('/auth/api/profiles/%d/' % pk, {'attributes': attributes})
| class Auth:
def __init__(self, client):
self.client = client
def get_profiles(self):
return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results']
def get_groups(self):
return self.client.get('/auth/api/groups/')
def get_group_map(self):
return {group['id']: group['name'] for group in self.get_groups()}
def activate_profile(self, pk):
return self.client.put('/auth/api/profiles/%d/activate/' % pk, {})
def update_profile_attributes(self, pk, attributes):
return self.client.patch('/auth/api/profiles/%d/' % pk, {'attributes': attributes}) |
input = """
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
"""
def validate(passport):
passport_fields = { "byr": False, "iyr": False, "eyr": False, "hgt": False, "hcl": False, "ecl": False, "pid": False }
for line in passport.split("\n"):
values = line.split(" ")
for value in values:
field = value.split(":")[0]
if field == "cid":
continue
passport_fields[field] = True
if False in passport_fields.values():
return False
return True
count = 0
for i in input.strip().split("\n\n"):
if validate(i):
count += 1
print(count) | input = '\necl:gry pid:860033327 eyr:2020 hcl:#fffffd\nbyr:1937 iyr:2017 cid:147 hgt:183cm\n\niyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884\nhcl:#cfa07d byr:1929\n\nhcl:#ae17e1 iyr:2013\neyr:2024\necl:brn pid:760753108 byr:1931\nhgt:179cm\n\nhcl:#cfa07d eyr:2025 pid:166559648\niyr:2011 ecl:brn hgt:59in\n'
def validate(passport):
passport_fields = {'byr': False, 'iyr': False, 'eyr': False, 'hgt': False, 'hcl': False, 'ecl': False, 'pid': False}
for line in passport.split('\n'):
values = line.split(' ')
for value in values:
field = value.split(':')[0]
if field == 'cid':
continue
passport_fields[field] = True
if False in passport_fields.values():
return False
return True
count = 0
for i in input.strip().split('\n\n'):
if validate(i):
count += 1
print(count) |
class Solution:
def kthFactor(self, n: int, k: int) -> int:
s1 = set()
s2 = set()
for i in range(1,int(n**0.5)+1):
if n%i ==0:
s1.add(i)
s2.add(int(n/i))
l = list(s1|s2)
l.sort()
if k > len(l):
return -1
return l[k-1] | class Solution:
def kth_factor(self, n: int, k: int) -> int:
s1 = set()
s2 = set()
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
s1.add(i)
s2.add(int(n / i))
l = list(s1 | s2)
l.sort()
if k > len(l):
return -1
return l[k - 1] |
class Node(object): # Similar to Linked List initial set-up
def __init__(self, value): # Constructor
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "") # init
elif traversal_type == "inorder":
return self.in_order_print(tree.root, "") # init
elif traversal_type == "postorder":
return self.post_order_print(tree.root, "") # init
else:
print("Traversal type " + str(traversal_type) + "not valid")
return False
def preorder_print(self, start, traversal):
# Root --> Left --> Right
if start:
traversal += (str(start.value) + "--")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def in_order_print(self, start, traversal):
# Very Left --> Root --> Very Right
if start:
traversal = self.in_order_print(start.left, traversal)
traversal += (str(start.value) + '--')
traversal = self.in_order_print(start.right, traversal)
return traversal
def post_order_print(self, start, traversal):
# Very Left --> Very Right --> Root
if start:
traversal = self.post_order_print(start.left, traversal)
traversal = self.post_order_print(start.right, traversal)
traversal += (str(start.value) + '--')
return traversal
"""Try doing Post-Order tomorrow"""
# Visualization of Current Tree
# Pre-Order Output: 1--2--4--9--10--11--5--3--6--7--8--
# In-Order Output: 11--10--9--4--2--5--1--6--3--7--8--
# Pre-Order Output: 11--10--9--4--5--2--6--8--7--3--1--
# 1
# / \
# 2 3
# / | / |
# 4 5 6 7
# / \
# 9 8
# /
# 10
# /
# 11
# Tree Set-Up
# Another implementation
# class BinaryTree(object):
# def __init__(self, root):
# self.root = Node(root)
# def search(self, find_val):
# return self.preorder_search(tree.root, find_val)
# def print_tree(self):
# return self.preorder_print(tree.root, "")[:-1]
# def preorder_search(self, start, find_val):
# if start:
# if start.value == find_val:
# return True
# else:
# return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val)
# return False
# def preorder_print(self, start, traversal):
# if start:
# traversal += (str(start.value) + "-")
# traversal = self.preorder_print(start.left, traversal)
# traversal = self.preorder_print(start.right, traversal)
# return traversal
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
tree.root.right.right.right = Node(8)
tree.root.left.left.left = Node(9)
tree.root.left.left.left.left = Node(10)
tree.root.left.left.left.left.left = Node(11)
# print(tree.print_tree("preorder"))
# print(tree.print_tree("inorder"))
print(tree.print_tree("postorder"))
| class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarytree(object):
def __init__(self, root):
self.root = node(root)
def print_tree(self, traversal_type):
if traversal_type == 'preorder':
return self.preorder_print(tree.root, '')
elif traversal_type == 'inorder':
return self.in_order_print(tree.root, '')
elif traversal_type == 'postorder':
return self.post_order_print(tree.root, '')
else:
print('Traversal type ' + str(traversal_type) + 'not valid')
return False
def preorder_print(self, start, traversal):
if start:
traversal += str(start.value) + '--'
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def in_order_print(self, start, traversal):
if start:
traversal = self.in_order_print(start.left, traversal)
traversal += str(start.value) + '--'
traversal = self.in_order_print(start.right, traversal)
return traversal
def post_order_print(self, start, traversal):
if start:
traversal = self.post_order_print(start.left, traversal)
traversal = self.post_order_print(start.right, traversal)
traversal += str(start.value) + '--'
return traversal
'Try doing Post-Order tomorrow'
tree = binary_tree(1)
tree.root.left = node(2)
tree.root.right = node(3)
tree.root.left.left = node(4)
tree.root.left.right = node(5)
tree.root.right.left = node(6)
tree.root.right.right = node(7)
tree.root.right.right.right = node(8)
tree.root.left.left.left = node(9)
tree.root.left.left.left.left = node(10)
tree.root.left.left.left.left.left = node(11)
print(tree.print_tree('postorder')) |
# _*_ coding: utf-8 _*_
"""
util_config.py by xianhu
"""
__all__ = [
"CONFIG_FETCH_MESSAGE",
"CONFIG_PARSE_MESSAGE",
"CONFIG_MESSAGE_PATTERN",
"CONFIG_URL_LEGAL_PATTERN",
"CONFIG_URL_ILLEGAL_PATTERN",
]
# define the structure of message, used in Fetcher and Parser
CONFIG_FETCH_MESSAGE = "priority=%s, keys=%s, deep=%s, repeat=%s, url=%s"
CONFIG_PARSE_MESSAGE = "priority=%s, keys=%s, deep=%s, url=%s"
CONFIG_MESSAGE_PATTERN = r"priority=(?P<priority>\d+),\s*keys=(?P<keys>.+?),\s*deep=(?P<deep>\d+),\s*(repeat=(?P<repeat>\d+),\s*)?url=(?P<url>.+)$"
# define url_legal_pattern and url_illegal_pattern
CONFIG_URL_LEGAL_PATTERN = r"^https?:[^\s]+?\.[^\s]+?"
CONFIG_URL_ILLEGAL_PATTERN = r"\.(cab|iso|zip|rar|tar|gz|bz2|7z|tgz|apk|exe|app|pkg|bmg|rpm|deb|dmg|jar|jad|bin|msi|" \
"pdf|doc|docx|xls|xlsx|ppt|pptx|txt|md|odf|odt|rtf|py|java|c|cc|js|css|log|csv|tsv|" \
"jpg|jpeg|png|gif|bmp|xpm|xbm|ico|drm|dxf|eps|psd|pcd|pcx|tif|tiff|" \
"mp3|mp4|swf|mkv|avi|flv|mov|wmv|wma|3gp|mpg|mpeg|mp4a|wav|ogg|rmvb)$"
| """
util_config.py by xianhu
"""
__all__ = ['CONFIG_FETCH_MESSAGE', 'CONFIG_PARSE_MESSAGE', 'CONFIG_MESSAGE_PATTERN', 'CONFIG_URL_LEGAL_PATTERN', 'CONFIG_URL_ILLEGAL_PATTERN']
config_fetch_message = 'priority=%s, keys=%s, deep=%s, repeat=%s, url=%s'
config_parse_message = 'priority=%s, keys=%s, deep=%s, url=%s'
config_message_pattern = 'priority=(?P<priority>\\d+),\\s*keys=(?P<keys>.+?),\\s*deep=(?P<deep>\\d+),\\s*(repeat=(?P<repeat>\\d+),\\s*)?url=(?P<url>.+)$'
config_url_legal_pattern = '^https?:[^\\s]+?\\.[^\\s]+?'
config_url_illegal_pattern = '\\.(cab|iso|zip|rar|tar|gz|bz2|7z|tgz|apk|exe|app|pkg|bmg|rpm|deb|dmg|jar|jad|bin|msi|pdf|doc|docx|xls|xlsx|ppt|pptx|txt|md|odf|odt|rtf|py|java|c|cc|js|css|log|csv|tsv|jpg|jpeg|png|gif|bmp|xpm|xbm|ico|drm|dxf|eps|psd|pcd|pcx|tif|tiff|mp3|mp4|swf|mkv|avi|flv|mov|wmv|wma|3gp|mpg|mpeg|mp4a|wav|ogg|rmvb)$' |
__title__ = 'The Onion Box'
__description__ = 'Dashboard to monitor Tor node operations.'
__version__ = '20.2'
__stamp__ = '20200119|095654'
| __title__ = 'The Onion Box'
__description__ = 'Dashboard to monitor Tor node operations.'
__version__ = '20.2'
__stamp__ = '20200119|095654' |
# This is the word list from where the answers for the hangman game will come from.
word_list = [
2015,
"Fred Swaniker",
"Rwanda and Mauritius",
2,
"Dr, Gaidi Faraj",
"Sila Ogidi",
"Madagascar",
94,
8,
"Mauritius"
]
# Here we are defining the variables 'Right'(for when they get the question correct) and \n
# 'tries'(for when they get a question wrong).
Right = 0
tries = 0
# This function below after called, will greet the user when they input their name.
def greet(name):
print("Hello " + name + " welcome to hangman and good luck!")
user_name = input("What is your name?")
greet(user_name)
# This functions below when called, will check when guess is returned whether the user's guess is in the word_list\n
# or not and will print out the appropriate responses while consecutively adding to the 'Right' or 'tries' variable.
def alu(guess):
if guess in word_list:
print("congrats!")
def check(guess):
if guess not in word_list:
print("Wrong")
return guess
guess1 = int(input("When was ALU founded?"))
if alu(guess1):
Right += 1
else:
check(guess1)
tries += 1
guess2 = input("Who is the CEO of ALU")
if alu(guess2):
Right += 1
else:
check(guess2)
tries += 1
guess3 = input("Where are ALU campuses?")
if alu(guess3):
Right += 1
else:
check(guess3)
tries += 1
guess4 = int(input("How many campuses does ALU have?"))
if alu(guess4):
Right += 1
else:
check(guess4)
tries += 1
guess5 = input("What is the name of ALU Rwanda's Dean?")
if alu(guess5):
Right += 1
else:
check(guess5)
tries += 1
guess6 = input("Who is in charge of Student Life?")
if alu(guess6):
Right += 1
else:
check(guess6)
tries += 1
if tries == 6:
exit("You lost")
guess7 = input("What is the name of our Lab?")
if alu(guess7):
Right += 1
else:
check(guess7)
tries += 1
if tries == 6:
exit("You lost")
guess8 = int(input("How many students do we have in Year 2 CS?"))
if alu(guess8):
Right += 1
else:
check(guess8)
tries += 1
if tries == 6:
exit("You lost")
guess9 = int(input("How many degrees does ALU offer?"))
if alu(guess9):
Right += 1
else:
check(guess9)
tries += 1
if tries == 6:
exit("You lost")
guess10 = input("Where are the headquarters of ALU?")
if alu(guess10):
Right += 1
else:
check(guess10)
tries += 1
if tries == 6:
exit("You lost")
| word_list = [2015, 'Fred Swaniker', 'Rwanda and Mauritius', 2, 'Dr, Gaidi Faraj', 'Sila Ogidi', 'Madagascar', 94, 8, 'Mauritius']
right = 0
tries = 0
def greet(name):
print('Hello ' + name + ' welcome to hangman and good luck!')
user_name = input('What is your name?')
greet(user_name)
def alu(guess):
if guess in word_list:
print('congrats!')
def check(guess):
if guess not in word_list:
print('Wrong')
return guess
guess1 = int(input('When was ALU founded?'))
if alu(guess1):
right += 1
else:
check(guess1)
tries += 1
guess2 = input('Who is the CEO of ALU')
if alu(guess2):
right += 1
else:
check(guess2)
tries += 1
guess3 = input('Where are ALU campuses?')
if alu(guess3):
right += 1
else:
check(guess3)
tries += 1
guess4 = int(input('How many campuses does ALU have?'))
if alu(guess4):
right += 1
else:
check(guess4)
tries += 1
guess5 = input("What is the name of ALU Rwanda's Dean?")
if alu(guess5):
right += 1
else:
check(guess5)
tries += 1
guess6 = input('Who is in charge of Student Life?')
if alu(guess6):
right += 1
else:
check(guess6)
tries += 1
if tries == 6:
exit('You lost')
guess7 = input('What is the name of our Lab?')
if alu(guess7):
right += 1
else:
check(guess7)
tries += 1
if tries == 6:
exit('You lost')
guess8 = int(input('How many students do we have in Year 2 CS?'))
if alu(guess8):
right += 1
else:
check(guess8)
tries += 1
if tries == 6:
exit('You lost')
guess9 = int(input('How many degrees does ALU offer?'))
if alu(guess9):
right += 1
else:
check(guess9)
tries += 1
if tries == 6:
exit('You lost')
guess10 = input('Where are the headquarters of ALU?')
if alu(guess10):
right += 1
else:
check(guess10)
tries += 1
if tries == 6:
exit('You lost') |
OS_MA_NFVO_IP = '192.168.1.197'
OS_USER_DOMAIN_NAME = 'Default'
OS_USERNAME = 'admin'
OS_PASSWORD = '0000'
OS_PROJECT_DOMAIN_NAME = 'Default'
OS_PROJECT_NAME = 'admin' | os_ma_nfvo_ip = '192.168.1.197'
os_user_domain_name = 'Default'
os_username = 'admin'
os_password = '0000'
os_project_domain_name = 'Default'
os_project_name = 'admin' |
# Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_pub_uri = "https://storage.googleapis.com/pub.dartlang.org/packages"
"""A set of BUILD rules that facilitate using or building on "pub"."""
def _pub_repository_impl(repository_ctx):
package = repository_ctx.attr.package
version = repository_ctx.attr.version
repository_ctx.download_and_extract(
"%s/%s-%s.tar.gz" % (_pub_uri, package, version),
repository_ctx.attr.output,
)
pub_deps = repository_ctx.attr.pub_deps
bazel_deps = ["\"@vendor_%s//:%s\"" % (dep, dep) for dep in pub_deps]
deps = ",\n".join(bazel_deps)
repository_ctx.file(
"%s/BUILD" % (repository_ctx.attr.output),
"""
load("@io_bazel_rules_dart//dart/build_rules:core.bzl", "dart_library")
package(default_visibility = ["//visibility:public"])
filegroup(name = "LICENSE_FILES", srcs=["LICENSE"])
dart_library(
name = "%s",
srcs = glob(["lib/**"]),
license_files = ["LICENSE"],
pub_pkg_name = "%s",
deps = [
%s
],
)
""" % (package, package, deps),
)
pub_repository = repository_rule(
attrs = {
"output": attr.string(),
"package": attr.string(mandatory = True),
"version": attr.string(mandatory = True),
"pub_deps": attr.string_list(default = []),
},
implementation = _pub_repository_impl,
)
| _pub_uri = 'https://storage.googleapis.com/pub.dartlang.org/packages'
'A set of BUILD rules that facilitate using or building on "pub".'
def _pub_repository_impl(repository_ctx):
package = repository_ctx.attr.package
version = repository_ctx.attr.version
repository_ctx.download_and_extract('%s/%s-%s.tar.gz' % (_pub_uri, package, version), repository_ctx.attr.output)
pub_deps = repository_ctx.attr.pub_deps
bazel_deps = ['"@vendor_%s//:%s"' % (dep, dep) for dep in pub_deps]
deps = ',\n'.join(bazel_deps)
repository_ctx.file('%s/BUILD' % repository_ctx.attr.output, '\nload("@io_bazel_rules_dart//dart/build_rules:core.bzl", "dart_library")\n\npackage(default_visibility = ["//visibility:public"])\n\nfilegroup(name = "LICENSE_FILES", srcs=["LICENSE"])\n\ndart_library(\n name = "%s",\n srcs = glob(["lib/**"]),\n license_files = ["LICENSE"],\n pub_pkg_name = "%s",\n deps = [\n %s\n ],\n)\n\n' % (package, package, deps))
pub_repository = repository_rule(attrs={'output': attr.string(), 'package': attr.string(mandatory=True), 'version': attr.string(mandatory=True), 'pub_deps': attr.string_list(default=[])}, implementation=_pub_repository_impl) |
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if len(nums) < 1:
raise Exception("Invalid Array")
n = len(nums)
res = []
s = set()
for x in nums:
s.add(x)
for i in range(1, n + 1):
if i not in s:
res.append(i)
return res
| class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
if len(nums) < 1:
raise exception('Invalid Array')
n = len(nums)
res = []
s = set()
for x in nums:
s.add(x)
for i in range(1, n + 1):
if i not in s:
res.append(i)
return res |
'''
03 - Multiple arguments
In the previous exercise, the square brackets around imag in the documentation showed us that the
imag argument is optional. But Python also uses a different way to tell users about arguments being
optional.
Have a look at the documentation of sorted() by typing help(sorted) in the IPython Shell.
You'll see that sorted() takes three arguments: iterable, key and reverse.
key=None means that if you don't specify the key argument, it will be None. reverse=False means
that if you don't specify the reverse argument, it will be False.
In this exercise, you'll only have to specify iterable and reverse, not key. The first input you
pass to sorted() will be matched to the iterable argument, but what about the second input? To tell
Python you want to specify reverse without changing anything about key, you can use =:
sorted(___, reverse = ___)
Two lists have been created for you on the right. Can you paste them together and sort them in
descending order?
Note: For now, we can understand an iterable as being any collection of objects, e.g. a List.
Instructions:
- Use + to merge the contents of first and second into a new list: full.
- Call sorted() on full and specify the reverse argument to be True. Save the sorted list as
full_sorted.
- Finish off by printing out full_sorted.
'''
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and second: full
full = first + second
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True)
# Print out full_sorted
print(full_sorted) | """
03 - Multiple arguments
In the previous exercise, the square brackets around imag in the documentation showed us that the
imag argument is optional. But Python also uses a different way to tell users about arguments being
optional.
Have a look at the documentation of sorted() by typing help(sorted) in the IPython Shell.
You'll see that sorted() takes three arguments: iterable, key and reverse.
key=None means that if you don't specify the key argument, it will be None. reverse=False means
that if you don't specify the reverse argument, it will be False.
In this exercise, you'll only have to specify iterable and reverse, not key. The first input you
pass to sorted() will be matched to the iterable argument, but what about the second input? To tell
Python you want to specify reverse without changing anything about key, you can use =:
sorted(___, reverse = ___)
Two lists have been created for you on the right. Can you paste them together and sort them in
descending order?
Note: For now, we can understand an iterable as being any collection of objects, e.g. a List.
Instructions:
- Use + to merge the contents of first and second into a new list: full.
- Call sorted() on full and specify the reverse argument to be True. Save the sorted list as
full_sorted.
- Finish off by printing out full_sorted.
"""
first = [11.25, 18.0, 20.0]
second = [10.75, 9.5]
full = first + second
full_sorted = sorted(full, reverse=True)
print(full_sorted) |
parameters = {}
genome = {}
genome_stats = {}
genome_test_stats = []
brain = {}
cortical_list = []
cortical_map = {}
intercortical_mapping = []
block_dic = {}
upstream_neurons = {}
memory_list = {}
activity_stats = {}
temp_neuron_list = []
original_genome_id = []
fire_list = []
termination_flag = False
variation_counter_actual = 0
exposure_counter_actual = 0
mnist_training = {}
mnist_testing = {}
top_10_utf_memory_neurons = {}
top_10_utf_neurons = {}
v1_members = []
prunning_candidates = set()
genome_id = ""
event_id = '_'
blueprint = ""
comprehension_queue = ''
working_directory = ''
connectome_path = ''
paths = {}
watchdog_queue = ''
exit_condition = False
fcl_queue = ''
proximity_queue = ''
last_ipu_activity = ''
last_alertness_trigger = ''
influxdb = ''
mongodb = ''
running_in_container = False
hardware = ''
gazebo = False
stimulation_data = {}
hw_controller_path = ''
hw_controller = None
opu_pub = None
router_address = None
burst_timer = 1
# rules = ""
brain_is_running = False
# live_mode_status can have modes of idle, learning, testing, tbd
live_mode_status = 'idle'
fcl_history = {}
brain_run_id = ""
burst_detection_list = {}
burst_count = 0
fire_candidate_list = {}
previous_fcl = {}
future_fcl = {}
labeled_image = []
training_neuron_list_utf = {}
training_neuron_list_img = {}
empty_fcl_counter = 0
neuron_mp_list = []
pain_flag = False
cumulative_neighbor_count = 0
time_neuron_update = ''
time_apply_plasticity_ext = ''
plasticity_time_total = None
plasticity_time_total_p1 = None
plasticity_dict = {}
tester_test_stats = {}
# Flags
flag_ready_to_inject_image = False
| parameters = {}
genome = {}
genome_stats = {}
genome_test_stats = []
brain = {}
cortical_list = []
cortical_map = {}
intercortical_mapping = []
block_dic = {}
upstream_neurons = {}
memory_list = {}
activity_stats = {}
temp_neuron_list = []
original_genome_id = []
fire_list = []
termination_flag = False
variation_counter_actual = 0
exposure_counter_actual = 0
mnist_training = {}
mnist_testing = {}
top_10_utf_memory_neurons = {}
top_10_utf_neurons = {}
v1_members = []
prunning_candidates = set()
genome_id = ''
event_id = '_'
blueprint = ''
comprehension_queue = ''
working_directory = ''
connectome_path = ''
paths = {}
watchdog_queue = ''
exit_condition = False
fcl_queue = ''
proximity_queue = ''
last_ipu_activity = ''
last_alertness_trigger = ''
influxdb = ''
mongodb = ''
running_in_container = False
hardware = ''
gazebo = False
stimulation_data = {}
hw_controller_path = ''
hw_controller = None
opu_pub = None
router_address = None
burst_timer = 1
brain_is_running = False
live_mode_status = 'idle'
fcl_history = {}
brain_run_id = ''
burst_detection_list = {}
burst_count = 0
fire_candidate_list = {}
previous_fcl = {}
future_fcl = {}
labeled_image = []
training_neuron_list_utf = {}
training_neuron_list_img = {}
empty_fcl_counter = 0
neuron_mp_list = []
pain_flag = False
cumulative_neighbor_count = 0
time_neuron_update = ''
time_apply_plasticity_ext = ''
plasticity_time_total = None
plasticity_time_total_p1 = None
plasticity_dict = {}
tester_test_stats = {}
flag_ready_to_inject_image = False |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio']
class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math': 65 , 'English': 70 , 'History': 80 , 'French': 70 , 'Science': 60}
total = sum(courses.values())
print(total)
percentage = total/500*100
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = { 'Geoffrey Hinton' : 78, 'Andrew Ng' : 95, 'Sebastian Raschka' : 65 ,
'Yoshua Benjio' : 50 , 'Hilary Mason' : 70 , 'Corinna Cortes' : 66 , 'Peter Warden' : 75}
max_marks_scored = max(mathematics, key=mathematics.get)
print(max_marks_scored)
topper = max_marks_scored
print(topper)
# Code ends here
# --------------
# Given string
topper = ' andrew ng'
# Code starts here
first_name = topper.split()[0]
print(first_name)
last_name = topper.split()[1]
print(last_name)
full_name = last_name +' '+ first_name
print(full_name)
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
| class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60}
total = sum(courses.values())
print(total)
percentage = total / 500 * 100
print(percentage)
mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 66, 'Peter Warden': 75}
max_marks_scored = max(mathematics, key=mathematics.get)
print(max_marks_scored)
topper = max_marks_scored
print(topper)
topper = ' andrew ng'
first_name = topper.split()[0]
print(first_name)
last_name = topper.split()[1]
print(last_name)
full_name = last_name + ' ' + first_name
print(full_name)
certificate_name = full_name.upper()
print(certificate_name) |
n = int(input().strip())
items = [
int(A_temp)
for A_temp
in input().strip().split(' ')
]
items_map = {}
result = None
for i, item in enumerate(items):
if item not in items_map:
items_map[item] = [i]
else:
items_map[item].append(i)
for _, item_indexes in items_map.items():
items_indexes_length = len(item_indexes)
if items_indexes_length > 1:
for i in range(items_indexes_length):
for j in range(i + 1, items_indexes_length):
diff = item_indexes[j] - item_indexes[i]
if result is None:
result = diff
elif diff < result:
result = diff
print(result if result else -1)
| n = int(input().strip())
items = [int(A_temp) for a_temp in input().strip().split(' ')]
items_map = {}
result = None
for (i, item) in enumerate(items):
if item not in items_map:
items_map[item] = [i]
else:
items_map[item].append(i)
for (_, item_indexes) in items_map.items():
items_indexes_length = len(item_indexes)
if items_indexes_length > 1:
for i in range(items_indexes_length):
for j in range(i + 1, items_indexes_length):
diff = item_indexes[j] - item_indexes[i]
if result is None:
result = diff
elif diff < result:
result = diff
print(result if result else -1) |
"""A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
# No entry left
if not queryset.filter(pk__gt=start_pk).exists():
break
try:
# Fetch chunk_size entries if possible
end_pk = queryset.filter(pk__gt=start_pk).values_list(
'pk', flat=True)[chunk_size - 1]
# Fetch rest entries if less than chunk_size left
except IndexError:
end_pk = queryset.values_list('pk', flat=True).last()
yield queryset.filter(pk__gt=start_pk).filter(pk__lte=end_pk)
start_pk = end_pk
| """A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
if not queryset.filter(pk__gt=start_pk).exists():
break
try:
end_pk = queryset.filter(pk__gt=start_pk).values_list('pk', flat=True)[chunk_size - 1]
except IndexError:
end_pk = queryset.values_list('pk', flat=True).last()
yield queryset.filter(pk__gt=start_pk).filter(pk__lte=end_pk)
start_pk = end_pk |
def compareMetaboliteDicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compareMetabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_d2_keys[i]]:
return False
else:
return True
def compareMetabolites(met1, met2, naive=False):
if isinstance(met1, set):
return compareReactions(list(met1), list(met2), naive)
if isinstance(met1, list):
if not isinstance(met2, list):
return False
elif len(met1) != len(met2):
return False
else:
for i in range(len(met1)):
if not compareMetabolites(met1[i], met2[i], naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
elif not met1._bound == met2._bound:
return False
elif not met1._constraint_sense == met2._constraint_sense:
return False
#elif not met1.annotation == met2.annotation:
# return False
elif not met1.charge == met2.charge:
return False
elif not met1.compartment == met2.compartment:
return False
elif not met1.name == met2.name:
return False
elif not met1.compartment == met2.compartment:
return False
#elif not met1.notes == met2.notes:
# return False
elif not naive:
if not compareReactions(met1._reaction, met2._reaction, naive=True):
return False
elif not compareModels(met1._model, met2._model, naive=True):
return False
else:
return True
else:
return True
def compareReactions(r1, r2, naive=False):
if isinstance(r1, set):
return compareReactions(list(r1), list(r2), naive)
if isinstance(r1, list):
if not isinstance(r2, list):
return False
elif len(r1) != len(r2):
return False
else:
for i in range(len(r1)):
if not compareReactions(r1[i], r2[i],naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
#elif not r1._compartments == r2._compartments:
# return False
#elif not r1._forward_variable == r2._forward_variable:
# return False
elif not r1._gene_reaction_rule == r2._gene_reaction_rule:
return False
elif not r1._id == r2._id:
return False
elif not r1._lower_bound == r2._lower_bound:
return False
#elif not r1._model == r2._model:
# return False
#elif not r1._reverse_variable == r2._reverse_variable:
# return False
elif not r1._upper_bound == r2._upper_bound:
return False
#elif not r1.annotation == r2.annotation:
# return False
elif not r1.name== r2.name:
return False
#elif not r1.notes == r2.notes:
# return False
elif not r1.subsystem == r2.subsystem:
return False
elif not r1.variable_kind == r2.variable_kind:
return False
elif not naive:
if not compareMetaboliteDicts(r1._metabolites, r2._metabolites):
return False
elif not compareGenes(r1._genes,r2._genes, naive=True):
return False
else:
return True
else:
return True
def compareGenes(g1, g2, naive=False):
if isinstance(g1, set):
return compareGenes(list(g1), list(g2), naive)
if isinstance(g1, list):
if not isinstance(g2, list):
return False
elif len(g1) != len(g2):
return False
else:
for i in range(len(g1)):
if not compareGenes(g1[i], g2[i], naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
elif not g1._functional == g2._functional:
return False
elif not g1._id == g2._id:
return False
#elif not g1._model == g2._model:
# return False
elif not g1.annotation == g2.annotation:
return False
elif not g1.name == g2.name:
return False
#elif not g1.notes == g2.notes:
# return False
elif not naive:
if not compareReactions(g1._reaction,g2._reaction, naive=True):
return False
else:
return True
else:
return True
def compareModels(m1, m2, naive=False):
if not True:
#can never be entered
pass
#elif not m1._compartments == m2._compartments:
# return False
#elif not m1._contexts == m2._contexts:
# return False
#elif not m1._solver == m2._solver:
# return False
elif not m1._id == m2._id:
return False
#elif not m1._trimmed == m2.trimmed:
# return False
#elif not m1._trimmed_genes == m2._trimmed_genes:
# return False
#elif not m1._trimmed_reactions == m2._trimmed_reactions:
# return False
#elif not m1.annotation == m2.annotation:
# return False
elif not m1.bounds == m2.bounds:
return False
elif not m1.name == m2.name:
return False
#elif not m1.notes == m2.notes:
# return False
#elif not m1.quadratic_component == m2.quadratic_component:
# return False
elif not naive:
if not compareGenes(m1.genes, m2.genes):
return False
elif not compareMetabolites(m1.metabolites, m2.metabolites):
return False
elif not compareReactions(m1.reactions,m2.reactions):
return False
else:
return True
else:
return True
| def compare_metabolite_dicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compare_metabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_d2_keys[i]]:
return False
else:
return True
def compare_metabolites(met1, met2, naive=False):
if isinstance(met1, set):
return compare_reactions(list(met1), list(met2), naive)
if isinstance(met1, list):
if not isinstance(met2, list):
return False
elif len(met1) != len(met2):
return False
else:
for i in range(len(met1)):
if not compare_metabolites(met1[i], met2[i], naive):
return False
else:
return True
elif not True:
pass
elif not met1._bound == met2._bound:
return False
elif not met1._constraint_sense == met2._constraint_sense:
return False
elif not met1.charge == met2.charge:
return False
elif not met1.compartment == met2.compartment:
return False
elif not met1.name == met2.name:
return False
elif not met1.compartment == met2.compartment:
return False
elif not naive:
if not compare_reactions(met1._reaction, met2._reaction, naive=True):
return False
elif not compare_models(met1._model, met2._model, naive=True):
return False
else:
return True
else:
return True
def compare_reactions(r1, r2, naive=False):
if isinstance(r1, set):
return compare_reactions(list(r1), list(r2), naive)
if isinstance(r1, list):
if not isinstance(r2, list):
return False
elif len(r1) != len(r2):
return False
else:
for i in range(len(r1)):
if not compare_reactions(r1[i], r2[i], naive):
return False
else:
return True
elif not True:
pass
elif not r1._gene_reaction_rule == r2._gene_reaction_rule:
return False
elif not r1._id == r2._id:
return False
elif not r1._lower_bound == r2._lower_bound:
return False
elif not r1._upper_bound == r2._upper_bound:
return False
elif not r1.name == r2.name:
return False
elif not r1.subsystem == r2.subsystem:
return False
elif not r1.variable_kind == r2.variable_kind:
return False
elif not naive:
if not compare_metabolite_dicts(r1._metabolites, r2._metabolites):
return False
elif not compare_genes(r1._genes, r2._genes, naive=True):
return False
else:
return True
else:
return True
def compare_genes(g1, g2, naive=False):
if isinstance(g1, set):
return compare_genes(list(g1), list(g2), naive)
if isinstance(g1, list):
if not isinstance(g2, list):
return False
elif len(g1) != len(g2):
return False
else:
for i in range(len(g1)):
if not compare_genes(g1[i], g2[i], naive):
return False
else:
return True
elif not True:
pass
elif not g1._functional == g2._functional:
return False
elif not g1._id == g2._id:
return False
elif not g1.annotation == g2.annotation:
return False
elif not g1.name == g2.name:
return False
elif not naive:
if not compare_reactions(g1._reaction, g2._reaction, naive=True):
return False
else:
return True
else:
return True
def compare_models(m1, m2, naive=False):
if not True:
pass
elif not m1._id == m2._id:
return False
elif not m1.bounds == m2.bounds:
return False
elif not m1.name == m2.name:
return False
elif not naive:
if not compare_genes(m1.genes, m2.genes):
return False
elif not compare_metabolites(m1.metabolites, m2.metabolites):
return False
elif not compare_reactions(m1.reactions, m2.reactions):
return False
else:
return True
else:
return True |
class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
user_id, session_id = str(user_id), str(session_id)
session_type = self.get_type()
strings = []
for event, product in self:
columns = [user_id, session_type, session_id, event, str(product)]
strings.append(','.join(columns))
return strings
def get_type(self):
raise NotImplemented
class OrganicSessions(Session):
def __init__(self):
super(OrganicSessions, self).__init__()
def next(self, context, product):
self.append(
{
't': context.time(),
'u': context.user(),
'z': 'pageview',
'v': product
}
)
def get_type(self):
return 'organic'
def get_views(self):
return [p for _, _, e, p in self if e == 'pageview']
| class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
(user_id, session_id) = (str(user_id), str(session_id))
session_type = self.get_type()
strings = []
for (event, product) in self:
columns = [user_id, session_type, session_id, event, str(product)]
strings.append(','.join(columns))
return strings
def get_type(self):
raise NotImplemented
class Organicsessions(Session):
def __init__(self):
super(OrganicSessions, self).__init__()
def next(self, context, product):
self.append({'t': context.time(), 'u': context.user(), 'z': 'pageview', 'v': product})
def get_type(self):
return 'organic'
def get_views(self):
return [p for (_, _, e, p) in self if e == 'pageview'] |
"""Recursive implementations."""
def find_max(A):
"""invoke recursive function to find maximum value in A."""
def rmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi: return A[lo]
mid = (lo+hi) // 2
L = rmax(lo, mid)
R = rmax(mid+1, hi)
return max(L, R)
return rmax(0, len(A)-1)
def find_max_with_count(A):
"""Count number of comparisons."""
def frmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1] incl. count"""
if lo == hi: return (0, A[lo])
mid = (lo+hi)//2
ctleft,left = frmax(lo, mid)
ctright,right = frmax(mid+1, hi)
return (1+ctleft+ctright, max(left, right))
return frmax(0, len(A)-1)
def count(A,target):
"""invoke recursive function to return number of times target appears in A."""
def rcount(lo, hi, target):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return 1 if A[lo] == target else 0
mid = (lo+hi)//2
left = rcount(lo, mid, target)
right = rcount(mid+1, hi, target)
return left + right
return rcount(0, len(A)-1, target)
| """Recursive implementations."""
def find_max(A):
"""invoke recursive function to find maximum value in A."""
def rmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return A[lo]
mid = (lo + hi) // 2
l = rmax(lo, mid)
r = rmax(mid + 1, hi)
return max(L, R)
return rmax(0, len(A) - 1)
def find_max_with_count(A):
"""Count number of comparisons."""
def frmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1] incl. count"""
if lo == hi:
return (0, A[lo])
mid = (lo + hi) // 2
(ctleft, left) = frmax(lo, mid)
(ctright, right) = frmax(mid + 1, hi)
return (1 + ctleft + ctright, max(left, right))
return frmax(0, len(A) - 1)
def count(A, target):
"""invoke recursive function to return number of times target appears in A."""
def rcount(lo, hi, target):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return 1 if A[lo] == target else 0
mid = (lo + hi) // 2
left = rcount(lo, mid, target)
right = rcount(mid + 1, hi, target)
return left + right
return rcount(0, len(A) - 1, target) |
"""ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = 'Statistics Norway (ssb.no)'
__all__ = []
| """ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = 'Statistics Norway (ssb.no)'
__all__ = [] |
problem_type = "segmentation"
dataset_name = "synthia_rand_cityscapes"
dataset_name2 = None
perc_mb2 = None
model_name = "resnetFCN"
freeze_layers_from = None
show_model = False
load_imageNet = True
load_pretrained = False
weights_file = "weights.hdf5"
train_model = True
test_model = True
pred_model = False
debug = True
debug_images_train = 50
debug_images_valid = 50
debug_images_test = 50
debug_n_epochs = 2
batch_size_train = 2
batch_size_valid = 2
batch_size_test = 2
crop_size_train = (512, 512)
crop_size_valid = None
crop_size_test = None
resize_train = None
resize_valid = None
resize_test = None
shuffle_train = True
shuffle_valid = False
shuffle_test = False
seed_train = 1924
seed_valid = 1924
seed_test = 1924
optimizer = "rmsprop"
learning_rate = 0.0001
weight_decay = 0.0
n_epochs = 1000
save_results_enabled = True
save_results_nsamples = 5
save_results_batch_size = 5
save_results_n_legend_rows = 1
earlyStopping_enabled = True
earlyStopping_monitor = "val_jaccard"
earlyStopping_mode = "max"
earlyStopping_patience = 50
earlyStopping_verbose = 0
checkpoint_enabled = True
checkpoint_monitor = "val_jaccard"
checkpoint_mode = "max"
checkpoint_save_best_only = True
checkpoint_save_weights_only = True
checkpoint_verbose = 0
plotHist_enabled = True
plotHist_verbose = 0
LRScheduler_enabled = True
LRScheduler_batch_epoch = "batch"
LRScheduler_type = "poly"
LRScheduler_M = 75000
LRScheduler_decay = 0.1
LRScheduler_S = 10000
LRScheduler_power = 0.9
TensorBoard_enabled = True
TensorBoard_histogram_freq = 1
TensorBoard_write_graph = True
TensorBoard_write_images = False
TensorBoard_logs_folder = None
norm_imageNet_preprocess = True
norm_fit_dataset = False
norm_rescale = 1
norm_featurewise_center = False
norm_featurewise_std_normalization = False
norm_samplewise_center = False
norm_samplewise_std_normalization = False
norm_gcn = False
norm_zca_whitening = False
cb_weights_method = None
da_rotation_range = 0
da_width_shift_range = 0.0
da_height_shift_range = 0.0
da_shear_range = 0.0
da_zoom_range = 0.5
da_channel_shift_range = 0.0
da_fill_mode = "constant"
da_cval = 0.0
da_horizontal_flip = True
da_vertical_flip = False
da_spline_warp = False
da_warp_sigma = 10
da_warp_grid_size = 3
da_save_to_dir = False | problem_type = 'segmentation'
dataset_name = 'synthia_rand_cityscapes'
dataset_name2 = None
perc_mb2 = None
model_name = 'resnetFCN'
freeze_layers_from = None
show_model = False
load_image_net = True
load_pretrained = False
weights_file = 'weights.hdf5'
train_model = True
test_model = True
pred_model = False
debug = True
debug_images_train = 50
debug_images_valid = 50
debug_images_test = 50
debug_n_epochs = 2
batch_size_train = 2
batch_size_valid = 2
batch_size_test = 2
crop_size_train = (512, 512)
crop_size_valid = None
crop_size_test = None
resize_train = None
resize_valid = None
resize_test = None
shuffle_train = True
shuffle_valid = False
shuffle_test = False
seed_train = 1924
seed_valid = 1924
seed_test = 1924
optimizer = 'rmsprop'
learning_rate = 0.0001
weight_decay = 0.0
n_epochs = 1000
save_results_enabled = True
save_results_nsamples = 5
save_results_batch_size = 5
save_results_n_legend_rows = 1
early_stopping_enabled = True
early_stopping_monitor = 'val_jaccard'
early_stopping_mode = 'max'
early_stopping_patience = 50
early_stopping_verbose = 0
checkpoint_enabled = True
checkpoint_monitor = 'val_jaccard'
checkpoint_mode = 'max'
checkpoint_save_best_only = True
checkpoint_save_weights_only = True
checkpoint_verbose = 0
plot_hist_enabled = True
plot_hist_verbose = 0
lr_scheduler_enabled = True
lr_scheduler_batch_epoch = 'batch'
lr_scheduler_type = 'poly'
lr_scheduler_m = 75000
lr_scheduler_decay = 0.1
lr_scheduler_s = 10000
lr_scheduler_power = 0.9
tensor_board_enabled = True
tensor_board_histogram_freq = 1
tensor_board_write_graph = True
tensor_board_write_images = False
tensor_board_logs_folder = None
norm_image_net_preprocess = True
norm_fit_dataset = False
norm_rescale = 1
norm_featurewise_center = False
norm_featurewise_std_normalization = False
norm_samplewise_center = False
norm_samplewise_std_normalization = False
norm_gcn = False
norm_zca_whitening = False
cb_weights_method = None
da_rotation_range = 0
da_width_shift_range = 0.0
da_height_shift_range = 0.0
da_shear_range = 0.0
da_zoom_range = 0.5
da_channel_shift_range = 0.0
da_fill_mode = 'constant'
da_cval = 0.0
da_horizontal_flip = True
da_vertical_flip = False
da_spline_warp = False
da_warp_sigma = 10
da_warp_grid_size = 3
da_save_to_dir = False |
{
"targets": [
{
"target_name": "cclust",
"sources": [ "./src/heatmap_clustering_js_module.cpp" ],
'dependencies': ['bonsaiclust']
},
{
'target_name': 'bonsaiclust',
'type': 'static_library',
'sources': [ 'src/cluster.c' ],
'cflags': ['-fPIC', '-I', '-pedantic', '-Wall']
}
]
}
| {'targets': [{'target_name': 'cclust', 'sources': ['./src/heatmap_clustering_js_module.cpp'], 'dependencies': ['bonsaiclust']}, {'target_name': 'bonsaiclust', 'type': 'static_library', 'sources': ['src/cluster.c'], 'cflags': ['-fPIC', '-I', '-pedantic', '-Wall']}]} |
#!/usr/bin/env python3.8
table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}"
"\N{Devanagari digit two}\N{Devanagari digit three}"
"\N{Devanagari digit four}\N{Devanagari digit five}"
"\N{Devanagari digit six}\N{Devanagari digit seven}"
"\N{Devanagari digit eight}\N{Devanagari digit nine}")
print("0123456789".translate(table)) | table = ''.maketrans('0123456789', '०१२३४५६७८९')
print('0123456789'.translate(table)) |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AzureCloudCredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access key to use when
accessing a storage tier in a Azure cloud service.
storage_account_name (string): Specifies the account name to use when
accessing a storage tier in a Azure cloud service.
tier_type (TierTypeAzureCloudCredentialsEnum): Specifies the storage
class of Azure. AzureTierType specifies the storage class for
Azure. 'kAzureTierHot' indicates a tier type of Azure properties
that is accessed frequently. 'kAzureTierCool' indicates a tier
type of Azure properties that is accessed less frequently, and
stored for at least 30 days. 'kAzureTierArchive' indicates a tier
type of Azure properties that is accessed rarely and stored for at
least 180 days.
"""
# Create a mapping from Model property names to API property names
_names = {
"storage_access_key":'storageAccessKey',
"storage_account_name":'storageAccountName',
"tier_type":'tierType'
}
def __init__(self,
storage_access_key=None,
storage_account_name=None,
tier_type=None):
"""Constructor for the AzureCloudCredentials class"""
# Initialize members of the class
self.storage_access_key = storage_access_key
self.storage_account_name = storage_account_name
self.tier_type = tier_type
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
storage_access_key = dictionary.get('storageAccessKey')
storage_account_name = dictionary.get('storageAccountName')
tier_type = dictionary.get('tierType')
# Return an object of this model
return cls(storage_access_key,
storage_account_name,
tier_type)
| class Azurecloudcredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access key to use when
accessing a storage tier in a Azure cloud service.
storage_account_name (string): Specifies the account name to use when
accessing a storage tier in a Azure cloud service.
tier_type (TierTypeAzureCloudCredentialsEnum): Specifies the storage
class of Azure. AzureTierType specifies the storage class for
Azure. 'kAzureTierHot' indicates a tier type of Azure properties
that is accessed frequently. 'kAzureTierCool' indicates a tier
type of Azure properties that is accessed less frequently, and
stored for at least 30 days. 'kAzureTierArchive' indicates a tier
type of Azure properties that is accessed rarely and stored for at
least 180 days.
"""
_names = {'storage_access_key': 'storageAccessKey', 'storage_account_name': 'storageAccountName', 'tier_type': 'tierType'}
def __init__(self, storage_access_key=None, storage_account_name=None, tier_type=None):
"""Constructor for the AzureCloudCredentials class"""
self.storage_access_key = storage_access_key
self.storage_account_name = storage_account_name
self.tier_type = tier_type
@classmethod
def from_dictionary(cls, dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
storage_access_key = dictionary.get('storageAccessKey')
storage_account_name = dictionary.get('storageAccountName')
tier_type = dictionary.get('tierType')
return cls(storage_access_key, storage_account_name, tier_type) |
__author__ = 'Riccardo Frigerio'
'''
Oggetto HOST
Attributi:
- mac_address: indirizzo MAC
- port: porta a cui e' collegato
- dpid: switch a cui e' collegato
'''
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dpid
| __author__ = 'Riccardo Frigerio'
"\nOggetto HOST\nAttributi:\n- mac_address: indirizzo MAC\n- port: porta a cui e' collegato\n- dpid: switch a cui e' collegato\n"
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dpid |
"""
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
| """
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
""" |
# nested loops = The "inner loop" will finish all of it's iterations before
# finishing one iteration of the "outer loop"
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")
#symbol = int(input("Enter a symbol to use: "))
for i in range(rows):
for j in range(columns):
print(symbol, end="")
print() | rows = int(input('How many rows?: '))
columns = int(input('How many columns?: '))
symbol = input('Enter a symbol to use: ')
for i in range(rows):
for j in range(columns):
print(symbol, end='')
print() |
# -*- coding: utf-8 -*-
"""Top-level package for Music Downloader Telegram Bot."""
# version as tuple for simple comparisons
VERSION = (0, 9, 16)
__author__ = """George Pchelkin"""
__email__ = 'george@pchelk.in'
# string created from tuple to avoid inconsistency
__version__ = ".".join([str(x) for x in VERSION])
| """Top-level package for Music Downloader Telegram Bot."""
version = (0, 9, 16)
__author__ = 'George Pchelkin'
__email__ = 'george@pchelk.in'
__version__ = '.'.join([str(x) for x in VERSION]) |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py'
]
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k_20220119-5b4887a0.pth' # noqa
model = dict(
backbone=dict(
_delete_=True,
type='EfficientNet',
arch='b3',
drop_path_rate=0.2,
out_indices=(3, 4, 5),
frozen_stages=0,
norm_cfg=dict(
type='SyncBN', requires_grad=True, eps=1e-3, momentum=0.01),
norm_eval=False,
init_cfg=dict(
type='Pretrained', prefix='backbone', checkpoint=checkpoint)),
neck=dict(
in_channels=[48, 136, 384],
start_level=0,
out_channels=256,
relu_before_extra_convs=True,
no_norm_on_lateral=True,
norm_cfg=norm_cfg),
bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg),
# training and testing settings
train_cfg=dict(assigner=dict(neg_iou_thr=0.5)))
# dataset settings
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
img_size = (896, 896)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=img_size,
ratio_range=(0.8, 1.2),
keep_ratio=True),
dict(type='RandomCrop', crop_size=img_size),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size=img_size),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=img_size,
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size=img_size),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=4,
workers_per_gpu=4,
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline))
# optimizer
optimizer_config = dict(grad_clip=None)
optimizer = dict(
type='SGD',
lr=0.04,
momentum=0.9,
weight_decay=0.0001,
paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=1000,
warmup_ratio=0.1,
step=[8, 11])
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=12)
# NOTE: This variable is for automatically scaling LR,
# USER SHOULD NOT CHANGE THIS VALUE.
default_batch_size = 32 # (8 GPUs) x (4 samples per GPU)
| _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py']
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k_20220119-5b4887a0.pth'
model = dict(backbone=dict(_delete_=True, type='EfficientNet', arch='b3', drop_path_rate=0.2, out_indices=(3, 4, 5), frozen_stages=0, norm_cfg=dict(type='SyncBN', requires_grad=True, eps=0.001, momentum=0.01), norm_eval=False, init_cfg=dict(type='Pretrained', prefix='backbone', checkpoint=checkpoint)), neck=dict(in_channels=[48, 136, 384], start_level=0, out_channels=256, relu_before_extra_convs=True, no_norm_on_lateral=True, norm_cfg=norm_cfg), bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg), train_cfg=dict(assigner=dict(neg_iou_thr=0.5)))
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
img_size = (896, 896)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=img_size, ratio_range=(0.8, 1.2), keep_ratio=True), dict(type='RandomCrop', crop_size=img_size), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=img_size), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])]
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=img_size, flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=img_size), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])]
data = dict(samples_per_gpu=4, workers_per_gpu=4, train=dict(pipeline=train_pipeline), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
optimizer_config = dict(grad_clip=None)
optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True))
lr_config = dict(policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=0.1, step=[8, 11])
runner = dict(type='EpochBasedRunner', max_epochs=12)
default_batch_size = 32 |
'''
1. Write a Python program to access a specific item in a singly linked list using index value.
2. Write a Python program to set a new value of an item in a singly linked list using index value.
3. Write a Python program to delete the first item from a singly linked list.
'''
| """
1. Write a Python program to access a specific item in a singly linked list using index value.
2. Write a Python program to set a new value of an item in a singly linked list using index value.
3. Write a Python program to delete the first item from a singly linked list.
""" |
"""
.. module:: aws_utilities_cli.iam
:platform: OS X
:synopsis: Small collection of utilities that
use the Amazon Web Services (AWS) SDK
.. moduleauthor:: dataday
"""
__all__ = ['generate_identity', 'generate_policy']
| """
.. module:: aws_utilities_cli.iam
:platform: OS X
:synopsis: Small collection of utilities that
use the Amazon Web Services (AWS) SDK
.. moduleauthor:: dataday
"""
__all__ = ['generate_identity', 'generate_policy'] |
class Node:
left = right = None
def __init__(self, data):
self.data = data
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
if root is None:
return Node(key)
if key < root.data:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def constructBST(keys):
root = None
for key in keys:
root = insert(root, key)
return root
if __name__ == '__main__':
keys = [15, 10, 20, 8, 12, 16, 25]
root = constructBST(keys)
inorder(root) | class Node:
left = right = None
def __init__(self, data):
self.data = data
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
if root is None:
return node(key)
if key < root.data:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def construct_bst(keys):
root = None
for key in keys:
root = insert(root, key)
return root
if __name__ == '__main__':
keys = [15, 10, 20, 8, 12, 16, 25]
root = construct_bst(keys)
inorder(root) |
class NoMessageRecipients(Exception):
"""
Raised when Message Recipients are not specified.
"""
pass
class InvalidAmount(Exception):
"""
Raised when an invalid currency amount is specified
"""
pass
| class Nomessagerecipients(Exception):
"""
Raised when Message Recipients are not specified.
"""
pass
class Invalidamount(Exception):
"""
Raised when an invalid currency amount is specified
"""
pass |
def something() -> None:
print("Andrew says: `something`.")
| def something() -> None:
print('Andrew says: `something`.') |
blacklist=set()
def get_blacklist():
return blacklist
def add_to_blacklist(jti):
return blacklist.add(jti)
| blacklist = set()
def get_blacklist():
return blacklist
def add_to_blacklist(jti):
return blacklist.add(jti) |
#unit
#mydict.py
class Dict(dict):
def __init__(self,**kw):
super(Dict,self).__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object han no attribute'%s'" %key)
def __setattr__(self,key,value):
self[key]=value
| class Dict(dict):
def __init__(self, **kw):
super(Dict, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise attribute_error("'Dict' object han no attribute'%s'" % key)
def __setattr__(self, key, value):
self[key] = value |
"""Translates validation error messages for the response"""
messages = {
'accepted': 'The :field: must be accepted.',
'after': 'The :field: must be a date after :other:.',
'alpha': 'The :field: may contain only letters.',
'alpha_dash': 'The :field: may only contain letters, numbers, and dashes.',
'alpha_num': 'The :field: may contain only letters and numbers.',
'array': 'The :field: must be an array.',
'before': 'The :field: must be a date before :other:.',
'between': 'The :field: must be between :least: and :most:.',
'between_string': 'The :field: must be between :least: and :most: characters.',
'between_numeric': 'The :field: must be between :least: and :most:.',
'boolean': 'The :field: must be either true or false.',
'confirmed': 'The :field: confirmation does not match.',
'date': 'The :field: is not a valid date.',
'different': 'The :field: and :other: must be different.',
'digits': 'The :field: must be :length: digits.',
'email': 'The :field: must be a valid email address.',
'exists': 'The selected :field: is invalid.',
'found_in': 'The selected :field: is invalid.',
'integer': 'The :field: must be an integer.',
'json': 'The :field: must be valid json format.',
'most_string': 'The :field: must not be greater than :most: characters.',
'most_numeric': 'The :field: must not be greater than :most:.',
'least_string': 'The :field: must be at least :least: characters.',
'least_numeric': 'The :field: must be at least :least:.',
'not_in': 'The selected :field: is invalid.',
'numeric': 'The :field: must be a number.',
'positive': 'The :field: must be a positive number.',
'regex': 'The :field: format is invalid.',
'required': 'The :field: field is required.',
'required_with': 'The :field: field is required when :other: is present.',
'required_without': 'The :field: field is required when :other: si not present.',
'same': 'The :field: and :other: must match.',
'size_string': 'The :field: must be :size: characters.',
'size_numeric': 'The :field: must be :size:.',
'string': 'The :field: must be a string.',
'unique': 'The :field: is already taken.',
'url': 'The :field: format is invalid.',
}
def trans(rule, fields):
message = messages[rule]
for k, v in fields.items():
message = message.replace(k, v).replace('_', ' ')
return message
| """Translates validation error messages for the response"""
messages = {'accepted': 'The :field: must be accepted.', 'after': 'The :field: must be a date after :other:.', 'alpha': 'The :field: may contain only letters.', 'alpha_dash': 'The :field: may only contain letters, numbers, and dashes.', 'alpha_num': 'The :field: may contain only letters and numbers.', 'array': 'The :field: must be an array.', 'before': 'The :field: must be a date before :other:.', 'between': 'The :field: must be between :least: and :most:.', 'between_string': 'The :field: must be between :least: and :most: characters.', 'between_numeric': 'The :field: must be between :least: and :most:.', 'boolean': 'The :field: must be either true or false.', 'confirmed': 'The :field: confirmation does not match.', 'date': 'The :field: is not a valid date.', 'different': 'The :field: and :other: must be different.', 'digits': 'The :field: must be :length: digits.', 'email': 'The :field: must be a valid email address.', 'exists': 'The selected :field: is invalid.', 'found_in': 'The selected :field: is invalid.', 'integer': 'The :field: must be an integer.', 'json': 'The :field: must be valid json format.', 'most_string': 'The :field: must not be greater than :most: characters.', 'most_numeric': 'The :field: must not be greater than :most:.', 'least_string': 'The :field: must be at least :least: characters.', 'least_numeric': 'The :field: must be at least :least:.', 'not_in': 'The selected :field: is invalid.', 'numeric': 'The :field: must be a number.', 'positive': 'The :field: must be a positive number.', 'regex': 'The :field: format is invalid.', 'required': 'The :field: field is required.', 'required_with': 'The :field: field is required when :other: is present.', 'required_without': 'The :field: field is required when :other: si not present.', 'same': 'The :field: and :other: must match.', 'size_string': 'The :field: must be :size: characters.', 'size_numeric': 'The :field: must be :size:.', 'string': 'The :field: must be a string.', 'unique': 'The :field: is already taken.', 'url': 'The :field: format is invalid.'}
def trans(rule, fields):
message = messages[rule]
for (k, v) in fields.items():
message = message.replace(k, v).replace('_', ' ')
return message |
"""
Commom settings to all applications
"""
A = 40.3
TECU = 1.0e16
C = 299792458
F1 = 1.57542e9
F2 = 1.22760e9
factor_1 = (F1 - F2) / (F1 + F2) / C
factor_2 = (F1 * F2) / (F2 - F1) / C
DIFF_TEC_MAX = 0.05
LIMIT_STD = 7.5
plot_it = True
REQUIRED_VERSION = 3.01
CONSTELLATIONS = ['G', 'R']
COLUMNS_IN_RINEX = {'3.03': {'G': {'L1': 'L1C', 'L2': 'L2W', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1C', 'L2': 'L2C', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
},
'3.02': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
},
'3.01': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
}
}
| """
Commom settings to all applications
"""
a = 40.3
tecu = 1e+16
c = 299792458
f1 = 1575420000.0
f2 = 1227600000.0
factor_1 = (F1 - F2) / (F1 + F2) / C
factor_2 = F1 * F2 / (F2 - F1) / C
diff_tec_max = 0.05
limit_std = 7.5
plot_it = True
required_version = 3.01
constellations = ['G', 'R']
columns_in_rinex = {'3.03': {'G': {'L1': 'L1C', 'L2': 'L2W', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'}, 'R': {'L1': 'L1C', 'L2': 'L2C', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}}, '3.02': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'}, 'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}}, '3.01': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'}, 'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}}} |
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dict_1 = {}
for i in s:
if i not in dict_1:
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)
for idx, val in enumerate(s):
if dict_1[val] == 1:
return idx
return -1
| class Solution(object):
def first_uniq_char(self, s):
"""
:type s: str
:rtype: int
"""
dict_1 = {}
for i in s:
if i not in dict_1:
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)
for (idx, val) in enumerate(s):
if dict_1[val] == 1:
return idx
return -1 |
#
# This is Seisflows
#
# See LICENCE file
#
###############################################################################
raise NotImplementedError
| raise NotImplementedError |
# -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class ItemLookupRequest(object):
"""Implementation of the 'ItemLookupRequest' model.
TODO: type model description here.
Attributes:
condition (ConditionEnum): TODO: type description here.
id_type (IdTypeEnum): TODO: type description here.
merchant_id (string): TODO: type description here.
item_id (list of string): TODO: type description here.
response_group (list of string): TODO: type description here.
search_index (string): TODO: type description here.
variation_page (object): TODO: type description here.
related_item_page (object): TODO: type description here.
relationship_type (list of string): TODO: type description here.
include_reviews_summary (string): TODO: type description here.
truncate_reviews_at (int): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
_names = {
"condition":'Condition',
"id_type":'IdType',
"merchant_id":'MerchantId',
"item_id":'ItemId',
"response_group":'ResponseGroup',
"search_index":'SearchIndex',
"variation_page":'VariationPage',
"related_item_page":'RelatedItemPage',
"relationship_type":'RelationshipType',
"include_reviews_summary":'IncludeReviewsSummary',
"truncate_reviews_at":'TruncateReviewsAt'
}
def __init__(self,
condition=None,
id_type=None,
merchant_id=None,
item_id=None,
response_group=None,
search_index=None,
variation_page=None,
related_item_page=None,
relationship_type=None,
include_reviews_summary=None,
truncate_reviews_at=None):
"""Constructor for the ItemLookupRequest class"""
# Initialize members of the class
self.condition = condition
self.id_type = id_type
self.merchant_id = merchant_id
self.item_id = item_id
self.response_group = response_group
self.search_index = search_index
self.variation_page = variation_page
self.related_item_page = related_item_page
self.relationship_type = relationship_type
self.include_reviews_summary = include_reviews_summary
self.truncate_reviews_at = truncate_reviews_at
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
condition = dictionary.get('Condition')
id_type = dictionary.get('IdType')
merchant_id = dictionary.get('MerchantId')
item_id = dictionary.get('ItemId')
response_group = dictionary.get('ResponseGroup')
search_index = dictionary.get('SearchIndex')
variation_page = dictionary.get('VariationPage')
related_item_page = dictionary.get('RelatedItemPage')
relationship_type = dictionary.get('RelationshipType')
include_reviews_summary = dictionary.get('IncludeReviewsSummary')
truncate_reviews_at = dictionary.get('TruncateReviewsAt')
# Return an object of this model
return cls(condition,
id_type,
merchant_id,
item_id,
response_group,
search_index,
variation_page,
related_item_page,
relationship_type,
include_reviews_summary,
truncate_reviews_at)
| """
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Itemlookuprequest(object):
"""Implementation of the 'ItemLookupRequest' model.
TODO: type model description here.
Attributes:
condition (ConditionEnum): TODO: type description here.
id_type (IdTypeEnum): TODO: type description here.
merchant_id (string): TODO: type description here.
item_id (list of string): TODO: type description here.
response_group (list of string): TODO: type description here.
search_index (string): TODO: type description here.
variation_page (object): TODO: type description here.
related_item_page (object): TODO: type description here.
relationship_type (list of string): TODO: type description here.
include_reviews_summary (string): TODO: type description here.
truncate_reviews_at (int): TODO: type description here.
"""
_names = {'condition': 'Condition', 'id_type': 'IdType', 'merchant_id': 'MerchantId', 'item_id': 'ItemId', 'response_group': 'ResponseGroup', 'search_index': 'SearchIndex', 'variation_page': 'VariationPage', 'related_item_page': 'RelatedItemPage', 'relationship_type': 'RelationshipType', 'include_reviews_summary': 'IncludeReviewsSummary', 'truncate_reviews_at': 'TruncateReviewsAt'}
def __init__(self, condition=None, id_type=None, merchant_id=None, item_id=None, response_group=None, search_index=None, variation_page=None, related_item_page=None, relationship_type=None, include_reviews_summary=None, truncate_reviews_at=None):
"""Constructor for the ItemLookupRequest class"""
self.condition = condition
self.id_type = id_type
self.merchant_id = merchant_id
self.item_id = item_id
self.response_group = response_group
self.search_index = search_index
self.variation_page = variation_page
self.related_item_page = related_item_page
self.relationship_type = relationship_type
self.include_reviews_summary = include_reviews_summary
self.truncate_reviews_at = truncate_reviews_at
@classmethod
def from_dictionary(cls, dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
condition = dictionary.get('Condition')
id_type = dictionary.get('IdType')
merchant_id = dictionary.get('MerchantId')
item_id = dictionary.get('ItemId')
response_group = dictionary.get('ResponseGroup')
search_index = dictionary.get('SearchIndex')
variation_page = dictionary.get('VariationPage')
related_item_page = dictionary.get('RelatedItemPage')
relationship_type = dictionary.get('RelationshipType')
include_reviews_summary = dictionary.get('IncludeReviewsSummary')
truncate_reviews_at = dictionary.get('TruncateReviewsAt')
return cls(condition, id_type, merchant_id, item_id, response_group, search_index, variation_page, related_item_page, relationship_type, include_reviews_summary, truncate_reviews_at) |
#Integer division
#You have a shop selling buns for $2.40 each. A customer comes in with $15, and would like to buy as many buns as possible.
#Complete the code to calculate how many buns the customer can afford.
#Note: Your customer won't be happy if you try to sell them part of a bun.
#Print only the result, any other text in the output will cause the checker to fail.
bun_price = 2.40
money = 15
print( money // bun_price ) | bun_price = 2.4
money = 15
print(money // bun_price) |
# An algorithm to reconstruct the queue.
# Suppose you have a random list of people standing in a queue.
# Each person is described by a pair of integers (h,k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key = lambda x: (-x[0], x[1]))
ans = []
for pep in people:
ans.insert(pep[1], pep)
return ans
| class Solution:
def reconstruct_queue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key=lambda x: (-x[0], x[1]))
ans = []
for pep in people:
ans.insert(pep[1], pep)
return ans |
# statements that used at the start of defenition or in statements without columns
defenition_statements = {
"DROP": "DROP",
"CREATE": "CREATE",
"TABLE": "TABLE",
"DATABASE": "DATABASE",
"SCHEMA": "SCHEMA",
"ALTER": "ALTER",
"TYPE": "TYPE",
"DOMAIN": "DOMAIN",
"REPLACE": "REPLACE",
"OR": "OR",
"CLUSTERED": "CLUSTERED",
"SEQUENCE": "SEQUENCE",
"TABLESPACE": "TABLESPACE",
}
common_statements = {
"INDEX": "INDEX",
"REFERENCES": "REFERENCES",
"KEY": "KEY",
"ADD": "ADD",
"AS": "AS",
"CLONE": "CLONE",
"DEFERRABLE": "DEFERRABLE",
"INITIALLY": "INITIALLY",
"IF": "IF",
"NOT": "NOT",
"EXISTS": "EXISTS",
"ON": "ON",
"FOR": "FOR",
"ENCRYPT": "ENCRYPT",
"SALT": "SALT",
"NO": "NO",
"USING": "USING",
# bigquery
"OPTIONS": "OPTIONS",
}
columns_defenition = {
"DELETE": "DELETE",
"UPDATE": "UPDATE",
"NULL": "NULL",
"ARRAY": "ARRAY",
",": "COMMA",
"DEFAULT": "DEFAULT",
"COLLATE": "COLLATE",
"ENFORCED": "ENFORCED",
"ENCODE": "ENCODE",
"GENERATED": "GENERATED",
"COMMENT": "COMMENT",
}
first_liners = {
"LIKE": "LIKE",
"CONSTRAINT": "CONSTRAINT",
"FOREIGN": "FOREIGN",
"PRIMARY": "PRIMARY",
"UNIQUE": "UNIQUE",
"CHECK": "CHECK",
"WITH": "WITH",
}
common_statements.update(first_liners)
defenition_statements.update(common_statements)
after_columns_tokens = {
"PARTITIONED": "PARTITIONED",
"PARTITION": "PARTITION",
"BY": "BY",
# hql
"INTO": "INTO",
"STORED": "STORED",
"LOCATION": "LOCATION",
"ROW": "ROW",
"FORMAT": "FORMAT",
"TERMINATED": "TERMINATED",
"COLLECTION": "COLLECTION",
"ITEMS": "ITEMS",
"MAP": "MAP",
"KEYS": "KEYS",
"SERDE": "SERDE",
"CLUSTER": "CLUSTER",
"SERDEPROPERTIES": "SERDEPROPERTIES",
"TBLPROPERTIES": "TBLPROPERTIES",
"SKEWED": "SKEWED",
# oracle
"STORAGE": "STORAGE",
"TABLESPACE": "TABLESPACE",
# mssql
"TEXTIMAGE_ON": "TEXTIMAGE_ON",
}
sequence_reserved = {
"INCREMENT": "INCREMENT",
"START": "START",
"MINVALUE": "MINVALUE",
"MAXVALUE": "MAXVALUE",
"CACHE": "CACHE",
"NO": "NO",
}
tokens = tuple(
set(
["ID", "DOT", "STRING", "DQ_STRING", "LP", "RP", "LT", "RT", "COMMAT"]
+ list(defenition_statements.values())
+ list(common_statements.values())
+ list(columns_defenition.values())
+ list(sequence_reserved.values())
+ list(after_columns_tokens.values())
)
)
symbol_tokens = {
")": "RP",
"(": "LP",
}
symbol_tokens_no_check = {"<": "LT", ">": "RT"}
| defenition_statements = {'DROP': 'DROP', 'CREATE': 'CREATE', 'TABLE': 'TABLE', 'DATABASE': 'DATABASE', 'SCHEMA': 'SCHEMA', 'ALTER': 'ALTER', 'TYPE': 'TYPE', 'DOMAIN': 'DOMAIN', 'REPLACE': 'REPLACE', 'OR': 'OR', 'CLUSTERED': 'CLUSTERED', 'SEQUENCE': 'SEQUENCE', 'TABLESPACE': 'TABLESPACE'}
common_statements = {'INDEX': 'INDEX', 'REFERENCES': 'REFERENCES', 'KEY': 'KEY', 'ADD': 'ADD', 'AS': 'AS', 'CLONE': 'CLONE', 'DEFERRABLE': 'DEFERRABLE', 'INITIALLY': 'INITIALLY', 'IF': 'IF', 'NOT': 'NOT', 'EXISTS': 'EXISTS', 'ON': 'ON', 'FOR': 'FOR', 'ENCRYPT': 'ENCRYPT', 'SALT': 'SALT', 'NO': 'NO', 'USING': 'USING', 'OPTIONS': 'OPTIONS'}
columns_defenition = {'DELETE': 'DELETE', 'UPDATE': 'UPDATE', 'NULL': 'NULL', 'ARRAY': 'ARRAY', ',': 'COMMA', 'DEFAULT': 'DEFAULT', 'COLLATE': 'COLLATE', 'ENFORCED': 'ENFORCED', 'ENCODE': 'ENCODE', 'GENERATED': 'GENERATED', 'COMMENT': 'COMMENT'}
first_liners = {'LIKE': 'LIKE', 'CONSTRAINT': 'CONSTRAINT', 'FOREIGN': 'FOREIGN', 'PRIMARY': 'PRIMARY', 'UNIQUE': 'UNIQUE', 'CHECK': 'CHECK', 'WITH': 'WITH'}
common_statements.update(first_liners)
defenition_statements.update(common_statements)
after_columns_tokens = {'PARTITIONED': 'PARTITIONED', 'PARTITION': 'PARTITION', 'BY': 'BY', 'INTO': 'INTO', 'STORED': 'STORED', 'LOCATION': 'LOCATION', 'ROW': 'ROW', 'FORMAT': 'FORMAT', 'TERMINATED': 'TERMINATED', 'COLLECTION': 'COLLECTION', 'ITEMS': 'ITEMS', 'MAP': 'MAP', 'KEYS': 'KEYS', 'SERDE': 'SERDE', 'CLUSTER': 'CLUSTER', 'SERDEPROPERTIES': 'SERDEPROPERTIES', 'TBLPROPERTIES': 'TBLPROPERTIES', 'SKEWED': 'SKEWED', 'STORAGE': 'STORAGE', 'TABLESPACE': 'TABLESPACE', 'TEXTIMAGE_ON': 'TEXTIMAGE_ON'}
sequence_reserved = {'INCREMENT': 'INCREMENT', 'START': 'START', 'MINVALUE': 'MINVALUE', 'MAXVALUE': 'MAXVALUE', 'CACHE': 'CACHE', 'NO': 'NO'}
tokens = tuple(set(['ID', 'DOT', 'STRING', 'DQ_STRING', 'LP', 'RP', 'LT', 'RT', 'COMMAT'] + list(defenition_statements.values()) + list(common_statements.values()) + list(columns_defenition.values()) + list(sequence_reserved.values()) + list(after_columns_tokens.values())))
symbol_tokens = {')': 'RP', '(': 'LP'}
symbol_tokens_no_check = {'<': 'LT', '>': 'RT'} |
def kmp(P, T):
# Compute the start position (number of chars) of the longest suffix that matches a prefix,
# and store them into list K, the first element of K is set to be -1, the second
#
K = [] # K[t] store the value that when mismatch happens at t, should move Pattern P K[t] characters ahead
t = -1 # K's length is len(P) + 1, the first element is set to be -1, corresponding to no elements in P.
K.append(t) # Add the first element, keep t = -1.
for k in range(1, len(P) + 1):
# traverse all the elemtn in P, calculate the corresponding value for each element.
while(t >= 0 and P[t] != P[k - 1]): # if t=-1, then let t = 0, if t>=0 and current suffix doesn't match, then try a shorter suffix
t = K[t]
t = t + 1 # If it matches, then the matching position should be one character ahead.
K.append(t) # record the matching postion for k
print(K)
# Match the String T with P
m = 0 # Record the current matching position in P when compared with T
for i in range(0, len(T)): # traverse T one-by-one
while (m >= 0 and P[m] != T[i]): # if mismatch happens at position m, move P forward with K[m] characters and restart comparison
m = K[m]
m = m + 1 # if position m matches, move P forward to next position
if m == len(P): # if m is already the end of K (or P), the a fully match is found. Continue comparison by move P forward K[m] characters
print (i - m + 1, i)
m = K[m]
if __name__ == "__main__":
kmp('abcbabca', 'abcbabcabcbabcbabcbabcabcbabcbabca')
kmp('abab', 'ababcabababc')
| def kmp(P, T):
k = []
t = -1
K.append(t)
for k in range(1, len(P) + 1):
while t >= 0 and P[t] != P[k - 1]:
t = K[t]
t = t + 1
K.append(t)
print(K)
m = 0
for i in range(0, len(T)):
while m >= 0 and P[m] != T[i]:
m = K[m]
m = m + 1
if m == len(P):
print(i - m + 1, i)
m = K[m]
if __name__ == '__main__':
kmp('abcbabca', 'abcbabcabcbabcbabcbabcabcbabcbabca')
kmp('abab', 'ababcabababc') |
class _FuncStorage:
def __init__(self):
self._function_map = {}
def insert_function(self, name, function):
self._function_map[name] = function
def get_all_functions(self):
return self._function_map
| class _Funcstorage:
def __init__(self):
self._function_map = {}
def insert_function(self, name, function):
self._function_map[name] = function
def get_all_functions(self):
return self._function_map |
A=int(input("dame int"))
B=int(input("dame int"))
if(A>B):
print("A es mayor")
else:
print("B es mayor")
| a = int(input('dame int'))
b = int(input('dame int'))
if A > B:
print('A es mayor')
else:
print('B es mayor') |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-03-15 00:07:14
# Description:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
for i in range(0, len(nums) - 1):
# Reduce the problem to two sum(0)
two_sum = -nums[i]
cache = set()
for num in nums[i + 1:]:
remaining = two_sum - num
if remaining in cache:
#sorting to create unique tuples
triplet = tuple(sorted([nums[i], remaining, num]))
# using tuple in a set will eliminate duplicates combinations
result.add(triplet)
else:
cache.add(num)
return result
if __name__ == "__main__":
pass
| class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
result = set()
for i in range(0, len(nums) - 1):
two_sum = -nums[i]
cache = set()
for num in nums[i + 1:]:
remaining = two_sum - num
if remaining in cache:
triplet = tuple(sorted([nums[i], remaining, num]))
result.add(triplet)
else:
cache.add(num)
return result
if __name__ == '__main__':
pass |
bluelabs_format_hints = {
'field-delimiter': ',',
'record-terminator': "\n",
'compression': 'GZIP',
'quoting': None,
'quotechar': '"',
'doublequote': False,
'escape': '\\',
'encoding': 'UTF8',
'dateformat': 'YYYY-MM-DD',
'timeonlyformat': 'HH24:MI:SS',
'datetimeformattz': 'YYYY-MM-DD HH:MI:SSOF',
'datetimeformat': 'YYYY-MM-DD HH24:MI:SS',
'header-row': False,
}
csv_format_hints = {
'field-delimiter': ',',
'record-terminator': "\n",
'compression': 'GZIP',
'quoting': 'minimal',
'quotechar': '"',
'doublequote': True,
'escape': None,
'encoding': 'UTF8',
'dateformat': 'MM/DD/YY',
'timeonlyformat': 'HH24:MI:SS',
'datetimeformattz': 'MM/DD/YY HH24:MI',
'datetimeformat': 'MM/DD/YY HH24:MI',
'header-row': True,
}
vertica_format_hints = {
'field-delimiter': '\001',
'record-terminator': '\002',
'compression': None,
'quoting': None,
'quotechar': '"',
'doublequote': False,
'escape': None,
'encoding': 'UTF8',
'dateformat': 'YYYY-MM-DD',
'timeonlyformat': 'HH24:MI:SS',
'datetimeformat': 'YYYY-MM-DD HH:MI:SS',
'datetimeformattz': 'YYYY-MM-DD HH:MI:SSOF',
'header-row': False,
}
| bluelabs_format_hints = {'field-delimiter': ',', 'record-terminator': '\n', 'compression': 'GZIP', 'quoting': None, 'quotechar': '"', 'doublequote': False, 'escape': '\\', 'encoding': 'UTF8', 'dateformat': 'YYYY-MM-DD', 'timeonlyformat': 'HH24:MI:SS', 'datetimeformattz': 'YYYY-MM-DD HH:MI:SSOF', 'datetimeformat': 'YYYY-MM-DD HH24:MI:SS', 'header-row': False}
csv_format_hints = {'field-delimiter': ',', 'record-terminator': '\n', 'compression': 'GZIP', 'quoting': 'minimal', 'quotechar': '"', 'doublequote': True, 'escape': None, 'encoding': 'UTF8', 'dateformat': 'MM/DD/YY', 'timeonlyformat': 'HH24:MI:SS', 'datetimeformattz': 'MM/DD/YY HH24:MI', 'datetimeformat': 'MM/DD/YY HH24:MI', 'header-row': True}
vertica_format_hints = {'field-delimiter': '\x01', 'record-terminator': '\x02', 'compression': None, 'quoting': None, 'quotechar': '"', 'doublequote': False, 'escape': None, 'encoding': 'UTF8', 'dateformat': 'YYYY-MM-DD', 'timeonlyformat': 'HH24:MI:SS', 'datetimeformat': 'YYYY-MM-DD HH:MI:SS', 'datetimeformattz': 'YYYY-MM-DD HH:MI:SSOF', 'header-row': False} |
# FROM THE OP PAPER-ISH
MINI_BATCH_SIZE = 32
MEMORY_SIZE = 10**6
BUFFER_SIZE = 100
LHIST = 4
GAMMA = 0.99
UPDATE_FREQ_ONlINE = 4
UPDATE_TARGET = 2500 # This was 10**4 but is measured in actor steps, so it's divided update_freq_online
TEST_FREQ = 5*10**4 # Measure in updates
TEST_STEPS = 10**4
LEARNING_RATE = 0.00025
G_MOMENTUM = 0.95
EPSILON_INIT = 1.0
EPSILON_FINAL = 0.1
EPSILON_TEST = 0.05
EPSILON_LIFE = 10**6
REPLAY_START = 5*10**4
NO_OP_MAX = 30
UPDATES = 5*10**6
CLIP_REWARD = 1.0
CLIP_ERROR = 1.0
# MISC
PLAY_STEPS = 3000
BUFFER_SAMPLES = 20
CROP = (0, -1)
FRAMESIZE = [84,84]
FRAMESIZETP = (84,84)
#DROPS = [0.0,0.15,0.1,0.0]
DROPS = [0.0, 0.0, 0.0, 0.0]
Games = ['air_raid', 'alien', 'amidar', 'assault', 'asterix', 'asteroids', 'atlantis',
'bank_heist', 'battle_zone', 'beam_rider', 'bowling', 'boxing', 'breakout', 'carnival',
'centipede', 'chopper_command', 'crazy_climber', 'demon_attack', 'double_dunk',
'enduro', 'fishing_derby', 'freeway', 'frostbite', 'gopher', 'gravitar',
'hero', 'ice_hockey', 'jamesbond', 'kangaroo', 'krull', 'kung_fu_master',
'montezuma_revenge', 'ms_pacman', 'name_this_game', 'pong',
'private_eye', 'qbert', 'riverraid', 'road_runner', 'robotank', 'seaquest',
'space_invaders', 'star_gunner', 'tennis', 'time_pilot', 'tutankham', 'up_n_down',
'venture', 'video_pinball', 'wizard_of_wor', 'zaxxon']
GamesExtras = ['defender','phoenix','berzerk','skiing','yars_revenge','solaris','pitfall',]
ACTION_MEANING = {
0: "NOOP",
1: "FIRE",
2: "UP",
3: "RIGHT",
4: "LEFT",
5: "DOWN",
6: "UPRIGHT",
7: "UPLEFT",
8: "DOWNRIGHT",
9: "DOWNLEFT",
10: "UPFIRE",
11: "RIGHTFIRE",
12: "LEFTFIRE",
13: "DOWNFIRE",
14: "UPRIGHTFIRE",
15: "UPLEFTFIRE",
16: "DOWNRIGHTFIRE",
17: "DOWNLEFTFIRE",
} | mini_batch_size = 32
memory_size = 10 ** 6
buffer_size = 100
lhist = 4
gamma = 0.99
update_freq_o_nl_ine = 4
update_target = 2500
test_freq = 5 * 10 ** 4
test_steps = 10 ** 4
learning_rate = 0.00025
g_momentum = 0.95
epsilon_init = 1.0
epsilon_final = 0.1
epsilon_test = 0.05
epsilon_life = 10 ** 6
replay_start = 5 * 10 ** 4
no_op_max = 30
updates = 5 * 10 ** 6
clip_reward = 1.0
clip_error = 1.0
play_steps = 3000
buffer_samples = 20
crop = (0, -1)
framesize = [84, 84]
framesizetp = (84, 84)
drops = [0.0, 0.0, 0.0, 0.0]
games = ['air_raid', 'alien', 'amidar', 'assault', 'asterix', 'asteroids', 'atlantis', 'bank_heist', 'battle_zone', 'beam_rider', 'bowling', 'boxing', 'breakout', 'carnival', 'centipede', 'chopper_command', 'crazy_climber', 'demon_attack', 'double_dunk', 'enduro', 'fishing_derby', 'freeway', 'frostbite', 'gopher', 'gravitar', 'hero', 'ice_hockey', 'jamesbond', 'kangaroo', 'krull', 'kung_fu_master', 'montezuma_revenge', 'ms_pacman', 'name_this_game', 'pong', 'private_eye', 'qbert', 'riverraid', 'road_runner', 'robotank', 'seaquest', 'space_invaders', 'star_gunner', 'tennis', 'time_pilot', 'tutankham', 'up_n_down', 'venture', 'video_pinball', 'wizard_of_wor', 'zaxxon']
games_extras = ['defender', 'phoenix', 'berzerk', 'skiing', 'yars_revenge', 'solaris', 'pitfall']
action_meaning = {0: 'NOOP', 1: 'FIRE', 2: 'UP', 3: 'RIGHT', 4: 'LEFT', 5: 'DOWN', 6: 'UPRIGHT', 7: 'UPLEFT', 8: 'DOWNRIGHT', 9: 'DOWNLEFT', 10: 'UPFIRE', 11: 'RIGHTFIRE', 12: 'LEFTFIRE', 13: 'DOWNFIRE', 14: 'UPRIGHTFIRE', 15: 'UPLEFTFIRE', 16: 'DOWNRIGHTFIRE', 17: 'DOWNLEFTFIRE'} |
# author: jamie
# email: jinjiedeng.jjd@gmail.com
def Priority (c):
if c == '&': return 3
elif c == '|': return 2
elif c == '^': return 1
elif c == '(': return 0
def InfixToPostfix (infix, postfix):
stack = []
for c in infix:
if c == '(':
stack.append('(')
elif c == ')':
while stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
elif c == '&' or c == '|' or c == '^':
while len(stack) and Priority(c) <= Priority(stack[-1]):
postfix.append(stack.pop())
stack.append(c)
else:
postfix.append(c)
while len(stack):
postfix.append(stack.pop())
def Evaluate (postfix, value):
stack = []
for c in postfix:
if c == '&' or c == '|' or c == '^':
rhs = stack.pop()
lhs = stack.pop()
if c == '&': stack.append(lhs & rhs)
elif c == '|': stack.append(lhs | rhs)
elif c == '^': stack.append(lhs ^ rhs)
elif c == '1' or c == '0':
stack.append(ord(c) - ord('0'))
else:
stack.append(value[ord(c) - ord('A')])
return stack.pop()
if __name__ == "__main__":
infix = input()
T = int(input())
for _ in range(T):
value = list(map(int, input().split()))
postfix = []
InfixToPostfix(infix, postfix)
print(Evaluate(postfix, value)) | def priority(c):
if c == '&':
return 3
elif c == '|':
return 2
elif c == '^':
return 1
elif c == '(':
return 0
def infix_to_postfix(infix, postfix):
stack = []
for c in infix:
if c == '(':
stack.append('(')
elif c == ')':
while stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
elif c == '&' or c == '|' or c == '^':
while len(stack) and priority(c) <= priority(stack[-1]):
postfix.append(stack.pop())
stack.append(c)
else:
postfix.append(c)
while len(stack):
postfix.append(stack.pop())
def evaluate(postfix, value):
stack = []
for c in postfix:
if c == '&' or c == '|' or c == '^':
rhs = stack.pop()
lhs = stack.pop()
if c == '&':
stack.append(lhs & rhs)
elif c == '|':
stack.append(lhs | rhs)
elif c == '^':
stack.append(lhs ^ rhs)
elif c == '1' or c == '0':
stack.append(ord(c) - ord('0'))
else:
stack.append(value[ord(c) - ord('A')])
return stack.pop()
if __name__ == '__main__':
infix = input()
t = int(input())
for _ in range(T):
value = list(map(int, input().split()))
postfix = []
infix_to_postfix(infix, postfix)
print(evaluate(postfix, value)) |
__version__ = 'unknown'
try:
__version__ = __import__('pkg_resources').get_distribution('django_richenum').version
except Exception as e:
pass
| __version__ = 'unknown'
try:
__version__ = __import__('pkg_resources').get_distribution('django_richenum').version
except Exception as e:
pass |
CHARACTERS_PER_LINE = 39
def break_lines(text):
chars_in_line = 1
final_text = ''
skip = False
for char in text:
if chars_in_line >= CHARACTERS_PER_LINE:
if char == ' ':
# we happen to be on a space, se we can just break here
final_text += '\n'
skip = True
else:
# work backwards to find the space to break on
for i in range(len(final_text) - 1, 0, -1):
if final_text[i] == ' ':
final_text = final_text[:i] + '\n' + final_text[i + 1:]
break
chars_in_line = 0
chars_in_line += 1
if not skip:
final_text += char
skip = False
return final_text
if __name__ == '__main__':
print(break_lines('The <y<Spirit of the Sword>> guides the goddess\' chosen hero to <r<Skyloft Village>>'))
print(break_lines('Hey, you look like you have a Questions?'))
print(break_lines('Skyloft Peater/Peatrice\'s Crystals has Bug Net'))
| characters_per_line = 39
def break_lines(text):
chars_in_line = 1
final_text = ''
skip = False
for char in text:
if chars_in_line >= CHARACTERS_PER_LINE:
if char == ' ':
final_text += '\n'
skip = True
else:
for i in range(len(final_text) - 1, 0, -1):
if final_text[i] == ' ':
final_text = final_text[:i] + '\n' + final_text[i + 1:]
break
chars_in_line = 0
chars_in_line += 1
if not skip:
final_text += char
skip = False
return final_text
if __name__ == '__main__':
print(break_lines("The <y<Spirit of the Sword>> guides the goddess' chosen hero to <r<Skyloft Village>>"))
print(break_lines('Hey, you look like you have a Questions?'))
print(break_lines("Skyloft Peater/Peatrice's Crystals has Bug Net")) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
stack = []
res = [0] * len(nums)
for i, n in enumerate(nums):
while stack and nums[stack[-1]] < n:
res[stack.pop()] = n
stack.append(i)
return res
| class Solution:
def next_larger_nodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
stack = []
res = [0] * len(nums)
for (i, n) in enumerate(nums):
while stack and nums[stack[-1]] < n:
res[stack.pop()] = n
stack.append(i)
return res |
def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ["name", "description", "encodingType", "location", "properties", "metadata",
"definition", "phenomenonTime", "resultTime", "observedArea", "result", "id", "@iot.id",
"resultQuality", "validTime", "time", "parameters", "feature"]
def tokenize_parentheses(tokens):
""" Finds non parsed parentheses in tokens (ex.: ['x(y']['z)'] -> ['x']['(']['y']['z'][')']
:param tokens: a list of tokens
:return: the list with unchecked parenteses tokenized
"""
for index, token in enumerate(tokens):
if ("(" in token or ")" in token) and len(token) > 1:
parenthesis_index = token.find("(")
parenthesis = "("
if parenthesis_index < 0:
parenthesis_index = token.find(")")
parenthesis = ")"
left_side = token[:parenthesis_index]
right_side = token[parenthesis_index + 1:]
del tokens[index]
if bool(left_side):
tokens.insert(index, left_side)
index += 1
tokens.insert(index, parenthesis)
if bool(right_side):
index += 1
tokens.insert(index, right_side)
| def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ['name', 'description', 'encodingType', 'location', 'properties', 'metadata', 'definition', 'phenomenonTime', 'resultTime', 'observedArea', 'result', 'id', '@iot.id', 'resultQuality', 'validTime', 'time', 'parameters', 'feature']
def tokenize_parentheses(tokens):
""" Finds non parsed parentheses in tokens (ex.: ['x(y']['z)'] -> ['x']['(']['y']['z'][')']
:param tokens: a list of tokens
:return: the list with unchecked parenteses tokenized
"""
for (index, token) in enumerate(tokens):
if ('(' in token or ')' in token) and len(token) > 1:
parenthesis_index = token.find('(')
parenthesis = '('
if parenthesis_index < 0:
parenthesis_index = token.find(')')
parenthesis = ')'
left_side = token[:parenthesis_index]
right_side = token[parenthesis_index + 1:]
del tokens[index]
if bool(left_side):
tokens.insert(index, left_side)
index += 1
tokens.insert(index, parenthesis)
if bool(right_side):
index += 1
tokens.insert(index, right_side) |
"""Exception utilities."""
class ParsingException(Exception):
pass
class EnvVariableNotSet(Exception):
def __init__(self, varname: str) -> None:
super(EnvVariableNotSet, self).__init__(f"Env variable [{varname}] not set.")
class InvalidLineUp(Exception):
pass
class UnsupportedLineUp(Exception):
def __init__(self, line_up_name: str) -> None:
super(UnsupportedLineUp, self).__init__(
f"Line-up [{line_up_name}] is not supported."
)
class InvalidTeamLineup(Exception):
pass
| """Exception utilities."""
class Parsingexception(Exception):
pass
class Envvariablenotset(Exception):
def __init__(self, varname: str) -> None:
super(EnvVariableNotSet, self).__init__(f'Env variable [{varname}] not set.')
class Invalidlineup(Exception):
pass
class Unsupportedlineup(Exception):
def __init__(self, line_up_name: str) -> None:
super(UnsupportedLineUp, self).__init__(f'Line-up [{line_up_name}] is not supported.')
class Invalidteamlineup(Exception):
pass |
# (major, minor, patch, prerelease)
VERSION = (0, 0, 6, "")
__shortversion__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:])
__package_name__ = 'pyqubo'
__contact_names__ = 'Recruit Communications Co., Ltd.'
__contact_emails__ = 'rco_pyqubo@ml.cocorou.jp'
__homepage__ = 'https://pyqubo.readthedocs.io/en/latest/'
__repository_url__ = 'https://github.com/recruit-communications/pyqubo'
__download_url__ = 'https://github.com/recruit-communications/pyqubo'
__description__ = 'PyQUBO allows you to create QUBOs or Ising models from mathematical expressions.'
__license__ = 'Apache 2.0'
__keywords__ = 'QUBO, quantum annealing, annealing machine, ising model, optimization'
| version = (0, 0, 6, '')
__shortversion__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:])
__package_name__ = 'pyqubo'
__contact_names__ = 'Recruit Communications Co., Ltd.'
__contact_emails__ = 'rco_pyqubo@ml.cocorou.jp'
__homepage__ = 'https://pyqubo.readthedocs.io/en/latest/'
__repository_url__ = 'https://github.com/recruit-communications/pyqubo'
__download_url__ = 'https://github.com/recruit-communications/pyqubo'
__description__ = 'PyQUBO allows you to create QUBOs or Ising models from mathematical expressions.'
__license__ = 'Apache 2.0'
__keywords__ = 'QUBO, quantum annealing, annealing machine, ising model, optimization' |
#033: ler tres numeros e dizer qual o maior e qual o menor:
print("Digite 3 numeros:")
maiorn = 0
n = int(input("Numero 1: "))
if n > maiorn:
maiorn = n
menorn = n
n = int(input("Numero 2: "))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input("Numero 3: "))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
print(f"o maior numero foi {maiorn} e o menor foi {menorn}")
| print('Digite 3 numeros:')
maiorn = 0
n = int(input('Numero 1: '))
if n > maiorn:
maiorn = n
menorn = n
n = int(input('Numero 2: '))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input('Numero 3: '))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
print(f'o maior numero foi {maiorn} e o menor foi {menorn}') |
#!/usr/bin/python3
#coding=utf-8
def cc_debug():
print(__name__) | def cc_debug():
print(__name__) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
'''
'''
Say you have an array for which the ith element is
the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
'''
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n == 0:
return 0
if k > n // 2:
return self.quickSolve(prices)
hold = [-2 ** 31] * (k + 1)
release = [0] * (k + 1)
for p in prices:
for i in range(k):
hold[i+1] = max(hold[i+1], release[i] - p)
release[i+1] = max(release[i+1], hold[i+1] + p)
return release[k]
def quickSolve(self, prices):
res = 0
for i in range(1, len(prices)):
if prices[i] - prices[i-1] > 0:
res += prices[i] - prices[i-1]
return res
| """
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
"""
'\nSay you have an array for which the ith element is\nthe price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit.\nYou may complete at most k transactions.\n\nNote:\nYou may not engage in multiple transactions at the same time\n(ie, you must sell the stock before you buy again).\n\nCredits:\nSpecial thanks to @Freezen for adding this problem and creating all test cases.\n'
class Solution(object):
def max_profit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n == 0:
return 0
if k > n // 2:
return self.quickSolve(prices)
hold = [-2 ** 31] * (k + 1)
release = [0] * (k + 1)
for p in prices:
for i in range(k):
hold[i + 1] = max(hold[i + 1], release[i] - p)
release[i + 1] = max(release[i + 1], hold[i + 1] + p)
return release[k]
def quick_solve(self, prices):
res = 0
for i in range(1, len(prices)):
if prices[i] - prices[i - 1] > 0:
res += prices[i] - prices[i - 1]
return res |
def drop(i_list: list,n:int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert(n>0)
_shallow_list = []
k=1
for element in i_list:
if k % n != 0:
_shallow_list.append(element)
k+=1
return _shallow_list
if __name__ == "__main__":
print(drop([1,2,3,4,5],6)) | def drop(i_list: list, n: int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert n > 0
_shallow_list = []
k = 1
for element in i_list:
if k % n != 0:
_shallow_list.append(element)
k += 1
return _shallow_list
if __name__ == '__main__':
print(drop([1, 2, 3, 4, 5], 6)) |
#!/usr/bin/python3
"""
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree.
The above image shows one of the valid configurations of camera placement.
Note:
The number of nodes in the given tree will be in the range [1, 1000].
Every node has value 0.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.covered = {None}
self.cnt = 0
def minCameraCover(self, root: TreeNode) -> int:
"""
Greedy?
Bottom up, cover leaf's parent is strictly better than cover leaf
"""
self.dfs(root, None)
if root not in self.covered:
self.covered.add(root)
self.cnt += 1
return self.cnt
def dfs(self, node, pi):
"""
post order
rely on the parents to cover it
"""
if not node:
return
self.dfs(node.left, node)
self.dfs(node.right, node)
if node.left not in self.covered or node.right not in self.covered:
self.cnt += 1
self.covered.add(node.left)
self.covered.add(node.right)
self.covered.add(node)
self.covered.add(pi)
class SolutionErrror:
def __init__(self):
self.covered = set()
def minCameraCover(self, root: TreeNode) -> int:
"""
Greedy?
Top-down, no good.
Bottom up, cover leaf's parent is strictly better than cover leaf
"""
dummy = TreeNode(0)
dummy.left = root
self.dfs(root, dummy)
self.covered.discard(dummy) # swallow KeyError
return len(self.covered)
def dfs(self, node, pi):
"""
post order
"""
if not node:
return
self.dfs(node.left, node)
self.dfs(node.right, node)
# post oder
if (
(not node.left or node.left in self.covered) and
(not node.right or node.right in self.covered)
):
self.covered.add(pi)
return
| """
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree.
The above image shows one of the valid configurations of camera placement.
Note:
The number of nodes in the given tree will be in the range [1, 1000].
Every node has value 0.
"""
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.covered = {None}
self.cnt = 0
def min_camera_cover(self, root: TreeNode) -> int:
"""
Greedy?
Bottom up, cover leaf's parent is strictly better than cover leaf
"""
self.dfs(root, None)
if root not in self.covered:
self.covered.add(root)
self.cnt += 1
return self.cnt
def dfs(self, node, pi):
"""
post order
rely on the parents to cover it
"""
if not node:
return
self.dfs(node.left, node)
self.dfs(node.right, node)
if node.left not in self.covered or node.right not in self.covered:
self.cnt += 1
self.covered.add(node.left)
self.covered.add(node.right)
self.covered.add(node)
self.covered.add(pi)
class Solutionerrror:
def __init__(self):
self.covered = set()
def min_camera_cover(self, root: TreeNode) -> int:
"""
Greedy?
Top-down, no good.
Bottom up, cover leaf's parent is strictly better than cover leaf
"""
dummy = tree_node(0)
dummy.left = root
self.dfs(root, dummy)
self.covered.discard(dummy)
return len(self.covered)
def dfs(self, node, pi):
"""
post order
"""
if not node:
return
self.dfs(node.left, node)
self.dfs(node.right, node)
if (not node.left or node.left in self.covered) and (not node.right or node.right in self.covered):
self.covered.add(pi)
return |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'adb',
'depot_tools/bot_update',
'depot_tools/gclient',
'goma',
'recipe_engine/context',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
'recipe_engine/url',
'depot_tools/tryserver',
]
def _CheckoutSteps(api, buildername):
# Checkout mojo and its dependencies (specified in DEPS) using gclient
api.gclient.set_config('mojo')
if 'Android' in buildername:
api.gclient.apply_config('android')
api.bot_update.ensure_checkout()
api.gclient.runhooks()
def _BuildSteps(api, buildername, is_debug, is_official):
mojob_path = api.path['checkout'].join('mojo', 'tools', 'mojob.py')
args = []
gn_args = []
if 'Android' in buildername:
args += ['--android']
if 'ASan' in buildername:
args += ['--asan']
if api.tryserver.is_tryserver:
args += ['--dcheck_always_on']
env = {}
goma_dir = ''
if 'Win' not in buildername:
# Disable Goma on Windows as it makes the build much slower (> 1 hour vs
# 15 minutes). Try renabling once we have trybots and the cache would be
# warm.
goma_dir = api.goma.ensure_goma()
env['GOMA_SERVICE_ACCOUNT_JSON_FILE'] = api.goma.service_account_json_path
if is_debug:
build_type = "--debug"
elif is_official:
build_type = "--official"
else:
build_type = "--release"
if goma_dir:
env['GOMA_DIR'] = goma_dir
with api.context(env=env):
with api.context(cwd=api.path['checkout']):
api.python('mojob gn',
mojob_path,
args=['gn', build_type] + args + gn_args)
api.python('mojob build',
mojob_path,
args=['build', build_type] + args)
def _DeviceCheckStep(api):
known_devices_path = api.path.join(
api.path.expanduser('~'), '.android', 'known_devices.json')
# Device recovery.
args = [
'--known-devices-file', known_devices_path,
'--adb-path', api.adb.adb_path(),
'-v'
]
api.step(
'device_recovery',
[api.path['checkout'].join('third_party', 'catapult', 'devil',
'devil', 'android', 'tools',
'device_recovery.py')] + args,
infra_step=True)
# Device provisioning.
api.python(
'provision_device',
api.path['checkout'].join('third_party', 'catapult', 'devil',
'devil', 'android', 'tools',
'provision_devices.py'),
infra_step=True)
# Device Status.
try:
buildbot_file = '/home/chrome-bot/.adb_device_info'
args = [
'--json-output', api.json.output(),
'--known-devices-file', known_devices_path,
'--buildbot-path', buildbot_file,
'-v', '--overwrite-known-devices-files',
]
result = api.python(
'device_status',
api.path['checkout'].join('third_party', 'catapult', 'devil', 'devil',
'android', 'tools', 'device_status.py'),
args=args,
infra_step=True)
return result
except api.step.InfraFailure as f:
params = {
'summary': ('Device Offline on %s %s' %
(api.properties['mastername'], api.properties['bot_id'])),
'comment': ('Buildbot: %s\n(Please do not change any labels)' %
api.properties['buildername']),
'labels': 'Restrict-View-Google,OS-Android,Infra-Client,Infra-Labs',
}
link = ('https://code.google.com/p/chromium/issues/entry?%s' %
api.url.urlencode(params))
f.result.presentation.links.update({
'report a bug': link
})
raise
def _GetTestConfig(api):
buildername = api.properties.get('buildername')
test_config = {}
if 'Android' in buildername:
test_config['target_os'] = 'android'
elif 'Linux' in buildername:
test_config['target_os'] = 'linux'
elif 'Win' in buildername:
test_config['target_os'] = 'windows'
else:
raise NotImplementedError('Unknown platform') # pragma: no cover
test_config['is_debug'] = 'dbg' in buildername
if 'Official' in buildername:
# This is not reached, as we only have Android official builds.
raise NotImplementedError(
'Testing not supported for official builds') # pragma: no cover
if 'Perf' in buildername:
test_config['test_types'] = ['perf']
else:
test_config['test_types'] = ['default']
if 'ASan' in buildername:
test_config['sanitizer'] = 'asan'
test_config['master_name'] = api.properties.get('mastername')
test_config['builder_name'] = api.properties.get('buildername')
test_config['build_number'] = api.properties.get('buildnumber')
test_config['test_results_server'] = api.properties.get(
'test_results_server', 'test-results.appspot.com')
test_config['dcheck_always_on'] = api.tryserver.is_tryserver
return test_config
def _TestSteps(api):
get_test_list_path = api.path['checkout'].join('mojo', 'tools',
'get_test_list.py')
test_config = _GetTestConfig(api)
test_out = [{'name': u'Hello', 'command': ['world']}]
result = api.python('get_test_list', get_test_list_path,
args=[api.json.input(test_config), api.json.output()],
step_test_data=lambda: api.json.test_api.output(test_out))
test_list = result.json.output
with api.step.defer_results():
for entry in test_list:
name = str(entry['name']) # api.step() wants a non-Unicode string.
command = entry['command']
with api.context(cwd=api.path['checkout']):
api.step(name, command)
def _UploadShellAndApps(api, buildername):
upload_path = api.path['checkout'].join('mojo', 'tools', 'upload_binaries.py')
is_android = 'Android' in buildername
args = []
if is_android:
args.append('--android')
if 'Official' in buildername:
args.append('--official')
api.python('upload shell and app binaries', upload_path, args)
def RunSteps(api):
buildername = api.properties.get('buildername')
_CheckoutSteps(api, buildername)
is_debug = 'dbg' in buildername
is_official = 'Official' in buildername
_BuildSteps(api, buildername, is_debug, is_official)
is_linux = 'Linux' in buildername
is_win = 'Win' in buildername
is_android = 'Android' in buildername
is_tester = 'Tests' in buildername
is_try = api.tryserver.is_tryserver
is_asan = 'ASan' in buildername
is_perf = 'Perf' in buildername
if is_android and is_tester:
_DeviceCheckStep(api)
upload_binaries = ((is_linux or is_android)
and not is_debug and not is_try and not is_perf and not is_asan)
if not is_tester and not is_linux and not is_win:
# TODO(blundell): Eliminate this special case
# once there's an Android release tester bot.
if upload_binaries and is_android:
_UploadShellAndApps(api, buildername)
return
_TestSteps(api)
# TODO(blundell): Remove the "and not is_android" once there's an
# Android release tester bot and I've removed the logic uploading the
# shell on Android above.
if upload_binaries and not is_android:
_UploadShellAndApps(api, buildername)
def GenTests(api):
tests = [
['mojo_linux', 'Mojo Linux'],
['mojo_linux_dbg', 'Mojo Linux (dbg)'],
['mojo_linux_asan', 'Mojo Linux ASan'],
['mojo_linux_asan_dbg', 'Mojo Linux ASan (dbg)'],
['mojo_android_builder', 'Mojo Android Builder'],
['mojo_android_official', 'Mojo Android Official Builder'],
['mojo_android_dbg', 'Mojo Android (dbg)'],
['mojo_android_builder_tests_dbg', 'Mojo Android Builder Tests (dbg)'],
['mojo_win_dbg', 'Mojo Win (dbg)'],
['mojo_linux_perf', 'Mojo Linux Perf']
]
for test_name, buildername in tests:
test = api.test(test_name) + api.properties.generic(buildername=buildername)
if 'Android' in buildername and 'Tests' in buildername:
test += api.step_data("device_status", api.json.output([
{
"battery": {
"status": "5",
"scale": "100",
"temperature": "249",
"level": "100",
"AC powered": "false",
"health": "2",
"voltage": "4286",
"Wireless powered": "false",
"USB powered": "true",
"technology": "Li-ion",
"present": "true"
},
"wifi_ip": "",
"imei_slice": "Unknown",
"ro.build.id": "LRX21O",
"build_detail":
"google/razor/flo:5.0/LRX21O/1570415:userdebug/dev-keys",
"serial": "07a00ca4",
"ro.build.product": "flo",
"adb_status": "device",
"blacklisted": False,
"usb_status": True,
},
{
"adb_status": "offline",
"blacklisted": True,
"serial": "03e0363a003c6ad4",
"usb_status": False,
},
{
"adb_status": "unauthorized",
"blacklisted": True,
"serial": "03e0363a003c6ad5",
"usb_status": True,
},
{
"adb_status": "device",
"blacklisted": True,
"serial": "03e0363a003c6ad6",
"usb_status": True,
},
{}
]))
yield test
yield(api.test('mojo_linux_try') +
api.properties.tryserver(buildername="Mojo Linux Try"))
yield(api.test('mojo_android_builder_tests_dbg_fail_device_check') +
api.properties.tryserver(buildername="Mojo Android Builder Tests (dbg)") +
api.step_data("device_status", retcode=1))
| deps = ['adb', 'depot_tools/bot_update', 'depot_tools/gclient', 'goma', 'recipe_engine/context', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', 'recipe_engine/url', 'depot_tools/tryserver']
def __checkout_steps(api, buildername):
api.gclient.set_config('mojo')
if 'Android' in buildername:
api.gclient.apply_config('android')
api.bot_update.ensure_checkout()
api.gclient.runhooks()
def __build_steps(api, buildername, is_debug, is_official):
mojob_path = api.path['checkout'].join('mojo', 'tools', 'mojob.py')
args = []
gn_args = []
if 'Android' in buildername:
args += ['--android']
if 'ASan' in buildername:
args += ['--asan']
if api.tryserver.is_tryserver:
args += ['--dcheck_always_on']
env = {}
goma_dir = ''
if 'Win' not in buildername:
goma_dir = api.goma.ensure_goma()
env['GOMA_SERVICE_ACCOUNT_JSON_FILE'] = api.goma.service_account_json_path
if is_debug:
build_type = '--debug'
elif is_official:
build_type = '--official'
else:
build_type = '--release'
if goma_dir:
env['GOMA_DIR'] = goma_dir
with api.context(env=env):
with api.context(cwd=api.path['checkout']):
api.python('mojob gn', mojob_path, args=['gn', build_type] + args + gn_args)
api.python('mojob build', mojob_path, args=['build', build_type] + args)
def __device_check_step(api):
known_devices_path = api.path.join(api.path.expanduser('~'), '.android', 'known_devices.json')
args = ['--known-devices-file', known_devices_path, '--adb-path', api.adb.adb_path(), '-v']
api.step('device_recovery', [api.path['checkout'].join('third_party', 'catapult', 'devil', 'devil', 'android', 'tools', 'device_recovery.py')] + args, infra_step=True)
api.python('provision_device', api.path['checkout'].join('third_party', 'catapult', 'devil', 'devil', 'android', 'tools', 'provision_devices.py'), infra_step=True)
try:
buildbot_file = '/home/chrome-bot/.adb_device_info'
args = ['--json-output', api.json.output(), '--known-devices-file', known_devices_path, '--buildbot-path', buildbot_file, '-v', '--overwrite-known-devices-files']
result = api.python('device_status', api.path['checkout'].join('third_party', 'catapult', 'devil', 'devil', 'android', 'tools', 'device_status.py'), args=args, infra_step=True)
return result
except api.step.InfraFailure as f:
params = {'summary': 'Device Offline on %s %s' % (api.properties['mastername'], api.properties['bot_id']), 'comment': 'Buildbot: %s\n(Please do not change any labels)' % api.properties['buildername'], 'labels': 'Restrict-View-Google,OS-Android,Infra-Client,Infra-Labs'}
link = 'https://code.google.com/p/chromium/issues/entry?%s' % api.url.urlencode(params)
f.result.presentation.links.update({'report a bug': link})
raise
def __get_test_config(api):
buildername = api.properties.get('buildername')
test_config = {}
if 'Android' in buildername:
test_config['target_os'] = 'android'
elif 'Linux' in buildername:
test_config['target_os'] = 'linux'
elif 'Win' in buildername:
test_config['target_os'] = 'windows'
else:
raise not_implemented_error('Unknown platform')
test_config['is_debug'] = 'dbg' in buildername
if 'Official' in buildername:
raise not_implemented_error('Testing not supported for official builds')
if 'Perf' in buildername:
test_config['test_types'] = ['perf']
else:
test_config['test_types'] = ['default']
if 'ASan' in buildername:
test_config['sanitizer'] = 'asan'
test_config['master_name'] = api.properties.get('mastername')
test_config['builder_name'] = api.properties.get('buildername')
test_config['build_number'] = api.properties.get('buildnumber')
test_config['test_results_server'] = api.properties.get('test_results_server', 'test-results.appspot.com')
test_config['dcheck_always_on'] = api.tryserver.is_tryserver
return test_config
def __test_steps(api):
get_test_list_path = api.path['checkout'].join('mojo', 'tools', 'get_test_list.py')
test_config = __get_test_config(api)
test_out = [{'name': u'Hello', 'command': ['world']}]
result = api.python('get_test_list', get_test_list_path, args=[api.json.input(test_config), api.json.output()], step_test_data=lambda : api.json.test_api.output(test_out))
test_list = result.json.output
with api.step.defer_results():
for entry in test_list:
name = str(entry['name'])
command = entry['command']
with api.context(cwd=api.path['checkout']):
api.step(name, command)
def __upload_shell_and_apps(api, buildername):
upload_path = api.path['checkout'].join('mojo', 'tools', 'upload_binaries.py')
is_android = 'Android' in buildername
args = []
if is_android:
args.append('--android')
if 'Official' in buildername:
args.append('--official')
api.python('upload shell and app binaries', upload_path, args)
def run_steps(api):
buildername = api.properties.get('buildername')
__checkout_steps(api, buildername)
is_debug = 'dbg' in buildername
is_official = 'Official' in buildername
__build_steps(api, buildername, is_debug, is_official)
is_linux = 'Linux' in buildername
is_win = 'Win' in buildername
is_android = 'Android' in buildername
is_tester = 'Tests' in buildername
is_try = api.tryserver.is_tryserver
is_asan = 'ASan' in buildername
is_perf = 'Perf' in buildername
if is_android and is_tester:
__device_check_step(api)
upload_binaries = (is_linux or is_android) and (not is_debug) and (not is_try) and (not is_perf) and (not is_asan)
if not is_tester and (not is_linux) and (not is_win):
if upload_binaries and is_android:
__upload_shell_and_apps(api, buildername)
return
__test_steps(api)
if upload_binaries and (not is_android):
__upload_shell_and_apps(api, buildername)
def gen_tests(api):
tests = [['mojo_linux', 'Mojo Linux'], ['mojo_linux_dbg', 'Mojo Linux (dbg)'], ['mojo_linux_asan', 'Mojo Linux ASan'], ['mojo_linux_asan_dbg', 'Mojo Linux ASan (dbg)'], ['mojo_android_builder', 'Mojo Android Builder'], ['mojo_android_official', 'Mojo Android Official Builder'], ['mojo_android_dbg', 'Mojo Android (dbg)'], ['mojo_android_builder_tests_dbg', 'Mojo Android Builder Tests (dbg)'], ['mojo_win_dbg', 'Mojo Win (dbg)'], ['mojo_linux_perf', 'Mojo Linux Perf']]
for (test_name, buildername) in tests:
test = api.test(test_name) + api.properties.generic(buildername=buildername)
if 'Android' in buildername and 'Tests' in buildername:
test += api.step_data('device_status', api.json.output([{'battery': {'status': '5', 'scale': '100', 'temperature': '249', 'level': '100', 'AC powered': 'false', 'health': '2', 'voltage': '4286', 'Wireless powered': 'false', 'USB powered': 'true', 'technology': 'Li-ion', 'present': 'true'}, 'wifi_ip': '', 'imei_slice': 'Unknown', 'ro.build.id': 'LRX21O', 'build_detail': 'google/razor/flo:5.0/LRX21O/1570415:userdebug/dev-keys', 'serial': '07a00ca4', 'ro.build.product': 'flo', 'adb_status': 'device', 'blacklisted': False, 'usb_status': True}, {'adb_status': 'offline', 'blacklisted': True, 'serial': '03e0363a003c6ad4', 'usb_status': False}, {'adb_status': 'unauthorized', 'blacklisted': True, 'serial': '03e0363a003c6ad5', 'usb_status': True}, {'adb_status': 'device', 'blacklisted': True, 'serial': '03e0363a003c6ad6', 'usb_status': True}, {}]))
yield test
yield (api.test('mojo_linux_try') + api.properties.tryserver(buildername='Mojo Linux Try'))
yield (api.test('mojo_android_builder_tests_dbg_fail_device_check') + api.properties.tryserver(buildername='Mojo Android Builder Tests (dbg)') + api.step_data('device_status', retcode=1)) |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2017 FIWARE Foundation, e.V.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
##
__author__ = 'fla'
GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
APPLICATION_NAME = 'TSC Enablers Dashboard'
CREDENTIAL_DIR = '.credentials'
CREDENTIAL_FILE = 'sheets.googleapis.com.json'
DB_NAME = 'enablers-dashboard.db'
DB_FOLDER = 'dbase'
LOG_FILE = 'tsc-dashboard.log'
# We need to add 16 rows in the number of enablers list corresponding to:
# - Title
# - Report date
# - Data sources updated on
# - Source
# - Units
# - Enabler Impl
# - INCUBATED
# - DEVELOPMENT
# - SUPPORT
# - DEPRECATED
# - And 6 extra blank rows between them
FIXED_ROWS = 16
# We keep the firsts row without change in the sheet (sheet title)
INITIAL_ROW = 2
# The number of columns to delete corresponds to:
# Source, Catalogue, ReadTheDocs, Docker, GitHub, Coverall, Academy, HelpDesk, Backlog, GitHub_Open_Issues,
# GitHub_Closed_Issues, GitHub_Adopters, GitHub_Adopters_Open_Issues, GitHub_Adopters_Closed_Issues,
# GitHub_Comits, GitHub_Forks, GitHub_Watchers, GitHub_Stars, Jira_WorkItem_Not_Closed, Jira_WorkItem_Closed
# + Extra 2 = 22
FIXED_COLUMNS = 22
# We start to delete from the initial column
INITIAL_COLUMN = 1
| __author__ = 'fla'
google_accounts_base_url = 'https://accounts.google.com'
application_name = 'TSC Enablers Dashboard'
credential_dir = '.credentials'
credential_file = 'sheets.googleapis.com.json'
db_name = 'enablers-dashboard.db'
db_folder = 'dbase'
log_file = 'tsc-dashboard.log'
fixed_rows = 16
initial_row = 2
fixed_columns = 22
initial_column = 1 |
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
rls = [[1]]
for i in range(2, numRows+1):
row = [1] * i
for j in range(1, i-1):
row[j] = rls[-1][j-1] + rls[-1][j]
rls.append(row)
return rls
| class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
rls = [[1]]
for i in range(2, numRows + 1):
row = [1] * i
for j in range(1, i - 1):
row[j] = rls[-1][j - 1] + rls[-1][j]
rls.append(row)
return rls |
def maxProfitWithKTransactions(prices, k):
n = len(prices)
profit = [[0]*n for _ in range(k+1)]
"""
t := number of transactions
d := day at which either buy/sell stock
profit[t][d] = max ( previous day profit = profit[t][d-1] ,
profit sold at this day + max(buy for this transaction + profit at last transaction)
prices[d] + max(-prices[x] + profit[t-1][x], where 0 <= x < d)
"""
if not prices:
return 0
for t in range(1, k+1):
for d in range(1, n):
previous_day_profit = profit[t][d-1]
max_profit_buy_on_t = float("-inf")
for x in range(0, d):
max_profit_buy_on_t = max(max_profit_buy_on_t, -prices[x] + profit[t-1][x])
profit[t][d] = max(previous_day_profit, prices[d] + max_profit_buy_on_t)
debug = False
if debug:
print(prices)
for row in profit:
print(row)
print("Maximum profit for k={} transaction for {} stock prices at each day = {}".format(k, prices, profit[-1][-1] if profit else 0))
return profit[-1][-1]
if __name__ == "__main__":
maxProfitWithKTransactions([5, 11, 3, 50, 60, 90], 2)
| def max_profit_with_k_transactions(prices, k):
n = len(prices)
profit = [[0] * n for _ in range(k + 1)]
'\n t := number of transactions\n d := day at which either buy/sell stock\n\n profit[t][d] = max ( previous day profit = profit[t][d-1] ,\n\n profit sold at this day + max(buy for this transaction + profit at last transaction)\n prices[d] + max(-prices[x] + profit[t-1][x], where 0 <= x < d)\n '
if not prices:
return 0
for t in range(1, k + 1):
for d in range(1, n):
previous_day_profit = profit[t][d - 1]
max_profit_buy_on_t = float('-inf')
for x in range(0, d):
max_profit_buy_on_t = max(max_profit_buy_on_t, -prices[x] + profit[t - 1][x])
profit[t][d] = max(previous_day_profit, prices[d] + max_profit_buy_on_t)
debug = False
if debug:
print(prices)
for row in profit:
print(row)
print('Maximum profit for k={} transaction for {} stock prices at each day = {}'.format(k, prices, profit[-1][-1] if profit else 0))
return profit[-1][-1]
if __name__ == '__main__':
max_profit_with_k_transactions([5, 11, 3, 50, 60, 90], 2) |
# 11. Replace tabs into spaces
# Replace every occurrence of a tab character into a space. Confirm the result by using sed, tr, or expand command.
with open('popular-names.txt') as f:
for line in f:
print(line.strip().replace("\t", " "))
| with open('popular-names.txt') as f:
for line in f:
print(line.strip().replace('\t', ' ')) |
""" Test data"""
stub_films = [{
"id": "12345",
"title": "This is film one",
},{
"id": "23456",
"title": "This is film two",
}]
stub_poeple = [{
"name": "person 1",
"films": ["url/12345", "url/23456"]
},{
"name": "person 2",
"films": ["url/23456"]
},{
"name": "person 3",
"films": ["url/12345"]
},{
"name": "person 4",
"films": ["url/12345"]
}] | """ Test data"""
stub_films = [{'id': '12345', 'title': 'This is film one'}, {'id': '23456', 'title': 'This is film two'}]
stub_poeple = [{'name': 'person 1', 'films': ['url/12345', 'url/23456']}, {'name': 'person 2', 'films': ['url/23456']}, {'name': 'person 3', 'films': ['url/12345']}, {'name': 'person 4', 'films': ['url/12345']}] |
s = input()
num = [0] * 26
for i in range(len(s)):
num[ord(s[i])-97] += 1
for i in num:
print(i, end = " ")
if i == len(num)-1:
print(i)
| s = input()
num = [0] * 26
for i in range(len(s)):
num[ord(s[i]) - 97] += 1
for i in num:
print(i, end=' ')
if i == len(num) - 1:
print(i) |
# Source : https://leetcode.com/problems/binary-tree-tilt/description/
# Date : 2017-12-26
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global ans
ans = 0
self.sumOfNode(root)
return ans
def sumOfNode(self, root):
if root == None:
return 0
left = self.sumOfNode(root.left)
right = self.sumOfNode(root.right)
global ans
ans += abs(left - right)
return left + right + root.val
| class Solution:
def find_tilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global ans
ans = 0
self.sumOfNode(root)
return ans
def sum_of_node(self, root):
if root == None:
return 0
left = self.sumOfNode(root.left)
right = self.sumOfNode(root.right)
global ans
ans += abs(left - right)
return left + right + root.val |
class Order():
def __init__(self, side, pair, size, price, stop_loss_price, id):
self.side = side
self.pair = pair
self.size = size
self.price = price
self.stop_loss_price = stop_loss_price
self.id = id
self.fills = []
def define_id(self, id):
self.id = id
def add_fill(self, execution):
self.fills.append(execution)
def get_fill_price(self):
nominator = sum(map(lambda f: f.size * f.price, self.fills))
fill_price = nominator/self.get_filled_quantity()
return fill_price
def get_filled_quantity(self):
return sum(map(lambda f: f.size, self.fills))
def get_fills(self):
return self.fills
| class Order:
def __init__(self, side, pair, size, price, stop_loss_price, id):
self.side = side
self.pair = pair
self.size = size
self.price = price
self.stop_loss_price = stop_loss_price
self.id = id
self.fills = []
def define_id(self, id):
self.id = id
def add_fill(self, execution):
self.fills.append(execution)
def get_fill_price(self):
nominator = sum(map(lambda f: f.size * f.price, self.fills))
fill_price = nominator / self.get_filled_quantity()
return fill_price
def get_filled_quantity(self):
return sum(map(lambda f: f.size, self.fills))
def get_fills(self):
return self.fills |
word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break | word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break |
# Copyright 2021 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
_RTOS_NONE = "//pw_build/constraints/rtos:none"
# Common select for tagging a target as only compatible with host OS's. This
# select implements the logic '(Windows or Macos or Linux) and not RTOS'.
# Example usage:
# load("//pw_build:selects.bzl","TARGET_COMPATIBLE_WITH_HOST_SELECT")
# pw_cc_library(
# name = "some_host_only_lib",
# hdrs = ["host.h"],
# target_compatible_with = select(TARGET_COMPATIBLE_WITH_HOST_SELECT),
# )
TARGET_COMPATIBLE_WITH_HOST_SELECT = {
"@platforms//os:windows": [_RTOS_NONE],
"@platforms//os:macos": [_RTOS_NONE],
"@platforms//os:linux": [_RTOS_NONE],
"//conditions:default": ["@platforms//:incompatible"],
}
| _rtos_none = '//pw_build/constraints/rtos:none'
target_compatible_with_host_select = {'@platforms//os:windows': [_RTOS_NONE], '@platforms//os:macos': [_RTOS_NONE], '@platforms//os:linux': [_RTOS_NONE], '//conditions:default': ['@platforms//:incompatible']} |
def factorial(n):
fact = 1
for i in range(2,n+1):
fact*= i
return fact
def main():
n = int(input("Enter a number: "))
if n >= 0:
print(f"Factorial: {factorial(n)}")
else:
print(f"Choose another number")
if __name__ == "__main__":
main()
| def factorial(n):
fact = 1
for i in range(2, n + 1):
fact *= i
return fact
def main():
n = int(input('Enter a number: '))
if n >= 0:
print(f'Factorial: {factorial(n)}')
else:
print(f'Choose another number')
if __name__ == '__main__':
main() |
users = []
class UserModel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {
"userId": len(self.db)+1,
"fname": fname,
"lname": lname,
"email": email,
"phone": phone,
"password": password,
"confirm_password": confirm_password,
"city": city,
}
self.db.append(payload)
return self.db
def check_email(self, email):
"""Method for checking if user email exist"""
user = [user for user in users if user['email'] == email]
if user:
return True
return False
def check_user(self, userId):
"""Method for checking if user exist"""
user = [user for user in users if user['userId'] == userId]
if user:
return True
return False
| users = []
class Usermodel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {'userId': len(self.db) + 1, 'fname': fname, 'lname': lname, 'email': email, 'phone': phone, 'password': password, 'confirm_password': confirm_password, 'city': city}
self.db.append(payload)
return self.db
def check_email(self, email):
"""Method for checking if user email exist"""
user = [user for user in users if user['email'] == email]
if user:
return True
return False
def check_user(self, userId):
"""Method for checking if user exist"""
user = [user for user in users if user['userId'] == userId]
if user:
return True
return False |
"""
Entradas:
lectura actual--->float--->lect2
lectura anterior--->float--->lect1
valor kw--->float--->valorkw
Salidas:
consumo--->float--->consumo
total factura-->flotante--->total
"""
lect2 = float ( entrada ( "Digite lectura real:" ))
lect1 = float ( entrada ( "Digite lectura anterior:" ))
valorkw = float ( input ( "Valor del kilowatio: " ))
consumo = ( lect2 - lect1 )
total = ( consumo * valorkw )
print ( "El valor a pagar es: " + str ( total )) | """
Entradas:
lectura actual--->float--->lect2
lectura anterior--->float--->lect1
valor kw--->float--->valorkw
Salidas:
consumo--->float--->consumo
total factura-->flotante--->total
"""
lect2 = float(entrada('Digite lectura real:'))
lect1 = float(entrada('Digite lectura anterior:'))
valorkw = float(input('Valor del kilowatio: '))
consumo = lect2 - lect1
total = consumo * valorkw
print('El valor a pagar es: ' + str(total)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.