content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
def start():
print("Hello, world.")
if __name__ == '__main__':
start()
| def start():
print('Hello, world.')
if __name__ == '__main__':
start() |
numbers = [3, 6, 2, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) | numbers = [3, 6, 2, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) |
class StateMachineException(Exception):
def __init__(self, message_format, **kwargs):
if kwargs:
self.message = message_format.format(**kwargs)
else:
self.message = message_format
self.__dict__.update(**kwargs)
def __str__(self):
return self.message
cla... | class Statemachineexception(Exception):
def __init__(self, message_format, **kwargs):
if kwargs:
self.message = message_format.format(**kwargs)
else:
self.message = message_format
self.__dict__.update(**kwargs)
def __str__(self):
return self.message
cla... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class DataSet:
def __init__(self,
src_channels_url: str,
injection_file_name: str,
out_file_name: str,
out_file_encoding: str,
out_file_first_line: str,
out_file_format... | class Dataset:
def __init__(self, src_channels_url: str, injection_file_name: str, out_file_name: str, out_file_encoding: str, out_file_first_line: str, out_file_format: str, filter_file_name: str, clean_filter: bool) -> None:
self._src_channels_url: str = src_channels_url
self._injection_file_name... |
sys_word = {}
for x in range(0,325):
sys_word[x] = 0
file = open("UAD-0015.txt", "r+")
words = file.read().split()
file.close()
for word in words:
sys_word[int(word)] += 1
for x in range(0,325):
sys_word[x] = sys_word[x]/int(325)
file_ = open("a_1.txt", "w")
for x in range(0,325):
if x is 324:
... | sys_word = {}
for x in range(0, 325):
sys_word[x] = 0
file = open('UAD-0015.txt', 'r+')
words = file.read().split()
file.close()
for word in words:
sys_word[int(word)] += 1
for x in range(0, 325):
sys_word[x] = sys_word[x] / int(325)
file_ = open('a_1.txt', 'w')
for x in range(0, 325):
if x is 324:
... |
#Soumya Pal
#Assignment 2 part 4
info = {
"name": "Shomo Pal",
"favorite_color": "Blue",
"favorite_number": 10,
"favorite_movies": ["Inception","The Shashank Redemption","One Piece (Anime not movie)"],
"favorite_songs" : [{'artist': 'Metallica', 'title': 'Nothing Else Matters'},
{'artist':... | info = {'name': 'Shomo Pal', 'favorite_color': 'Blue', 'favorite_number': 10, 'favorite_movies': ['Inception', 'The Shashank Redemption', 'One Piece (Anime not movie)'], 'favorite_songs': [{'artist': 'Metallica', 'title': 'Nothing Else Matters'}, {'artist': 'Nirvana', 'title': 'Come as you are'}]}
print(info['name'])
p... |
class Solution:
# @param {integer[][]} grid
# @return {integer}
def minPathSum(self, grid):
n = len(grid);
m = len(grid[0]);
p = [([0] * m) for i in range(n)]
p[0][0] = grid[0][0];
for k in range (1, n):
p[k][0] = p[k-1][0]+grid[k][0];
for... | class Solution:
def min_path_sum(self, grid):
n = len(grid)
m = len(grid[0])
p = [[0] * m for i in range(n)]
p[0][0] = grid[0][0]
for k in range(1, n):
p[k][0] = p[k - 1][0] + grid[k][0]
for k in range(1, m):
p[0][k] = p[0][k - 1] + grid[0][k]... |
# Cidades: Crie um dicionario chamado cities. Use os nomes de tres cidades como chaves em seu dicionario. Crie um dicionario com informacoes sobre cada cidade e inclua o pais em que a cidade esta localizada, a populacao aproximada e um fato sobre essa cidade. As chaves do dicionario de cada cidade devem ser algo como c... | cities = {'maputo': {'coutry': 'mozambique', 'population': '12.488.246', 'fact': 'corupt coutry'}, 'sao paulo': {'coutry': 'brazil', 'population': '145.264.218', 'fact': 'beautiful people'}, 'lisbon': {'coutry': 'portugal', 'population': '10.264.254', 'fact': 'racist'}}
for (key, value) in cities.items():
print(f'{... |
feedback_poly = {
2: [1],
3: [2],
4: [3],
5: [3],
6: [5],
7: [6],
8: [6, 5, 4],
9: [5],
10: [7],
11: [9],
12: [11, 10, 4],
13: [12, 11, 8],
14: [13, 12, 2],
15: [14],
16: [14, 13, 11],
17: [14],
18: [11],
19: [18, 17, 14],
20: [17],
21: [19... | feedback_poly = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [6, 5, 4], 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8], 14: [13, 12, 2], 15: [14], 16: [14, 13, 11], 17: [14], 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21], 23: [18], 24: [23, 22, 17]}
def one_hot_encode(n):
coeffs = []
... |
# Generated by h2py from /usr/include/sys/event.h
EVFILT_READ = (-1)
EVFILT_WRITE = (-2)
EVFILT_AIO = (-3)
EVFILT_VNODE = (-4)
EVFILT_PROC = (-5)
EVFILT_SIGNAL = (-6)
EVFILT_SYSCOUNT = 6
EV_ADD = 0x0001
EV_DELETE = 0x0002
EV_ENABLE = 0x0004
EV_DISABLE = 0x0008
EV_ONESHOT = 0x0010
EV_CLEAR = 0x0020
EV_SYSFLAGS = 0xF000
... | evfilt_read = -1
evfilt_write = -2
evfilt_aio = -3
evfilt_vnode = -4
evfilt_proc = -5
evfilt_signal = -6
evfilt_syscount = 6
ev_add = 1
ev_delete = 2
ev_enable = 4
ev_disable = 8
ev_oneshot = 16
ev_clear = 32
ev_sysflags = 61440
ev_flag1 = 8192
ev_eof = 32768
ev_error = 16384
note_delete = 1
note_write = 2
note_extend ... |
a = 1
b = 2
c = 3
print(a)
print(b)
print(c)
| a = 1
b = 2
c = 3
print(a)
print(b)
print(c) |
default_prefix = "DWB"
known_chains = {
"BEX": {
"chain_id": "38f14b346eb697ba04ae0f5adcfaa0a437ed3711197704aa256a14cb9b4a8f26",
"prefix": "DWB",
"dpay_symbol": "BEX",
"bbd_symbol": "BBD",
"vests_symbol": "VESTS",
},
"BET": {
"chain_id":
"9afbce9f... | default_prefix = 'DWB'
known_chains = {'BEX': {'chain_id': '38f14b346eb697ba04ae0f5adcfaa0a437ed3711197704aa256a14cb9b4a8f26', 'prefix': 'DWB', 'dpay_symbol': 'BEX', 'bbd_symbol': 'BBD', 'vests_symbol': 'VESTS'}, 'BET': {'chain_id': '9afbce9f2416520733bacb370315d32b6b2c43d6097576df1c1222859d91eecc', 'prefix': 'DWT', 'd... |
# RemoveDuplicatesfromSortedArray.py
# weird accepted answer that doesn't actually remove anything.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if (len(nums)==0):
return 0
i=0
j=0
while j < len(nums):
# print(nums, i , j)
... | class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
i = 0
j = 0
while j < len(nums):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
j += 1
return i + 1 |
# Values obtained from running against the Fuss & Navarro 2009 reference implementation
vals = [(0.3325402105490861,
0.18224585277734096,
2.0210322268188046,
0.37178992456396914,
0.7513994191503139,
1.6883221884854474,
1.0,
0.082198565245068272),
(-0.13074510229340497,
0.44696631528174735,
2.4890334... | vals = [(0.3325402105490861, 0.18224585277734096, 2.0210322268188046, 0.37178992456396914, 0.7513994191503139, 1.6883221884854474, 1.0, 0.08219856524506827), (-0.13074510229340497, 0.44696631528174735, 2.4890334572448456, 0.3816245478330931, 0.9498762676625047, 1.0790903665954314, 0.1, 0.4159172228850658), (0.605601086... |
class HourRange():
def __init__(self, start: int, end: int):
if start == end:
raise ValueError("Start and end may not be equal.")
if start < 0 or 23 < start:
raise ValueError("Invalid start value: " + str(start))
if end < 0 or 23 < end:
raise ValueError("I... | class Hourrange:
def __init__(self, start: int, end: int):
if start == end:
raise value_error('Start and end may not be equal.')
if start < 0 or 23 < start:
raise value_error('Invalid start value: ' + str(start))
if end < 0 or 23 < end:
raise value_error(... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root:TreeNode, sum:int, cur_sum:int):
if not root.left and not root.right:
if cur_sum + root.val == sum:
return True
else:... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root: TreeNode, sum: int, cur_sum: int):
if not root.left and (not root.right):
if cur_sum + root.val == sum:
return True
... |
def moeda(p = 0, moeda = 'R$'):
return (f'{moeda}{p:.2f}'.replace('.',','))
def metade(p = 0, formato=False):
res = p/2
return res if formato is False else moeda(res)
def dobro(p = 0, formato=False):
res = p*2
return res if formato is False else moeda(res)
def aumentar(p = 0, taxa = 0, formato... | def moeda(p=0, moeda='R$'):
return f'{moeda}{p:.2f}'.replace('.', ',')
def metade(p=0, formato=False):
res = p / 2
return res if formato is False else moeda(res)
def dobro(p=0, formato=False):
res = p * 2
return res if formato is False else moeda(res)
def aumentar(p=0, taxa=0, formato=False):
... |
class BookReader:
country = 'South Korea'
print(BookReader.country )
BookReader.country = 'USA'
print(BookReader.country )
| class Bookreader:
country = 'South Korea'
print(BookReader.country)
BookReader.country = 'USA'
print(BookReader.country) |
# DESCRIPTION
# Given a string containing only three types of characters: '(', ')' and '*',
# write a function to check whether this string is valid.
# We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must ... | class Solution:
def check_valid_string(self, s: str) -> bool:
"""
Time: O(N), where N is the length of the string
Space: O(1), constant space no aux space used
"""
cmin = 0
cmax = 0
for i in s:
if i == '(':
cmax += 1
... |
lines = open('dayfivedata.txt').read().split('\n')
ids = []
for line in lines:
top = 0; bottom = 127
for _ in range(7):
if 'F' in line[_]:
bottom = (top+bottom)//2
else:
top = (top+bottom)//2 + 1
left = 0; right = 7
for _ in range(7, 10):
if 'L' in line[_]... | lines = open('dayfivedata.txt').read().split('\n')
ids = []
for line in lines:
top = 0
bottom = 127
for _ in range(7):
if 'F' in line[_]:
bottom = (top + bottom) // 2
else:
top = (top + bottom) // 2 + 1
left = 0
right = 7
for _ in range(7, 10):
if ... |
n=int(input())
ans=[]
used=[False for i in range(n)]
d=[i+1 for i in range(n)]
a=list(map(int,input().split()))
p=0
f=False
while True:
for i in range(n-1):
if f:
i=n-2-i
if a[i]>i+1 and a[i+1]<i+2 and not used[i]:
ans.append(i+1)
used[i]=True
a[i],a[i... | n = int(input())
ans = []
used = [False for i in range(n)]
d = [i + 1 for i in range(n)]
a = list(map(int, input().split()))
p = 0
f = False
while True:
for i in range(n - 1):
if f:
i = n - 2 - i
if a[i] > i + 1 and a[i + 1] < i + 2 and (not used[i]):
ans.append(i + 1)
... |
# position, name, age, level, salary
se1 = ["Software Engineer", "Max", 20, "Junior", 5000]
se2 = ["Software Engineer", "Lisa", 25, "Senior", 7000]
# class
class SoftwareEngineer:
# class attributes
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary):
# instance attributes
... | se1 = ['Software Engineer', 'Max', 20, 'Junior', 5000]
se2 = ['Software Engineer', 'Lisa', 25, 'Senior', 7000]
class Softwareengineer:
alias = 'Keyboard Magician'
def __init__(self, name, age, level, salary):
self.name = name
self.age = age
self.level = level
self.salary = sala... |
class Usuario:
def __init__(self):
self.usuario=""
self.ingresos=0
def intro(self):
self.usuario=input("Ingrese el nombre del usuario:")
self.ingresos=float(input("Cantidad ingresos anual:"))
def visualizar(self):
print("Nombre:",self.usuario)
... | class Usuario:
def __init__(self):
self.usuario = ''
self.ingresos = 0
def intro(self):
self.usuario = input('Ingrese el nombre del usuario:')
self.ingresos = float(input('Cantidad ingresos anual:'))
def visualizar(self):
print('Nombre:', self.usuario)
prin... |
a=3
b=6
a,b=b,a
print('After Swapping values of A and B are',a,b)
| a = 3
b = 6
(a, b) = (b, a)
print('After Swapping values of A and B are', a, b) |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
lines = len(matrix)
lists = len(matrix[0])
mat = [[0] * lists for _ in range(lines)]
for i in range(lists):
mat[0][i] = int(matrix[0][i])
for i in ... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
lines = len(matrix)
lists = len(matrix[0])
mat = [[0] * lists for _ in range(lines)]
for i in range(lists):
mat[0][i] = int(matrix[0][i])
for i i... |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] = d[num] + 1
for k,v in d.items():
if v == 1:
return k
| class Solution:
def single_number(self, nums: List[int]) -> int:
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] = d[num] + 1
for (k, v) in d.items():
if v == 1:
return k |
# https://leetcode.com/problems/find-the-difference/
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
count = 0
for i in range(len(s)):
if s[i] != t[i] :
count = 1
print(t[i])
... | class Solution:
def find_the_difference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
count = 0
for i in range(len(s)):
if s[i] != t[i]:
count = 1
print(t[i])
return t[i]
if count == 0:
retur... |
for i in range(1,5):
for j in range(1,5):
print(j,end=" ")
print( )
| for i in range(1, 5):
for j in range(1, 5):
print(j, end=' ')
print() |
def round_off(ls2): # Function for the algorithm to obtain the desired output
final_grade = []
for value in ls2: # iterating in the list to read every student's marks
reminder = value % 5 # calculating remainder
if value < 38:
final_grade.append(value)
elif reminder >= 3: ... | def round_off(ls2):
final_grade = []
for value in ls2:
reminder = value % 5
if value < 38:
final_grade.append(value)
elif reminder >= 3:
value += 5 - reminder
final_grade.append(value)
else:
final_grade.append(value)
return fina... |
n,m = map(int,input().split())
rows = [input() for _ in range(n)]
k = int(input())
for row in sorted(rows, key=lambda row: int(row.split()[k])):
print(row)
| (n, m) = map(int, input().split())
rows = [input() for _ in range(n)]
k = int(input())
for row in sorted(rows, key=lambda row: int(row.split()[k])):
print(row) |
def func_header(funcname):
print('\t.global %s' % funcname)
print('\t.type %s, %%function' % funcname)
print('%s:' % funcname)
def push_stack(reg):
print('\tstr %s, [sp, -0x10]!' % reg)
def pop_stack(reg):
print('\tldr %s, [sp], 0x10' % reg)
def store_stack(value, offset):
print('\tmov... | def func_header(funcname):
print('\t.global %s' % funcname)
print('\t.type %s, %%function' % funcname)
print('%s:' % funcname)
def push_stack(reg):
print('\tstr %s, [sp, -0x10]!' % reg)
def pop_stack(reg):
print('\tldr %s, [sp], 0x10' % reg)
def store_stack(value, offset):
print('\tmov ... |
(10 and 2)[::-5]
(10 and 2)[5]
(10 and 2)(5)
(10 and 2).foo
-(10 and 2)
+(10 and 2)
~(10 and 2)
5 ** (10 and 2)
(10 and 2) ** 5
5 * (10 and 2)
(10 and 2) * 5
5 / (10 and 2)
(10 and 2) / 5
5 // (10 and 2)
(10 and 2) // 5
5 + (10 and 2)
(10 and 2) + 5
(10 and 2) - 5
5 - (10 and 2)
5 >> (10 and 2)
(10 and 2) << 5
... | (10 and 2)[::-5]
(10 and 2)[5]
(10 and 2)(5)
(10 and 2).foo
-(10 and 2)
+(10 and 2)
~(10 and 2)
5 ** (10 and 2)
(10 and 2) ** 5
5 * (10 and 2)
(10 and 2) * 5
5 / (10 and 2)
(10 and 2) / 5
5 // (10 and 2)
(10 and 2) // 5
5 + (10 and 2)
(10 and 2) + 5
(10 and 2) - 5
5 - (10 and 2)
5 >> (10 and 2)
(10 and 2) << 5
5 & (10 ... |
inputA = 277
inputB = 349
score = 0
queueA = []
queueB = []
i = 0
while len(queueA) < (5*(10**6)):
inputA = (inputA*16807)%2147483647
if inputA%4 == 0: queueA.append(inputA)
while len(queueB) < (5*(10**6)):
inputB = (inputB*48271)%2147483647
if inputB%8 == 0: queueB.append(inputB)
for i in range(0,(5*(10**6... | input_a = 277
input_b = 349
score = 0
queue_a = []
queue_b = []
i = 0
while len(queueA) < 5 * 10 ** 6:
input_a = inputA * 16807 % 2147483647
if inputA % 4 == 0:
queueA.append(inputA)
while len(queueB) < 5 * 10 ** 6:
input_b = inputB * 48271 % 2147483647
if inputB % 8 == 0:
queueB.append(... |
# Created by MechAviv
# [Magic Library Checker] | [1032220]
# Ellinia : Magic Library
if "1" not in sm.getQuestEx(25566, "c3"):
sm.setQuestEx(25566, "c3", "1")
sm.chatScript("You search the Magic Library.") | if '1' not in sm.getQuestEx(25566, 'c3'):
sm.setQuestEx(25566, 'c3', '1')
sm.chatScript('You search the Magic Library.') |
class Comparable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
other_value = other.value if isinstance(other, Comparable) else other
return self.value == other_value
def __ne__(self, other):
other_value = other.value if isinstance(other, Comparabl... | class Comparable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
other_value = other.value if isinstance(other, Comparable) else other
return self.value == other_value
def __ne__(self, other):
other_value = other.value if isinstance(other, Comparabl... |
def DecodeToFile(osufile, newfilename, SVLines: list):
with open(newfilename, "w+") as f:
old = open(osufile, "r")
old = old.readlines()
old_TotimingPoints = old[:old.index("[TimingPoints]\n") + 1]
old_afterTimingPoints = old[old.index("[TimingPoints]\n") + 1:]
all_file = old... | def decode_to_file(osufile, newfilename, SVLines: list):
with open(newfilename, 'w+') as f:
old = open(osufile, 'r')
old = old.readlines()
old__totiming_points = old[:old.index('[TimingPoints]\n') + 1]
old_after_timing_points = old[old.index('[TimingPoints]\n') + 1:]
all_file... |
#Program for a Function that takes a list of words and returns the length of the longest one.
def longest_word(list): #define a function which takes list as a parameter
longest=0
for words in list: #l... | def longest_word(list):
longest = 0
for words in list:
if len(words) > longest:
longest = len(words)
lword = words
return lword
w = ['Entertainment', 'entire', 'Elephant', 'inconsequential']
print('Longest word is', longest_word(w), 'with', len(longest_word(w)), 'letters.') |
def print_a_string():
my_string = "hello world"
print(my_string)
def print_a_number():
my_number = 9
print(my_number)
# my logic starts here
if __name__ == "__main__":
print_a_string()
print_a_number()
print("all done...bye-bye") | def print_a_string():
my_string = 'hello world'
print(my_string)
def print_a_number():
my_number = 9
print(my_number)
if __name__ == '__main__':
print_a_string()
print_a_number()
print('all done...bye-bye') |
def hms2dec(h,m,s):
return 15*(h + (m/60) + (s/3600))
def dms2dec(d,m,s):
if d>=0:
return (d + (m/60) + (s/3600))
return (d - (m/60) - (s/3600))
if __name__ == '__main__':
print(hms2dec(23, 12, 6))
print(dms2dec(22, 57, 18))
print(dms2dec(-66, 5, 5.1)) | def hms2dec(h, m, s):
return 15 * (h + m / 60 + s / 3600)
def dms2dec(d, m, s):
if d >= 0:
return d + m / 60 + s / 3600
return d - m / 60 - s / 3600
if __name__ == '__main__':
print(hms2dec(23, 12, 6))
print(dms2dec(22, 57, 18))
print(dms2dec(-66, 5, 5.1)) |
no_list = [22,68,90,78,90,88]
def average(x):
#complete the function's body to return the average
length=len(no_list)
return sum(no_list)/length
print(average(no_list))
| no_list = [22, 68, 90, 78, 90, 88]
def average(x):
length = len(no_list)
return sum(no_list) / length
print(average(no_list)) |
__lname__ = "yass"
__uname__ = "YASS"
__acronym__ = "Yet Another Subdomainer Software"
__version__ = "0.8.0"
__author__ = "Francesco Marano (@mrnfrancesco)"
__author_email__ = "francesco.mrn24@gmail.com"
__source_url__ = "https://github.com/mrnfrancesco/yass"
| __lname__ = 'yass'
__uname__ = 'YASS'
__acronym__ = 'Yet Another Subdomainer Software'
__version__ = '0.8.0'
__author__ = 'Francesco Marano (@mrnfrancesco)'
__author_email__ = 'francesco.mrn24@gmail.com'
__source_url__ = 'https://github.com/mrnfrancesco/yass' |
end = 1000
total = 0
for x in range(1,end):
if x % 15 == 0:
total = total + x
print(x)
elif x % 5 == 0:
total = total + x
print(x)
elif x % 3 == 0:
total = total + x
print(x)
print(f"total = {total}") | end = 1000
total = 0
for x in range(1, end):
if x % 15 == 0:
total = total + x
print(x)
elif x % 5 == 0:
total = total + x
print(x)
elif x % 3 == 0:
total = total + x
print(x)
print(f'total = {total}') |
# Section 3-16
# Question: How do we find the sum of the digits of a positive integer using recursion?
# Step 1: The recursive case
# Add the current digit to a total
# Step 2: The Base Condition
# If there are no more digits, return the total
# Step 3: The unintended cases
# If the input is not a positive integer... | test = 349587
expected = 3 + 4 + 9 + 5 + 8 + 7
def sum_digits(number):
assert number >= 0 and int(number) == number, 'Input must be a nonnegative integer.'
return 0 if number == 0 else number % 10 + sum_digits(int(number / 10))
outcome = sum_digits(test)
print('Expected: ', expected)
print('Outcome: ', outcome... |
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) / 2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
... | def binary_search(arr, l, r, x):
while l <= r:
mid = l + (r - l) / 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1 |
# Segment tree
class SegmentTree:
def __init__(self, data):
size = len(data)
t = 1
while t < size:
t <<= 1
offset = t - 1
index = [0] * (t * 2 - 1)
index[offset:offset + size] = range(size)
for i in range(offset - 1, -1, -1):
x = index[... | class Segmenttree:
def __init__(self, data):
size = len(data)
t = 1
while t < size:
t <<= 1
offset = t - 1
index = [0] * (t * 2 - 1)
index[offset:offset + size] = range(size)
for i in range(offset - 1, -1, -1):
x = index[i * 2 + 1]
... |
'''import math #as m also can be written
a=math.pi #a=m.pi
print(a)
'''
'''
from math import pi #import only pi from math
b=2*pi
print(b)
'''
'''
from math import * #import everything from math
b=2*pi
print(b)
'''
'''
food = 'spam'
if food == 'spam':
print('Ummmm, my favourite!')
print('I feel like sa... | """import math #as m also can be written
a=math.pi #a=m.pi
print(a)
"""
'\nfrom math import pi #import only pi from math\nb=2*pi\nprint(b)\n'
'\nfrom math import * #import everything from math\nb=2*pi\nprint(b)\n'
"\nfood = 'spam'\nif food == 'spam':\n print('Ummmm, my favourite!')\nprint('I feel like sa... |
def test_post_order(client, order_payload):
res = client.post("/order", json = order_payload)
assert res.status_code == 200
def test_post_game(client, game_payload):
res = client.post("/order", json = game_payload)
assert res.status_code == 200
def test_get_order(client):
res1 = client.get("/o... | def test_post_order(client, order_payload):
res = client.post('/order', json=order_payload)
assert res.status_code == 200
def test_post_game(client, game_payload):
res = client.post('/order', json=game_payload)
assert res.status_code == 200
def test_get_order(client):
res1 = client.get('/order')
... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_deg = (hour*30)%360 + (0.5)*minutes
minute_deg = ((minutes/5)*30)%360
if(abs(hour_deg-minute_deg)>180):
return 360 - abs(hour_deg-minute_deg)
else:
return abs(hour_d... | class Solution:
def angle_clock(self, hour: int, minutes: int) -> float:
hour_deg = hour * 30 % 360 + 0.5 * minutes
minute_deg = minutes / 5 * 30 % 360
if abs(hour_deg - minute_deg) > 180:
return 360 - abs(hour_deg - minute_deg)
else:
return abs(hour_deg - mi... |
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
# 'low' and 'high' represent the range of va... | class Solution:
def find_duplicate(self, nums: list[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
class Solution:
def find_duplicate(self, nums: list[int]) -> int:
low = 1
high = len(nums) - 1
... |
num = int(input(''))
hours = int(input(''))
value = float(input(''))
print('NUMBER = {:0}\nSALARY = U$ {:.2f}'.format(num, (hours * value))) | num = int(input(''))
hours = int(input(''))
value = float(input(''))
print('NUMBER = {:0}\nSALARY = U$ {:.2f}'.format(num, hours * value)) |
class Solution(object):
def combinationSum2(self, candidates, target):
ret = []
self.dfs(sorted(candidates), target, 0, [], ret)
return ret
def dfs(self, nums, target, idx, path, ret):
if target <= 0:
if target == 0:
ret.append(path)
r... | class Solution(object):
def combination_sum2(self, candidates, target):
ret = []
self.dfs(sorted(candidates), target, 0, [], ret)
return ret
def dfs(self, nums, target, idx, path, ret):
if target <= 0:
if target == 0:
ret.append(path)
ret... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | class Dispersionongrid:
def __init__(self, axes, polarization_npyarr, energy_npyarr):
self.axes = axes
self.polarization_npyarr = polarization_npyarr
self.energy_npyarr = energy_npyarr
return
pass
__id__ = '$Id$' |
str1 = "Udacity"
# LENGTH
print(len(str1)) # 7
# CHANGE CASE
# The `lower()` and `upper` method returns the string in lower case and upper case respectively
print(str1.lower()) # udacity
print(str1.upper()) # UDACITY
# SLICING
# string_var[lower_index : upper_index]
# Note that the upper_index is not inclusive... | str1 = 'Udacity'
print(len(str1))
print(str1.lower())
print(str1.upper())
print(str1[1:6])
print(str1[:6])
print(str1[1:])
print(str1[-6:-1])
str2 = ' Udacity '
print(str2.strip())
print(str1.replace('y', 'B'))
str3 = 'Welcome, Constance!'
print(str3.split(','))
print(str3 + ' ' + str1)
marks = 100
print(str3 + '... |
class Line:
def __init__(self,p1,p2):
if (p1[0] > p2[0]):
self.p1 = p2
self.p2 = p1
elif (p1[0] == p2[0] and p1[1] > p2[1]):
self.p1 = p2
self.p2 = p1
else:
self.p1 = p1
self.p2 = p2
print(self.p1)
prin... | class Line:
def __init__(self, p1, p2):
if p1[0] > p2[0]:
self.p1 = p2
self.p2 = p1
elif p1[0] == p2[0] and p1[1] > p2[1]:
self.p1 = p2
self.p2 = p1
else:
self.p1 = p1
self.p2 = p2
print(self.p1)
print(s... |
class Node:
pass
class SystemNode(Node):
def __init__(self, equations):
self.equations = equations
class EquationNode(Node):
def __init__(self, differential, expression):
self.differential = differential
self.expression = expression
class DifferentialNode(Node):
def __init_... | class Node:
pass
class Systemnode(Node):
def __init__(self, equations):
self.equations = equations
class Equationnode(Node):
def __init__(self, differential, expression):
self.differential = differential
self.expression = expression
class Differentialnode(Node):
def __init_... |
frase = str(input('Digite uma frase: '))
cont = 1
for c in frase:
if cont % 2 == 0:
print(c.upper(), end='')
else:
print(c.lower(), end='')
cont += 1
| frase = str(input('Digite uma frase: '))
cont = 1
for c in frase:
if cont % 2 == 0:
print(c.upper(), end='')
else:
print(c.lower(), end='')
cont += 1 |
# https://stackoverflow.com/questions/13979714/heap-sort-how-to-sort
swaps = 0
def heapify(arr, n, i):
global swaps
count = 0
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if... | swaps = 0
def heapify(arr, n, i):
global swaps
count = 0
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
count += 1
(arr[i], arr[largest]) = (arr[largest], ... |
class Solution:
def solve(self, words):
groups = defaultdict(list)
for word in words:
for key in groups:
if len(word)==len(key) and any(all(word[j]==key[j-i] for j in range(i,len(word))) and all(word[j]==key[len(word)-i+j] for j in range(i)) for i in range(len(word))):
... | class Solution:
def solve(self, words):
groups = defaultdict(list)
for word in words:
for key in groups:
if len(word) == len(key) and any((all((word[j] == key[j - i] for j in range(i, len(word)))) and all((word[j] == key[len(word) - i + j] for j in range(i))) for i in ra... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurantlessthan20, obj[15]: Re... | def find_decision(obj):
if obj[3] <= 3:
if obj[10] <= 20:
if obj[13] > 0.0:
if obj[2] <= 3:
if obj[12] <= 3.0:
if obj[17] > 1:
if obj[14] <= 2.0:
if obj[6] <= 4:
... |
#-- gestures supported by Otto
#-- OttDIY Python Project, 2020
OTTOHAPPY = const(0)
OTTOSUPERHAPPY = const(1)
OTTOSAD = const(2)
OTTOSLEEPING = const(3)
OTTOFART = const(4)
OTTOCONFUSED = const(5)
OTTOLOVE = const(6)
OTTOANGRY = const(7)
OTTOFRETFUL = const(8)
OTTOMAGIC = cons... | ottohappy = const(0)
ottosuperhappy = const(1)
ottosad = const(2)
ottosleeping = const(3)
ottofart = const(4)
ottoconfused = const(5)
ottolove = const(6)
ottoangry = const(7)
ottofretful = const(8)
ottomagic = const(9)
ottowave = const(10)
ottovictory = const(11)
ottofail = const(12) |
products = {}
command = input()
while command != "statistics":
command = command.split(": ")
key = command[0]
value = int(command[1])
if key not in products:
products[key] = 0
products[key] += value
command = input()
print("Products in stock:")
for k, v in products.items():
print(... | products = {}
command = input()
while command != 'statistics':
command = command.split(': ')
key = command[0]
value = int(command[1])
if key not in products:
products[key] = 0
products[key] += value
command = input()
print('Products in stock:')
for (k, v) in products.items():
print(f... |
# Simple function to add values
def aFunction():
a = 1
b = 2
c = a + b
print(c)
return c
# simple loop to count up in a range
def aLoop():
count = 0
# for each item in the range
for item in range(0, 100):
print(count)
count = count + 1
return count... | def a_function():
a = 1
b = 2
c = a + b
print(c)
return c
def a_loop():
count = 0
for item in range(0, 100):
print(count)
count = count + 1
return count
def a_func_1(my_num):
result = a_func_2(my_num)
print(result)
return result
def a_func_2(var):
var +... |
#!/usr/bin/python
# 1. Retourner VRAI si N est parfait, faux sinon
# 2. Afficher la liste des nombres parfait compris entre 1 et 10 000
def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
fo... | def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
for i in range(10000):
if est_parfait(i):
print(i) |
class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return "PASSWORD"
def default(scopes: list, **kwargs):
return Credentials(), "myproject"
class Request(object):
pass
| class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return 'PASSWORD'
def default(scopes: list, **kwargs):
return (credentials(), 'myproject')
class Request(object):
pass |
xCoordinate = [1,2,3,4,5,6,7,8,9,10]
xCdt = [1,2,3,4,5,6,7,8,9,10]
def setup():
size(500,500)
smooth()
noStroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35*i + 90
for j in range(len(xCdt)):
xCdt[j] = 35*j + 90
def draw():
background(50)
for j in range(len(xCdt)):... | x_coordinate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_cdt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def setup():
size(500, 500)
smooth()
no_stroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35 * i + 90
for j in range(len(xCdt)):
xCdt[j] = 35 * j + 90
def draw():
background(50)
... |
#TeamLeague
class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_t... | class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_team_by__id... |
## Solution Challenge 10
def data_url(country):
'''
Function to build url for data retrieval
'''
BASE_URL = "http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/"
SUFFIX_URL = "-TAVG-Trend.txt"
return(BASE_URL + country + SUFFIX_URL) | def data_url(country):
"""
Function to build url for data retrieval
"""
base_url = 'http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/'
suffix_url = '-TAVG-Trend.txt'
return BASE_URL + country + SUFFIX_URL |
#
# PySNMP MIB module RFC1382-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1382-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:26:33 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( Octe... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1]+3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if ro... | def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1] + 3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if rows[i] - ... |
def find_min_max(nums):
if nums[0]<nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums)-2):
if nums[i+2] < min:
min = nums[i+2]
elif nums[i+2] > max:
max = nums[i+2]
return (min, max)
de... | def find_min_max(nums):
if nums[0] < nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums) - 2):
if nums[i + 2] < min:
min = nums[i + 2]
elif nums[i + 2] > max:
max = nums[i + 2]
return (min... |
def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) | def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) |
x=1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
a,b=y
a=int(a)
b=int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(input('Novo g... | x = 1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
(a, b) = y
a = int(a)
b = int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(inpu... |
#
# PySNMP MIB module SNR-ERD-PRO-Mini (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNR-ERD-PRO-Mini
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = ComputeRank("rank")
docs = [{}, {}]... | class Computerank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for (i, document) in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = compute_rank('rank')
docs = [{}, {}... |
'''
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible... | """
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible... |
ENTITY = "<<Entity>>"
REL = 'Rel/'
ATTR = 'Attr/'
SOME = 'SOME'
ALL = 'ALL'
GRAPH = 'GRAPH'
LIST = 'LIST'
TEXT = 'TEXT'
SHAPE = 'SHAPE'
SOME_LIMIT = 15
EXACT_MATCH = 'EXACT_MATCH'
REGEX_MATCH = 'REGEX_MATCH'
SYNONYM_MATCH = 'SYNONYM_MATCH' | entity = '<<Entity>>'
rel = 'Rel/'
attr = 'Attr/'
some = 'SOME'
all = 'ALL'
graph = 'GRAPH'
list = 'LIST'
text = 'TEXT'
shape = 'SHAPE'
some_limit = 15
exact_match = 'EXACT_MATCH'
regex_match = 'REGEX_MATCH'
synonym_match = 'SYNONYM_MATCH' |
def calculate(arr, index=0):
back = - 1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == (index+1):
return True
return calculate(arr, index+1)
arr = [int(i) for i in input().split()]
print(calculate(arr))
| def calculate(arr, index=0):
back = -1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == index + 1:
return True
return calculate(arr, index + 1)
arr = [int(i) for i in input().split()]
print(calculate(arr)) |
class IberException(Exception):
pass
class ResponseException(IberException):
def __init__(self, status_code):
super().__init__("Response error, code: {}".format(status_code))
class LoginException(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user ... | class Iberexception(Exception):
pass
class Responseexception(IberException):
def __init__(self, status_code):
super().__init__('Response error, code: {}'.format(status_code))
class Loginexception(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user ... |
v = 6.0 # velocity of seismic waves [km/s]
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
# Your code goes here!
return x, y
| v = 6.0
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
return (x, y) |
class Logi:
def __init__(self, email, password):
self.email = email
self.password = password
| class Logi:
def __init__(self, email, password):
self.email = email
self.password = password |
requestDict = {
'instances':
[
{
"Lat": 37.4434774, "Long": -122.1652269,
"Altitude": 21.0, "Date_": "7/4/17",
"Time_": "23:37:25", "dt_": "7/4/17 23:37"
#driving meet conjestion
}... | request_dict = {'instances': [{'Lat': 37.4434774, 'Long': -122.1652269, 'Altitude': 21.0, 'Date_': '7/4/17', 'Time_': '23:37:25', 'dt_': '7/4/17 23:37'}, {'Lat': 37.429302, 'Long': -122.16145, 'Altitude': 20.0, 'Date_': '7/4/17', 'Time_': '09:37:25', 'dt_': '7/4/17 09:37'}]} |
#!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.tx... | class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = object('COM')
objects = {'COM': root}
def get_object(id):
if id not in objects:
objects[id] = object(id)
return objects[id]
with open('input.txt') as f:
for line in f... |
def fizzbuzz(num):
if (num >= 0 and num % 3 == 0 and num % 5 == 0):
return "Fizz Buzz"
if (num >= 0 and num % 3 == 0):
return "Fizz"
if (num >= 0 and num % 5 == 0):
return "Buzz"
if (num >= 0):
return ""
| def fizzbuzz(num):
if num >= 0 and num % 3 == 0 and (num % 5 == 0):
return 'Fizz Buzz'
if num >= 0 and num % 3 == 0:
return 'Fizz'
if num >= 0 and num % 5 == 0:
return 'Buzz'
if num >= 0:
return '' |
dataset_paths = {
'ffhq': '',
'celeba_test': '',
'cars_train': '',
'cars_test': '',
'church_train': '',
'church_test': '',
'horse_train': '',
'horse_test': '',
'afhq_wild_train': '',
'afhq_wild_test': '',
'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr',
'... | dataset_paths = {'ffhq': '', 'celeba_test': '', 'cars_train': '', 'cars_test': '', 'church_train': '', 'church_test': '', 'horse_train': '', 'horse_test': '', 'afhq_wild_train': '', 'afhq_wild_test': '', 'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr', 'font_test': '/mnt/... |
def v(kod):
if (k == len(kod)):
print(' '.join(kod))
return
if (len(kod) != 0):
for i in range(int(kod[-1]) + 1, n + 1):
if (str(i) not in kod):
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range... | def v(kod):
if k == len(kod):
print(' '.join(kod))
return
if len(kod) != 0:
for i in range(int(kod[-1]) + 1, n + 1):
if str(i) not in kod:
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range(1, n + 1):
... |
'''
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
'''
# a1: item value... | """
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
"""
a1 = [100, 70, 50... |
administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021
| administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021 |
class NoneTypeFont(Exception):
pass
class PortraitBoolError(Exception):
pass
class NoneStringObject(Exception):
pass
class BMPvalidationError(Exception):
pass
| class Nonetypefont(Exception):
pass
class Portraitboolerror(Exception):
pass
class Nonestringobject(Exception):
pass
class Bmpvalidationerror(Exception):
pass |
default_values = {
'mode': 'train',
'net': 'resnet32_cifar',
'device': 'cuda:0',
'num_epochs': 300,
'activation_type': 'deepBspline_explicit_linear',
'spline_init': 'leaky_relu',
'spline_size': 51,
'spline_range': 4,
'save_memory': False,
'knot_threshold': 0.,
'num_hidden_lay... | default_values = {'mode': 'train', 'net': 'resnet32_cifar', 'device': 'cuda:0', 'num_epochs': 300, 'activation_type': 'deepBspline_explicit_linear', 'spline_init': 'leaky_relu', 'spline_size': 51, 'spline_range': 4, 'save_memory': False, 'knot_threshold': 0.0, 'num_hidden_layers': 2, 'num_hidden_neurons': 4, 'lipschitz... |
NONE = u'none'
OTHER = u'other'
PRIMARY = u'primary'
JUNIOR_SECONDARY = u'junior_secondary'
SECONDARY = u'secondary'
ASSOCIATES = u'associates'
BACHELORS = u'bachelors'
MASTERS = u'masters'
DOCTORATE = u'doctorate'
| none = u'none'
other = u'other'
primary = u'primary'
junior_secondary = u'junior_secondary'
secondary = u'secondary'
associates = u'associates'
bachelors = u'bachelors'
masters = u'masters'
doctorate = u'doctorate' |
class SteepshotBotError(Exception):
msg = {}
def get_msg(self, locale: str = 'en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class SteepshotServerError(SteepshotBotError):
msg = {
'en': 'Some Steepshot error occurred: '
}
class Stee... | class Steepshotboterror(Exception):
msg = {}
def get_msg(self, locale: str='en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class Steepshotservererror(SteepshotBotError):
msg = {'en': 'Some Steepshot error occurred: '}
class Steemerror(SteepshotBo... |
class Instrument:
insId: int
name: str
urlName: str
instrument: int
isin: str
ticker: str
yahoo: str
sectorId: int
marketId: int
branchId: int
countryId: int
listingDate: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, marketId... | class Instrument:
ins_id: int
name: str
url_name: str
instrument: int
isin: str
ticker: str
yahoo: str
sector_id: int
market_id: int
branch_id: int
country_id: int
listing_date: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, m... |
num = int(input("Enter a number: "))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root**pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root**pwr == num:
print(root, "^", pwr, sep="")
break
pwr += 1
if root**pwr == num:
break
else:
pwr = 0
... | num = int(input('Enter a number: '))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root ** pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root ** pwr == num:
print(root, '^', pwr, sep='')
break
pwr += 1
if root ** pwr == num:
... |
expected_output = {
"route-information": {
"route-table": {
"active-route-count": "1250009",
"destination-count": "1250009",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": {
"rt-announced-count": "1",
... | expected_output = {'route-information': {'route-table': {'active-route-count': '1250009', 'destination-count': '1250009', 'hidden-route-count': '0', 'holddown-route-count': '0', 'rt': {'rt-announced-count': '1', 'rt-destination': '10.55.0.0', 'rt-entry': {'active-tag': '*', 'age': {'#text': '4:32'}, 'announce-bits': '2... |
SERVER_EMAIL = 'SERVER_EMAIL'
SERVER_PASSWORD = 'SERVER_PASSWORD'
WATCHED = {
'service': ['service'],
'process': ['process'],
}
NOTIFICATION_DETAILS = {
'service': [
{
'identifiers': ['identifiers'],
'to_emails': ['nimesh.aug11@gmail.com'],
'subject': 'subject'... | server_email = 'SERVER_EMAIL'
server_password = 'SERVER_PASSWORD'
watched = {'service': ['service'], 'process': ['process']}
notification_details = {'service': [{'identifiers': ['identifiers'], 'to_emails': ['nimesh.aug11@gmail.com'], 'subject': 'subject', 'body': 'body'}], 'process': [{'identifiers': ['identifiers'], ... |
print("HelloWorld")
print(len("HelloWorld"))
a_string = "Hello"
b_string = "World"
print("a_string + b_string: ", a_string+b_string)
c_string = "abcdefghijklmnopqrstuvwxyz"
print("num of letters from a to z", len(c_string))
print(c_string[:3]) #abc
print(c_string[23:]) #xyz
#step count reverse
print(c_string[::-1])
#st... | print('HelloWorld')
print(len('HelloWorld'))
a_string = 'Hello'
b_string = 'World'
print('a_string + b_string: ', a_string + b_string)
c_string = 'abcdefghijklmnopqrstuvwxyz'
print('num of letters from a to z', len(c_string))
print(c_string[:3])
print(c_string[23:])
print(c_string[::-1])
print(c_string[::2])
print(c_st... |
def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item
| def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item |
a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s+len(b):]
print(ans)
| a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s + len(b):]
print(ans) |
# Lecture 5, Problem 9
def semordnilapWrapper(str1, str2):
# A single-length string cannot be semordnilap.
if len(str1) == 1 or len(str2) == 1:
return False
# Equal strings cannot be semordnilap.
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, s... | def semordnilap_wrapper(str1, str2):
if len(str1) == 1 or len(str2) == 1:
return False
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, str2):
"""
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
... |
#!/usr/bin/env python
# Monitoring the Mem usage of a Sonicwall
# Herward Cooper <coops@fawk.eu> - 2012
# Uses OID 1.3.6.1.4.1.8741.1.3.1.4.0
sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory=[]
inventory.append( (None, None, "sonicwall_mem_default_values") )
... | sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory = []
inventory.append((None, None, 'sonicwall_mem_default_values'))
return inventory
def check_sonicwall_mem(item, params, info):
(warn, crit) = params
state = int(info[0][0])
perfdata = [('cpu', st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.