content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def main(urd):
# First, create a new dataset.
# Second, create a second dataset chained to the first
print('\n# Run a method that creates a dataset')
job = urd.build('example10')
print('# (Now, test "bd dsinfo %s" to inspect the dataset!)' % (job,))
print('\n# Run a method that creates a datasets and chains it... | def main(urd):
print('\n# Run a method that creates a dataset')
job = urd.build('example10')
print('# (Now, test "bd dsinfo %s" to inspect the dataset!)' % (job,))
print('\n# Run a method that creates a datasets and chains it to the previous one.')
job = urd.build('example12', datasets=dict(previous... |
class StateMachine(object):
def __init__(self, initial_state):
self.state = initial_state
def testBehaviour(self):
return self.state.testBehaviour()
| class Statemachine(object):
def __init__(self, initial_state):
self.state = initial_state
def test_behaviour(self):
return self.state.testBehaviour() |
class UiMessage:
def __init__(self, content):
self.system_seat_ids = content['systemSeatIds']
self.on_generic_event = content['uiMessage'].get('onGenericEvent')
self.on_hover = content['uiMessage'].get('onHover')
| class Uimessage:
def __init__(self, content):
self.system_seat_ids = content['systemSeatIds']
self.on_generic_event = content['uiMessage'].get('onGenericEvent')
self.on_hover = content['uiMessage'].get('onHover') |
# -*- coding: utf-8 -*-
def frequency_sort(items):
items=sorted(items, key=items.index)
return sorted(items,key=items.count,reverse=True)
# another pattern
return sorted(items, key=lambda x: (-items.count(x), items.index(x)))
if __name__ == '__main__':
print("Example:")
print(frequency_sort(... | def frequency_sort(items):
items = sorted(items, key=items.index)
return sorted(items, key=items.count, reverse=True)
return sorted(items, key=lambda x: (-items.count(x), items.index(x)))
if __name__ == '__main__':
print('Example:')
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
assert list(fre... |
class Fizz:
foo = {}
bar = 42
obj1 = Fizz()
obj1.foo["abc"] = 123
obj1.bar += 1
obj2 = Fizz()
# What is the output of these two calls to print?
print(obj2.foo["abc"])
print(obj2.bar)
| class Fizz:
foo = {}
bar = 42
obj1 = fizz()
obj1.foo['abc'] = 123
obj1.bar += 1
obj2 = fizz()
print(obj2.foo['abc'])
print(obj2.bar) |
primeFactors = []
number = 600851475143
counter = 0
iterationRecord = 0
for i in range(1, number+1):
if i - iterationRecord >= counter:
print(chr(27) + "[2J")
print("The calculations have progressed by %s percent." % str(i / number * 100)[0:5])
print("This is loop iteration number %d out of ... | prime_factors = []
number = 600851475143
counter = 0
iteration_record = 0
for i in range(1, number + 1):
if i - iterationRecord >= counter:
print(chr(27) + '[2J')
print('The calculations have progressed by %s percent.' % str(i / number * 100)[0:5])
print('This is loop iteration number %d out... |
rad=int(input("enter radius:"))
area=3.14*rad*rad
circum=2*3.14*rad
print("area of circle:",area)
print("circumference of circle:",circum)
| rad = int(input('enter radius:'))
area = 3.14 * rad * rad
circum = 2 * 3.14 * rad
print('area of circle:', area)
print('circumference of circle:', circum) |
for _ in range(int(input())):
a="".join(input().split()).lower()
L=['a','e','i','o','u']
c=0
for i in L:
c+=a.count(i)
print(len(a)-c,c) | for _ in range(int(input())):
a = ''.join(input().split()).lower()
l = ['a', 'e', 'i', 'o', 'u']
c = 0
for i in L:
c += a.count(i)
print(len(a) - c, c) |
name = 'localeurl'
authors = 'Joost Cassee and Artiom Diomin'
version = 'trunk'
release = version
| name = 'localeurl'
authors = 'Joost Cassee and Artiom Diomin'
version = 'trunk'
release = version |
def add(a,b) :
if isinstance(a, (int,float)) and isinstance(b,(int,float)) :
return a+b
return
def sub(a,b) :
if isinstance(a, (int,float)) and isinstance(b,(int,float)) :
return a-b
return
def mul(a,b) :
if isinstance(a, (int,float)) and isinstance(b,(int,float)) :
... | def add(a, b):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a + b
return
def sub(a, b):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a - b
return
def mul(a, b):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
... |
def filtrar_palabra(lista, fin, n):
num = 0
while num <= (fin-1):
if len(lista[num]) <= n :
lista.pop(num)
num = 0
fin -= 1
print (lista)
else:
num += 1
print("Tus palabras con", n ,"letras o mas, son:", lista)
lista = []
num = 1
fin = int (input ("Dame la cantidad de palabras a filtr... | def filtrar_palabra(lista, fin, n):
num = 0
while num <= fin - 1:
if len(lista[num]) <= n:
lista.pop(num)
num = 0
fin -= 1
print(lista)
else:
num += 1
print('Tus palabras con', n, 'letras o mas, son:', lista)
lista = []
num = 1
fin ... |
# To enter any character and print it's upper case and lower case
x = input("Enter the symbol to be checked: ")
if x >= 'A' and x <= 'Z':
print(x ," is an Uppercase character")
elif x >= 'a' and x <= 'z':
print(x , "is an lower case character")
else:
("Invalid Input")
| x = input('Enter the symbol to be checked: ')
if x >= 'A' and x <= 'Z':
print(x, ' is an Uppercase character')
elif x >= 'a' and x <= 'z':
print(x, 'is an lower case character')
else:
'Invalid Input' |
class Node:
def __init__(self, data):
self.data = data
self.neighbors = []
def add_neighbor(self, new_node):
self.neighbors.append(new_node)
def __repr__(self):
return self.data
class Graph:
def __init__(self):
self.nodes = []
def add_node(self, node):
self.nodes.append(node... | class Node:
def __init__(self, data):
self.data = data
self.neighbors = []
def add_neighbor(self, new_node):
self.neighbors.append(new_node)
def __repr__(self):
return self.data
class Graph:
def __init__(self):
self.nodes = []
def add_node(self, node):
... |
class SemanticTypes:
PROGRAM = "program"
VARIABLE = "variable"
EMPTY = "empty"
VARS_DECLARATION = "vars_declaration"
FUNCTION_DECLARATION = "function_declaration"
IF_ELSE_DECLARATION = "if_else_declaration"
REPEAT_DECLARATION = "repeat_declaration"
RETURN_DECLARATION = "return_declarati... | class Semantictypes:
program = 'program'
variable = 'variable'
empty = 'empty'
vars_declaration = 'vars_declaration'
function_declaration = 'function_declaration'
if_else_declaration = 'if_else_declaration'
repeat_declaration = 'repeat_declaration'
return_declaration = 'return_declaratio... |
COUNTRY_CODES = [
{"Name":"Afghanistan", "Code":"AF"},
{"Name":"Aland Islands", "Code":"AX"},
{"Name":"Albania", "Code":"AL"},
{"Name":"Algeria", "Code":"DZ"},
{"Name":"American Samoa", "Code":"AS"},
{"Name":"Andorra", "Code":"AD"},
{"Name":"Angola", "Code":"AO"},
{"Name":"Anguilla", "Co... | country_codes = [{'Name': 'Afghanistan', 'Code': 'AF'}, {'Name': 'Aland Islands', 'Code': 'AX'}, {'Name': 'Albania', 'Code': 'AL'}, {'Name': 'Algeria', 'Code': 'DZ'}, {'Name': 'American Samoa', 'Code': 'AS'}, {'Name': 'Andorra', 'Code': 'AD'}, {'Name': 'Angola', 'Code': 'AO'}, {'Name': 'Anguilla', 'Code': 'AI'}, {'Name... |
class DirectTreeGenotypeConfig():
def __init__(self,
max_parts: int = 50,
min_parts: int = 10,
max_oscillation: float = 5,
init_n_parts_mu: float = 10,
init_n_parts_sigma: float = 4,
init_prob_no_child: float = 0.... | class Directtreegenotypeconfig:
def __init__(self, max_parts: int=50, min_parts: int=10, max_oscillation: float=5, init_n_parts_mu: float=10, init_n_parts_sigma: float=4, init_prob_no_child: float=0.1, init_prob_child_active_joint: float=0.4, init_prob_child_linear_joint: float=0, init_prob_child_block: float=0.5,... |
class BinaryTree:
def __init__(self,root):
self.key=root
self.leftChild=None
self.rightChild=None
def insertLeft(self,root):
if self.leftChild==None:
self.leftChild=BinaryTree(root)
else:
tempNode=BinaryTree(root)
tempNode.leftChild=self.leftChild
self.leftChild=tempNode
def insertRight(self,ro... | class Binarytree:
def __init__(self, root):
self.key = root
self.leftChild = None
self.rightChild = None
def insert_left(self, root):
if self.leftChild == None:
self.leftChild = binary_tree(root)
else:
temp_node = binary_tree(root)
te... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
@lru_cache(None)
def dp(i, j):
if j == len(p): return i == len(s)
fm = i < len(s) and (p[j] == s[i] or p[j] == '.')
if j + 1 < len(p) and p[j + 1] == '*':
return dp(i, j + 2) or fm and dp(... | class Solution:
def is_match(self, s: str, p: str) -> bool:
@lru_cache(None)
def dp(i, j):
if j == len(p):
return i == len(s)
fm = i < len(s) and (p[j] == s[i] or p[j] == '.')
if j + 1 < len(p) and p[j + 1] == '*':
return dp(i, j ... |
class Solution:
def maxProduct(self, nums: List[int]) -> int:
first = 0
second = 0
for num in nums:
if num > first:
second = first
first = num
else:
if num > second:
second = num
return (first... | class Solution:
def max_product(self, nums: List[int]) -> int:
first = 0
second = 0
for num in nums:
if num > first:
second = first
first = num
elif num > second:
second = num
return (first - 1) * (second - 1) |
total18 = homem_total = mulher20_total = idade = 0
while True:
texto = 'CADASTRO DE PESSOAS'
print('-=' * 20)
print(f'{texto:^40}')
print('-=' * 20)
idade = int(input('Idade: '))
sexo = ' '
if idade > 18:
total18 += 1
while sexo not in 'MF':
sexo = str(input('Sexo[M/F]: ... | total18 = homem_total = mulher20_total = idade = 0
while True:
texto = 'CADASTRO DE PESSOAS'
print('-=' * 20)
print(f'{texto:^40}')
print('-=' * 20)
idade = int(input('Idade: '))
sexo = ' '
if idade > 18:
total18 += 1
while sexo not in 'MF':
sexo = str(input('Sexo[M/F]: '... |
'''
Created on Nov 13, 2015
@author: Vlad
'''
class Client:
def __init__(self, id_client, name):
'''
Client object
:param id_client: inte
:param name:
:return:
'''
self.__id_client = id_client
self.__name = name
@property
def id_client(self):
'''
Getter for the id of the client
:retu... | """
Created on Nov 13, 2015
@author: Vlad
"""
class Client:
def __init__(self, id_client, name):
"""
Client object
:param id_client: inte
:param name:
:return:
"""
self.__id_client = id_client
self.__name = name
@property
def id_client(self):
"""
Getter for t... |
def tts(data, p=.75):
N = data.shape[0]
train_idxs, test_idxs = get_indeces(N, p)
train = data[train_idxs]
test = data[test_idxs]
y_train = train[:, -1]
y_test = test[:, -1]
X_train = train[:, :-1]
X_test = test[:, :-1]
return X_train, X_test, y_train, ... | def tts(data, p=0.75):
n = data.shape[0]
(train_idxs, test_idxs) = get_indeces(N, p)
train = data[train_idxs]
test = data[test_idxs]
y_train = train[:, -1]
y_test = test[:, -1]
x_train = train[:, :-1]
x_test = test[:, :-1]
return (X_train, X_test, y_train, y_test) |
full_name = input("Enter full name, split up with a space: ")
space_index = full_name.find(" ")
first_name = full_name[:space_index]
last_name = full_name[space_index + 1:]
initials = first_name[0] + last_name[0]
print("First name:", first_name)
print("Last name:", last_name)
print("Initials", initials) | full_name = input('Enter full name, split up with a space: ')
space_index = full_name.find(' ')
first_name = full_name[:space_index]
last_name = full_name[space_index + 1:]
initials = first_name[0] + last_name[0]
print('First name:', first_name)
print('Last name:', last_name)
print('Initials', initials) |
galactic_search = [
(2.5, 10),
(2.5, 5),
(27.5, 10),
(27.5, 5)
]
barrel_racing = [
(2.5, 10),
(2.5, 5),
(5, 10),
(5, 5),
(12.5, 5),
(20, 10),
(25, 5)
]
slalom = [
(2.5, 10),
(2.5, 5),
(5, 10),
(5, 5),
(10, 5),
(12.5, 5),
(15, 5),
(17.5, 5),
... | galactic_search = [(2.5, 10), (2.5, 5), (27.5, 10), (27.5, 5)]
barrel_racing = [(2.5, 10), (2.5, 5), (5, 10), (5, 5), (12.5, 5), (20, 10), (25, 5)]
slalom = [(2.5, 10), (2.5, 5), (5, 10), (5, 5), (10, 5), (12.5, 5), (15, 5), (17.5, 5), (20, 5), (25, 5)]
bounce = [(2.5, 10), (2.5, 5), (5, 10), (5, 5), (7.5, 2.5), (7.5, ... |
n = int(input())
L = [int(input()) for i in range(n)]
cnt = 0
while True:
M = max(L)
if L.count(M) == 1 and L[0] == M:
print(cnt)
break
cnt+=1
L[L.index(M,1,len(L))]-=1
L[0]+=1
| n = int(input())
l = [int(input()) for i in range(n)]
cnt = 0
while True:
m = max(L)
if L.count(M) == 1 and L[0] == M:
print(cnt)
break
cnt += 1
L[L.index(M, 1, len(L))] -= 1
L[0] += 1 |
Cost_of_one_computer = float(input("Enter the cost of one computer : Rs."))
Number_of_computers = int(input("Enter the number of computers : "))
Cost_of_one_table = float(input("Enter the cost of one table : Rs."))
Number_of_tables = int(input("Enter the number of tables : "))
Cost_of_one_chair = float(input("Enter... | cost_of_one_computer = float(input('Enter the cost of one computer : Rs.'))
number_of_computers = int(input('Enter the number of computers : '))
cost_of_one_table = float(input('Enter the cost of one table : Rs.'))
number_of_tables = int(input('Enter the number of tables : '))
cost_of_one_chair = float(input('Enter the... |
#Config for django-cities-light
#http://django-cities-light.readthedocs.io/en/stable-3.x.x/full.html
CITIES_LIGHT_TRANSLATION_LANGUAGES = ['es', 'en']
CITIES_LIGHT_APP_NAME = 'catalogues'
CITIES_LIGHT_INCLUDE_COUNTRIES = ['MX']
#End config for django-cities-light | cities_light_translation_languages = ['es', 'en']
cities_light_app_name = 'catalogues'
cities_light_include_countries = ['MX'] |
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
result = [0 for _ in range(len(num1) + len(num2))]
for index_1 in range(len(num1) - 1, -1, -1):
for index_2 in range(len(num2) - 1, -1, -1):
mul ... | class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
result = [0 for _ in range(len(num1) + len(num2))]
for index_1 in range(len(num1) - 1, -1, -1):
for index_2 in range(len(num2) - 1, -1, -1):
mul... |
def finish_off(handle1, handle2, name1, name2, rating1, rating2, dic1, dic2, lis1, lis2, result):
par1 = 0
par2 = 0
result = result + "Handle : " + handle1 + "\n"
result = result + "Name : " + name1+ "\n"
result = result + "Current ratings : " + rating1 + '\n'
result = result + "\n"
result = result + "Handle :... | def finish_off(handle1, handle2, name1, name2, rating1, rating2, dic1, dic2, lis1, lis2, result):
par1 = 0
par2 = 0
result = result + 'Handle : ' + handle1 + '\n'
result = result + 'Name : ' + name1 + '\n'
result = result + 'Current ratings : ' + rating1 + '\n'
result = result + '\n'
result ... |
# -*- coding: utf-8 -*-
'''
You need to count the number of digits in a given string.
Input: A Str.
Output: An Int.
'''
def count_digits(text):
# your code here
count = 0
for word in text:
if word.isdigit():
count += 1
return count
if __name__ == '__main__':
print("Example... | """
You need to count the number of digits in a given string.
Input: A Str.
Output: An Int.
"""
def count_digits(text):
count = 0
for word in text:
if word.isdigit():
count += 1
return count
if __name__ == '__main__':
print('Example:')
print(count_digits('hi'))
assert count... |
HEIGHT = 68
WIDTH = 8
# aspect ratio of device is
# 5 1/8" / 130.175mm horizontal spacing (measured)
# 17mm vertical spacing per adafruit,
ASPECT = 130.175 / 17
HYDRA_STATE_FILE = '/srv/hydra/hydra.state'
# HYDRA_STATE_FILE = f'{os.getenv("HOME")}/.hydra.state'
| height = 68
width = 8
aspect = 130.175 / 17
hydra_state_file = '/srv/hydra/hydra.state' |
# def keyword defines function
# statements belonging to a function have to be indented
# PEP8 (beauty standard) requires 2 white spaces after function definition
# declaration precedence is required (makes sense, it's an interpreter)
def greet_user():
print("Hi there!")
print("Welcome aboard!")
print("Star... | def greet_user():
print('Hi there!')
print('Welcome aboard!')
print('Start')
greet_user()
print('Finish') |
TemperatureProvider = provider(fields = ['type'])
temperatures = ["HOT", "LUKEWARM", "ICED"]
def _impl(ctx):
# use `ctx.build_setting_value` to access the raw value
# of this build setting. This value is either derived from
# the default value set on the target or from the setting
# being set somewhe... | temperature_provider = provider(fields=['type'])
temperatures = ['HOT', 'LUKEWARM', 'ICED']
def _impl(ctx):
raw_temperature = ctx.build_setting_value
if raw_temperature not in temperatures:
fail(str(ctx.label) + ' build setting allowed to take values {' + ', '.join(temperatures) + '} but was set to una... |
#! /usr/bin/python3
ALPH = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
with open('.gitignore', 'w') as file:
file.write('.gitignore\n')
file.writelines([f'{x}.cc\n' for x in ALPH])
if __name__ == '__main__':
main() | alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
with open('.gitignore', 'w') as file:
file.write('.gitignore\n')
file.writelines([f'{x}.cc\n' for x in ALPH])
if __name__ == '__main__':
main() |
def main(j, args, params, tags, tasklet):
session = args.requestContext.env['beaker.session']
msg = "h4. Access Denied"
if j.core.portal.active.isLoggedInFromCTX(args.requestContext):
msg += " - [Logout|/system/login?user_logoff_=1]"
else:
loginurl = j.core.portal.active.force_oauth_ur... | def main(j, args, params, tags, tasklet):
session = args.requestContext.env['beaker.session']
msg = 'h4. Access Denied'
if j.core.portal.active.isLoggedInFromCTX(args.requestContext):
msg += ' - [Logout|/system/login?user_logoff_=1]'
else:
loginurl = j.core.portal.active.force_oauth_url ... |
input=__import__('sys').stdin.readline
r,c=map(int,input().split());g=[list(input()) for _ in range(r)]
visited=[[False]*c for _ in range(r)]
def bfs(i,j):
v=0;o=0;q=[]
visited[i][j]=True
q.append((i,j))
while len(q):
x,y=q.pop(0);t=g[x][y]
visited[x][y]=True
if t=='v': v+=1
... | input = __import__('sys').stdin.readline
(r, c) = map(int, input().split())
g = [list(input()) for _ in range(r)]
visited = [[False] * c for _ in range(r)]
def bfs(i, j):
v = 0
o = 0
q = []
visited[i][j] = True
q.append((i, j))
while len(q):
(x, y) = q.pop(0)
t = g[x][y]
... |
#Soma
tabb = [1+1]
tab = [2+1]
tab_2 = [3+1]
tab_3 = [4+1]
tab_4 = [5+1]
tab_5 = [6+1]
tab_6 = [7+1]
tab_7 = [8+1]
tab_8 = [9+1]
tab_9 = [10+1]
for y in tabb:
print("1+1 = {}".format(y))
for i in tab:
print("2+1 = {}".format(i))
for a in tab_2:
print("3+1 = {}".format(a))
for b in tab_3:
print("4+1 = {... | tabb = [1 + 1]
tab = [2 + 1]
tab_2 = [3 + 1]
tab_3 = [4 + 1]
tab_4 = [5 + 1]
tab_5 = [6 + 1]
tab_6 = [7 + 1]
tab_7 = [8 + 1]
tab_8 = [9 + 1]
tab_9 = [10 + 1]
for y in tabb:
print('1+1 = {}'.format(y))
for i in tab:
print('2+1 = {}'.format(i))
for a in tab_2:
print('3+1 = {}'.format(a))
for b in tab_3:
p... |
class Vertex:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
def bambora(v):
v.x = 5
v.y = 5
v1 = Vertex(1,3)
v2 = v1
v1 = Vertex(5,4)
print(v1)
print(v2)
# print(v1)
# bambora(v1)
# print(v1)
| class Vertex:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def bambora(v):
v.x = 5
v.y = 5
v1 = vertex(1, 3)
v2 = v1
v1 = vertex(5, 4)
print(v1)
print(v2) |
mse = np.zeros((max_order + 1))
for order in range(0, max_order + 1):
X_design = make_design_matrix(x, order)
# Get prediction for the polynomial regression model of this order
y_hat = X_design @ theta_hats[order]
# Compute the residuals
residuals = y - y_hat
# Compute the MSE
mse[order] = np.mean(res... | mse = np.zeros(max_order + 1)
for order in range(0, max_order + 1):
x_design = make_design_matrix(x, order)
y_hat = X_design @ theta_hats[order]
residuals = y - y_hat
mse[order] = np.mean(residuals ** 2)
with plt.xkcd():
(fig, ax) = plt.subplots()
ax.bar(range(max_order + 1), mse)
ax.set(tit... |
WINDOW_SIZE = 2
MAX_SEQ_NO = 2*WINDOW_SIZE
SERVER_MAX_RETRIES = 10
SERVER_RECV_TIMEOUT = 1.0
SERVER_TIMER_THREAD_TIMEOUT = 1.0
SERVER_FILE_NOT_FOUND = 5
SERVER_END_PACKET = 2
SERVER_END_ABNORMAL = 3
SERVER_BUFFER_SIZE = 4096
CLIENT_MAX_RETRIES = 10
CLIENT_REQUEST_RETRIES = 2
CLIENT_RECV_TIMEOUT = 0.4
CL... | window_size = 2
max_seq_no = 2 * WINDOW_SIZE
server_max_retries = 10
server_recv_timeout = 1.0
server_timer_thread_timeout = 1.0
server_file_not_found = 5
server_end_packet = 2
server_end_abnormal = 3
server_buffer_size = 4096
client_max_retries = 10
client_request_retries = 2
client_recv_timeout = 0.4
client_buffer_si... |
environ = {}
def getcwd():
pass
| environ = {}
def getcwd():
pass |
pessoas = []
pessoa = []
resposta = str
pesomin = 1000
pessoamin = []
pesomax = 0
pessoamax = []
count = 0
peso = int
nome = str
while resposta != 'n' and resposta != 'N':
nome = (input('Digite o nome da pessoa: '))
peso = (int(input('Digite a peso da pessoa: ')))
pessoa.append(nome)
pessoa.append(peso)... | pessoas = []
pessoa = []
resposta = str
pesomin = 1000
pessoamin = []
pesomax = 0
pessoamax = []
count = 0
peso = int
nome = str
while resposta != 'n' and resposta != 'N':
nome = input('Digite o nome da pessoa: ')
peso = int(input('Digite a peso da pessoa: '))
pessoa.append(nome)
pessoa.append(peso)
... |
# Project Euler: Problem 2
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
sum = 0
f = 1
s = 2
x = s
while x < 4000000:
if x % 2 == 0:
sum += x
x = f + s
f, s = s, x
print(sum)
| sum = 0
f = 1
s = 2
x = s
while x < 4000000:
if x % 2 == 0:
sum += x
x = f + s
(f, s) = (s, x)
print(sum) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"assert_allclose": "utils.ipynb",
"get_colors": "utils.ipynb",
"get_notebook_file": "utils.ipynb",
"save_notebook": "utils.ipynb",
"build_notebook": "utils.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'assert_allclose': 'utils.ipynb', 'get_colors': 'utils.ipynb', 'get_notebook_file': 'utils.ipynb', 'save_notebook': 'utils.ipynb', 'build_notebook': 'utils.ipynb', 'convert_notebook': 'utils.ipynb', 'MyDisjointSet': 'module3.ipynb', 'MyDisjointSet2'... |
#MDCLXVI
#M = 1000
#D = 500
#C = 100
#L = 50
#X = 10
#V = 5
#I = 1
class romanTOint():
def __init__(self,roman):
self.roman = roman
def romantoint(self):
roman_list = ['I','V','X','L','C','D','M']
roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
roman = self.roman
if len(roman) == 1:
... | class Romantoint:
def __init__(self, roman):
self.roman = roman
def romantoint(self):
roman_list = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
roman = self.roman
if len(roman) == 1:
retur... |
workers = 1
bind = 'unix:erp-mobilidade.sock'
umask = 0o007
reload = True
#logging
accesslog = '-'
| workers = 1
bind = 'unix:erp-mobilidade.sock'
umask = 7
reload = True
accesslog = '-' |
# Author: Adomous Wright
# Date: 12/25/17
# Make a guest list and print a message indicating the number of guests
guests = ['Ryan','Patrick','Bob']
num_guests = len(guests)
print("There are", num_guests,"guests that will be attending the dinner party.")
| guests = ['Ryan', 'Patrick', 'Bob']
num_guests = len(guests)
print('There are', num_guests, 'guests that will be attending the dinner party.') |
# Left Rotation
# Given an array and a number, d, perform d left rotations on the array.
#
# https://www.hackerrank.com/challenges/array-left-rotation/problem
#
def rotate(l, n):
n = n % len(l)
return l[n:] + l[:n]
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
... | def rotate(l, n):
n = n % len(l)
return l[n:] + l[:n]
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().split()))
a = rotate(a, d)
print(' '.join(map(str, a))) |
#Implementation of the queue
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue) < 1
def show(self):
for i in range(len(sel... | class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def is_empty(self):
return len(self.queue) < 1
def show(self):
... |
hokages = {
"Hashirama", "Tobirama", "Hiruzen", "Minato"
}
print(type(hokages))
print(hokages)
hokages.add("Tsunade")
hokages.add("Kakashi")
print(hokages) | hokages = {'Hashirama', 'Tobirama', 'Hiruzen', 'Minato'}
print(type(hokages))
print(hokages)
hokages.add('Tsunade')
hokages.add('Kakashi')
print(hokages) |
f = open('Conventions.txt','r')
message = f.read()
print(message)
f.close()
print (message.splitlines())
| f = open('Conventions.txt', 'r')
message = f.read()
print(message)
f.close()
print(message.splitlines()) |
text = "kdnaifsiugsj: 203209"
text = slice(text, text.find(":"))
print(text)
| text = 'kdnaifsiugsj: 203209'
text = slice(text, text.find(':'))
print(text) |
word_list = ["Life", "is", "short"]
def print_a_word(word_list):
if not word_list:
return
else:
print(word_list.pop(), end=" ")
print_a_word(word_list)
print_a_word(word_list[::-1])
| word_list = ['Life', 'is', 'short']
def print_a_word(word_list):
if not word_list:
return
else:
print(word_list.pop(), end=' ')
print_a_word(word_list)
print_a_word(word_list[::-1]) |
def get_square_3x3(grid, row, column):
square = []
if row<3:
if column < 3:
square = [grid[i][0:3] for i in range(0, 3)]
elif column<6:
square = [grid[i][3:6] for i in range(0, 3)]
else:
square = [grid[i][6:9] for i in range(0, 3)]
elif row<6:
... | def get_square_3x3(grid, row, column):
square = []
if row < 3:
if column < 3:
square = [grid[i][0:3] for i in range(0, 3)]
elif column < 6:
square = [grid[i][3:6] for i in range(0, 3)]
else:
square = [grid[i][6:9] for i in range(0, 3)]
elif row < 6... |
_base_ = [
'../../_dynamic_/models/faster_rcnn_fpn_ar50to101_gsync.py',
'../../_dynamic_/model_samplers/ar50to101_flops.py',
'../../_base_/default_runtime.py',
]
| _base_ = ['../../_dynamic_/models/faster_rcnn_fpn_ar50to101_gsync.py', '../../_dynamic_/model_samplers/ar50to101_flops.py', '../../_base_/default_runtime.py'] |
def prime(n):
if n == 2:
return True
if n % 2 == 0 or n == 1:
return False
for i in range(3, int(n ** .5) + 1, 2):
if n % i == 0:
return False
return True
def nthprime(n):
c, nth = 1, 3
while c < n:
if prime(nth):
c += 1
nth += 2
return nth - 2
print(nthprime(10001))
| def prime(n):
if n == 2:
return True
if n % 2 == 0 or n == 1:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def nthprime(n):
(c, nth) = (1, 3)
while c < n:
if prime(nth):
c += 1
nth +... |
class APIPerformanceTime:
def __init__(self):
self.project_name = None
self.mined_entity_directory = None
self.xml_conv_overhead_time = 0.0
self.mining_time = 0.0
self.tot_attr_processing_time = 0.0
self.tot_src_files_processed = 0
self.tot_packages_processed... | class Apiperformancetime:
def __init__(self):
self.project_name = None
self.mined_entity_directory = None
self.xml_conv_overhead_time = 0.0
self.mining_time = 0.0
self.tot_attr_processing_time = 0.0
self.tot_src_files_processed = 0
self.tot_packages_processed... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
new_head = ListNode()
while head:
new_head.val = head.val
... | class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
new_head = list_node()
while head:
new_head.val = head.val
temp = list_node()
temp.next = new_head
new_head = temp
return new_head.next |
def power(base,p):
result = 1
while p:
if p%2 :
result *= base
p -= 1
else:
p /= 2
base *= base
return result
print(power(20,2)) | def power(base, p):
result = 1
while p:
if p % 2:
result *= base
p -= 1
else:
p /= 2
base *= base
return result
print(power(20, 2)) |
hor = 0
dep = 0
with open("../../input/02.txt", "r") as f:
for line in f:
match line.strip().split():
case ["forward", num]:
hor += int(num)
case ["down", num]:
dep += int(num)
case ["up", num]:
dep -= int(num)
print(hor, d... | hor = 0
dep = 0
with open('../../input/02.txt', 'r') as f:
for line in f:
match line.strip().split():
case ['forward', num]:
hor += int(num)
case ['down', num]:
dep += int(num)
case ['up', num]:
dep -= int(num)
print(hor, de... |
d = {1: 2, 4: 8, 7: 9}
s = 0
for x in d:
s = s + d[x]
print (s)
| d = {1: 2, 4: 8, 7: 9}
s = 0
for x in d:
s = s + d[x]
print(s) |
#!/usr/bin/env python3.6
x = 123456789
x = 1_2_3_4_5_6_7
x = 1E+1
x = 0xb1acc
x = 0.00_00_006
x = 12_34_567J
x = .1_2
x = 1_2.
# output
#!/usr/bin/env python3.6
x = 123456789
x = 1_2_3_4_5_6_7
x = 1e1
x = 0xB1ACC
x = 0.00_00_006
x = 12_34_567j
x = 0.1_2
x = 1_2.0 | x = 123456789
x = 1234567
x = 10.0
x = 727756
x = 6e-07
x = 1234567j
x = 0.12
x = 12.0
x = 123456789
x = 1234567
x = 10.0
x = 727756
x = 6e-07
x = 1234567j
x = 0.12
x = 12.0 |
basket = ['a', 'b', 'b', 'c', 'd', 'e']
print(basket.index('c')) # 3
print(basket.index('b', 2)) # 2
print('e' in basket) # True
print('z' in basket) # False
print(basket.count('b')) # 2
print(basket.count('d')) # 1 | basket = ['a', 'b', 'b', 'c', 'd', 'e']
print(basket.index('c'))
print(basket.index('b', 2))
print('e' in basket)
print('z' in basket)
print(basket.count('b'))
print(basket.count('d')) |
class SDRV1(object):
def __init__(self, name, value, unit, status):
self.name = name
self.value = value
self.unit = unit
self.status = status
def __str__(self):
name = str(self.name)
reading = f'{self.value} {self.unit}'
status = str(self.status)
... | class Sdrv1(object):
def __init__(self, name, value, unit, status):
self.name = name
self.value = value
self.unit = unit
self.status = status
def __str__(self):
name = str(self.name)
reading = f'{self.value} {self.unit}'
status = str(self.status)
... |
BASE_URL = "http://www.tsetmc.com/tsev2/data/MarketWatchInit.aspx?h=0&r=0"
CLIENT_TYPE_URL = "http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx"
SYMBOL_PAGE_URL = "http://www.tsetmc.com/loader.aspx?ParTree=151311&i={inscode}"
SYMBOL_HISTORY_URL = "http://www.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i={inscod... | base_url = 'http://www.tsetmc.com/tsev2/data/MarketWatchInit.aspx?h=0&r=0'
client_type_url = 'http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx'
symbol_page_url = 'http://www.tsetmc.com/loader.aspx?ParTree=151311&i={inscode}'
symbol_history_url = 'http://www.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i={inscod... |
with open('day3_1.txt') as file:
lines = file.readlines()
bits_freq = [[0, 0] for b in str(lines[0]).strip()]
for line in lines:
i = 0
for b in str(line).strip():
# print('b is', b)
if b == '0':
bits_freq[i][0] += 1
elif b == '1':
... | with open('day3_1.txt') as file:
lines = file.readlines()
bits_freq = [[0, 0] for b in str(lines[0]).strip()]
for line in lines:
i = 0
for b in str(line).strip():
if b == '0':
bits_freq[i][0] += 1
elif b == '1':
bits_freq[i][1] += 1
... |
# Problem: https://docs.google.com/document/d/16Wd9v3eGH7VW6n-utr-zM7vKLv8R0bYrAXi65aMaQHo/edit?usp=sharing
t = input()
a = ''
b = ''
for c in t:
if c.isupper():
a += c
else:
b += c
print(a)
print(b)
| t = input()
a = ''
b = ''
for c in t:
if c.isupper():
a += c
else:
b += c
print(a)
print(b) |
class PaleBaseResponse(object):
def __init__(self, *args):
super(PaleBaseResponse, self).__init__(*args)
if args:
self.message = args[0]
else:
self.message = "i am a teapot"
@property
def response(self):
http_status = getattr(self, 'http_status_code',... | class Palebaseresponse(object):
def __init__(self, *args):
super(PaleBaseResponse, self).__init__(*args)
if args:
self.message = args[0]
else:
self.message = 'i am a teapot'
@property
def response(self):
http_status = getattr(self, 'http_status_code'... |
# Author: b1tank
# Email: b1tank@outlook.com
#=================================
'''
79_word-search LeetCode
Solution:
- DFS + backtracking using '#' in-place marking instead of set()
'''
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def helper(boa... | """
79_word-search LeetCode
Solution:
- DFS + backtracking using '#' in-place marking instead of set()
"""
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def helper(board, i, j, w):
if not w:
return True
if i < 0 or i >= len(board... |
#Creating a Dictionary
# Dictionaries are unordered collections , so the order of a dictionary can change while printing !
myDict = {} # create a dictionary or by using dict()
eng2spn = {"one" : "uno", "two" : "dos", "three" : "tres"}
print("------------------------------")
print(eng2spn)
print(eng2spn["one"])
'''
... | my_dict = {}
eng2spn = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print('------------------------------')
print(eng2spn)
print(eng2spn['one'])
'\nDictionaries work on the concept of hash maps and hash functions.\nwhen we pass the key "one" in the dictionary.. it passed the key\nie "one" to the hash function. the has... |
def test_simple_wall_with_callback(app, client):
resp = client.get('/pr-one')
assert resp.status_code == 503
assert resp.data.decode('utf-8') == 'simple-wall'
def test_simple_wall_with_default_callback_and_custom_status(app, client):
resp = client.get('/pr-two')
assert resp.status_code == 307
... | def test_simple_wall_with_callback(app, client):
resp = client.get('/pr-one')
assert resp.status_code == 503
assert resp.data.decode('utf-8') == 'simple-wall'
def test_simple_wall_with_default_callback_and_custom_status(app, client):
resp = client.get('/pr-two')
assert resp.status_code == 307
a... |
LED_pin = 18 # physical pin 12 on RasPi-0W
wakeup_time = 30 # number of minutes for LED to fade in over
after_wakeup_on_time = (
30 # number of minutes for LED to remain lit (unless turned off) after target time
)
| led_pin = 18
wakeup_time = 30
after_wakeup_on_time = 30 |
#!/usr/bin/env python3
# Day 25: Uncrossed Lines
#
# We write the integers of A and B (in the order they are given) on two
# separate horizontal lines.
#
# Now, we may draw connecting lines: a straight line connecting two numbers
# A[i] and B[j] such that:
# - A[i] == B[j];
# - The line we draw does not intersect any ... | class Solution:
def __init__(self):
self.memo = {}
def max_uncrossed_lines_rec(self, A: [int], B: [int], i: int, j: int):
if i == len(A) or j == len(B):
return 0
if (i, j) in self.memo:
return self.memo[i, j]
if A[i] == B[j]:
count = 1 + self... |
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
# if desiredTotal == 0:
# return True
seen = {}
def can_win(choices, remainder):
# always check the optimum choice
# if the largest choice exceeds the remai... | class Solution:
def can_i_win(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
seen = {}
def can_win(choices, remainder):
if choices[-1] >= remainder:
return True
seen_key = tuple(choices)
if seen_key in seen:
return se... |
def Encrypt(msg, key=10):
msg = str(msg)
encryption = ""
for i in msg:
encryption += chr(int(ord(i)) + int(key))
return encryption
def Decrypt(msg, key=10):
msg = str(msg)
decryption = ""
for i in msg:
decryption += chr(int(ord(i)) - int(key))
return decr... | def encrypt(msg, key=10):
msg = str(msg)
encryption = ''
for i in msg:
encryption += chr(int(ord(i)) + int(key))
return encryption
def decrypt(msg, key=10):
msg = str(msg)
decryption = ''
for i in msg:
decryption += chr(int(ord(i)) - int(key))
return decryption |
## VIASH START
par = {
"input": ["I am debug!"],
"greeter": "Hello world!"
}
## VIASH END
if par["input"] is None:
par["input"] = []
print(par["greeter"], *par["input"])
| par = {'input': ['I am debug!'], 'greeter': 'Hello world!'}
if par['input'] is None:
par['input'] = []
print(par['greeter'], *par['input']) |
class QUndoCommand(object):
children = []
name = "untitled"
def undo(self):
for c in reversed(self.children):
c.undo()
def redo(self):
for c in self.children:
c.redo()
class QUndoStack(object):
undoCmds = []
macroStack = [] # list of lists
macroNameS... | class Qundocommand(object):
children = []
name = 'untitled'
def undo(self):
for c in reversed(self.children):
c.undo()
def redo(self):
for c in self.children:
c.redo()
class Qundostack(object):
undo_cmds = []
macro_stack = []
macro_name_stack = []
... |
f = open('C:\\Users\\sschaub\\Documents\\teaching\\tools\\cpsenroll.txt','r')
#data = f.read()
#lines = data.split('\n')
lines = f.readlines()
for line in lines:
fields = line.split(',')
if fields[0] == '110' and fields[1] == '01':
print(fields)
[courseNum, sectNum, firstName, lastName, username] = line.spl... | f = open('C:\\Users\\sschaub\\Documents\\teaching\\tools\\cpsenroll.txt', 'r')
lines = f.readlines()
for line in lines:
fields = line.split(',')
if fields[0] == '110' and fields[1] == '01':
print(fields)
[course_num, sect_num, first_name, last_name, username] = line.split(',')
if courseNum == '1... |
create_tables = {
'USER_TABLE': '''
create table if not exists users (
id integer primary key autoincrement,
dni text,
first_name text,
last_name text,
password text
);
''',
'DOCTORS_TABLE': '''
create table if not exists doctors (
id integer prima... | create_tables = {'USER_TABLE': '\n create table if not exists users (\n id integer primary key autoincrement,\n dni text,\n first_name text,\n last_name text,\n password text\n );\n ', 'DOCTORS_TABLE': '\n create table if not exists doctors (\n id integer primary ke... |
# This is an example of my custom awesome encryption concept.
# You can use this, but as this is public, I recommend you build your own
print("Encrypt Me")
def encrpyt(word):
x = list()
for letter in word:
x.append(letter)
for item in x:
if item == 'E' or 'b':
item = 'a'
print(x)
encrpyt("Encrypt")
# Inc... | print('Encrypt Me')
def encrpyt(word):
x = list()
for letter in word:
x.append(letter)
for item in x:
if item == 'E' or 'b':
item = 'a'
print(x)
encrpyt('Encrypt') |
def solve(data):
earliest, buses = data
best_bus, min_time_to_wait = buses[0][1], buses[0][1]
for (_, bus_id) in buses:
time_to_wait = ((earliest // bus_id) + 1) * bus_id - earliest
if time_to_wait < min_time_to_wait:
best_bus = bus_id
min_time_to_wait = time_to_wait
... | def solve(data):
(earliest, buses) = data
(best_bus, min_time_to_wait) = (buses[0][1], buses[0][1])
for (_, bus_id) in buses:
time_to_wait = (earliest // bus_id + 1) * bus_id - earliest
if time_to_wait < min_time_to_wait:
best_bus = bus_id
min_time_to_wait = time_to_w... |
CERTIFICATION = '''
-----BEGIN CERTIFICATE-----
MIIDSDCCAjCgAwIBAgIUPMKpJ/j10eQrcQBNnkImIaOYHakwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIxMDgwNTAwMzU1NloXDTIyMDgw
NTAwMzU1NlowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAxe/ZseXgOTVoF7uTjX5Leknk95jIoyGc+VlxA8BhzGOr
r4u6VNQZRCMq... | certification = '\n-----BEGIN CERTIFICATE-----\nMIIDSDCCAjCgAwIBAgIUPMKpJ/j10eQrcQBNnkImIaOYHakwDQYJKoZIhvcNAQEL\nBQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIxMDgwNTAwMzU1NloXDTIyMDgw\nNTAwMzU1NlowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF\nAAOCAQ8AMIIBCgKCAQEAxe/ZseXgOTVoF7uTjX5Leknk95jIoyGc+VlxA8BhzGOr\nr4u6VNQZ... |
'''
Created Dec 3, 2009
Compare lists and only append unique values
Author: Sam Gleske
'''
class UniqueList:
unique = []
def __init__(self, someList = []):
unique = []
for line in someList:
if line not in unique:
if line != "" or line != None:
... | """
Created Dec 3, 2009
Compare lists and only append unique values
Author: Sam Gleske
"""
class Uniquelist:
unique = []
def __init__(self, someList=[]):
unique = []
for line in someList:
if line not in unique:
if line != '' or line != None:
... |
num = 10
#fixbug
num = 20
num1 = 30
num2 = 40
| num = 10
num = 20
num1 = 30
num2 = 40 |
# -*- coding: utf-8 -*-
def main():
n, b1, b2, b3 = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(n)]
r = [list(map(int, input().split())) for _ in range(n)]
for ri in r:
print(' '.join(map(str, ri)))
if __name__ == '__main__':
main()
| def main():
(n, b1, b2, b3) = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(n)]
r = [list(map(int, input().split())) for _ in range(n)]
for ri in r:
print(' '.join(map(str, ri)))
if __name__ == '__main__':
main() |
def dec(f):
return f
def func():
def dec(f):
return f
@dec
def inner():
pass
func()
| def dec(f):
return f
def func():
def dec(f):
return f
@dec
def inner():
pass
func() |
# Example: Create Domain
domain_id = api.create_domain(name='qwerty', description='Python Docs Example')
print(domain_id)
# rd-domainId
| domain_id = api.create_domain(name='qwerty', description='Python Docs Example')
print(domain_id) |
dwarfs = {}
while True:
data = input().split(" <:> ")
if data[0] == "Once upon a time":
break
dwarf_name = data[0]
dwarf_hat_color = data[1]
dwarf_physics = int(data[2])
if dwarf_name not in dwarfs:
dwarfs[(dwarf_name, dwarf_hat_color)] = dwarf_physics
elif dwarf_name in dwa... | dwarfs = {}
while True:
data = input().split(' <:> ')
if data[0] == 'Once upon a time':
break
dwarf_name = data[0]
dwarf_hat_color = data[1]
dwarf_physics = int(data[2])
if dwarf_name not in dwarfs:
dwarfs[dwarf_name, dwarf_hat_color] = dwarf_physics
elif dwarf_name in dwarfs... |
SECRET_KEY = 'fake-key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contri... | secret_key = 'fake-key'
debug = True
installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'paranoid_model.tests']
middleware = ['django.middleware.security.SecurityMiddleware', 'django.contrib.... |
def match(command):
return ("please run 'gclient sync'" in command.output.lower())
def get_new_command(command):
return '{}'.format(command.script)
def side_effect(command, fixed_command):
subprocess.call('gclient sync', shell=True)
# Optional:
enabled_by_default = True
priority = 1000 # Lower first... | def match(command):
return "please run 'gclient sync'" in command.output.lower()
def get_new_command(command):
return '{}'.format(command.script)
def side_effect(command, fixed_command):
subprocess.call('gclient sync', shell=True)
enabled_by_default = True
priority = 1000
requires_output = True |
__all__ = [
'dates',
'dictionary',
'greetings',
'ircbot',
'js',
'listcommands',
'locator',
'pip',
'repeats',
'scheme',
'storedresponses',
]
| __all__ = ['dates', 'dictionary', 'greetings', 'ircbot', 'js', 'listcommands', 'locator', 'pip', 'repeats', 'scheme', 'storedresponses'] |
def prime_factors(N):
n = round(N ** 0.5) + 1
i = 1
factors = []
while True:
i += 1
if N % i == 0:
factors.append(i)
N = N // i
i = 1
n = round(N ** 0.5) + 1
if i > n:
if N != 1:
factors.append(N)
... | def prime_factors(N):
n = round(N ** 0.5) + 1
i = 1
factors = []
while True:
i += 1
if N % i == 0:
factors.append(i)
n = N // i
i = 1
n = round(N ** 0.5) + 1
if i > n:
if N != 1:
factors.append(N)
... |
class MeasurementIntervalNotSetError(RuntimeError):
"Raises when user does not specify the number of seconds or the number of iterations to run for the reporting period"
class ModelIsNotCallableError(RuntimeError):
"Raise when the object provided as a model is not a python `Callable` object"
class NamesNotE... | class Measurementintervalnotseterror(RuntimeError):
"""Raises when user does not specify the number of seconds or the number of iterations to run for the reporting period"""
class Modelisnotcallableerror(RuntimeError):
"""Raise when the object provided as a model is not a python `Callable` object"""
class Nam... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node in the linked list
def mergeTwoLists(self, A, B):
i ... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_two_lists(self, A, B):
i = A
j = B
head = None
checker = None
while i and j:
if i.val < j.val:
temp = list_node(i.val)
... |
class TempTracker(object):
def __init__(self):
# for min max
# initialize max_temp and min_temp to None
self.min_temp = float('inf')
self.max_temp = float('-inf')
# for mean
# initialize mean, sum_so_far and count to zero
self.mean, self.sum_so_far, self.coun... | class Temptracker(object):
def __init__(self):
self.min_temp = float('inf')
self.max_temp = float('-inf')
(self.mean, self.sum_so_far, self.count) = (0, 0, 0)
self.mode = 0
self.temp_frequency = [0] * 111
def insert(self, temperature):
self.count += 1
se... |
def treeCount(right, down):
horizontal_count = right
count = 0
tree_count = 0
for line in massaged_lines:
# skip first row of map
if count is 0:
count += 1
continue
else:
if count % down == 0:
map_space = line[horizontal_count]... | def tree_count(right, down):
horizontal_count = right
count = 0
tree_count = 0
for line in massaged_lines:
if count is 0:
count += 1
continue
else:
if count % down == 0:
map_space = line[horizontal_count]
if map_space ==... |
fn=input('enter filename..')
try:
f=open(fn,'r')
data=f.read()
print (data)
except FileNotFoundError as e:
print ("error message",e)
print ("end of program")
| fn = input('enter filename..')
try:
f = open(fn, 'r')
data = f.read()
print(data)
except FileNotFoundError as e:
print('error message', e)
print('end of program') |
def icecreamParlor(m, arr):
for pos1 in range(len(arr)):
cost1 = arr[pos1]
for pos2, cost2 in enumerate(arr[pos1 + 1:]):
if cost1 + cost2 == m:
return pos1 + 1, pos2 + 1 + pos1 + 1
print(icecreamParlor(4, [1, 4, 5, 3, 2])) | def icecream_parlor(m, arr):
for pos1 in range(len(arr)):
cost1 = arr[pos1]
for (pos2, cost2) in enumerate(arr[pos1 + 1:]):
if cost1 + cost2 == m:
return (pos1 + 1, pos2 + 1 + pos1 + 1)
print(icecream_parlor(4, [1, 4, 5, 3, 2])) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
num = input()
dist = set()
for i in range(int(num)):
dist.add(input())
print(len(dist))
| num = input()
dist = set()
for i in range(int(num)):
dist.add(input())
print(len(dist)) |
class Utils:
@staticmethod
def get_taxable_income(annual_income, bonus, rebates, donation):
return annual_income + bonus - rebates - (2.5 * donation)
@staticmethod
def get_annual_income(monthly_income):
return 12 * monthly_income
| class Utils:
@staticmethod
def get_taxable_income(annual_income, bonus, rebates, donation):
return annual_income + bonus - rebates - 2.5 * donation
@staticmethod
def get_annual_income(monthly_income):
return 12 * monthly_income |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.