content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module GDC-SC553-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GDC-SC553-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
#ui class
class UI:
def welcome():
print('Welcome to the Blackjack Trainer!')
print('This program is designed to help you practice your blackjack.')
print('Enter q to quit at any time.')
def hand_display(dealer_hand, hand):
print('Dealer shows:', dealer_hand[1])
pri... | class Ui:
def welcome():
print('Welcome to the Blackjack Trainer!')
print('This program is designed to help you practice your blackjack.')
print('Enter q to quit at any time.')
def hand_display(dealer_hand, hand):
print('Dealer shows:', dealer_hand[1])
print('Your hand:... |
numbers = [1,2,3,4,5]
# see contents of the array
print(numbers)
# length of the array
print(len(numbers))
#add to array
numbers.append(6)
namelist = []
#namelist = list()
# add names
namelist.append('name')
name = input("Enter your name: ")
if name in namelist:
print("I know you!")
else:
print("Sorry,... | numbers = [1, 2, 3, 4, 5]
print(numbers)
print(len(numbers))
numbers.append(6)
namelist = []
namelist.append('name')
name = input('Enter your name: ')
if name in namelist:
print('I know you!')
else:
print("Sorry, I don't know who you are :(")
x = [1, 2, 3]
x.append([4, 5])
print(x)
x = [1, 2, 3]
x.extend([4, 5]... |
class Periodo:
def __init__(self, codigo, nome, disciplina_lista):
self._id = codigo
self._nome = nome
self._disciplina_lista = disciplina_lista
def get_id(self):
return self._id
def get_nome(self):
return self._nome
def get_disciplina_lista(self):
... | class Periodo:
def __init__(self, codigo, nome, disciplina_lista):
self._id = codigo
self._nome = nome
self._disciplina_lista = disciplina_lista
def get_id(self):
return self._id
def get_nome(self):
return self._nome
def get_disciplina_lista(self):
ret... |
pubkey = 569581432115411077780908947843367646738369018797567841
with open("flag.enc") as f:
encoded = f.read()
flag = ""
for c in encoded.split(','):
if not c: break
if int(c, 16) != 0:
flag += "0"
else:
flag += "1"
print(hex(int(flag, 2))[2:].rstrip("L").decode("hex"))
| pubkey = 569581432115411077780908947843367646738369018797567841
with open('flag.enc') as f:
encoded = f.read()
flag = ''
for c in encoded.split(','):
if not c:
break
if int(c, 16) != 0:
flag += '0'
else:
flag += '1'
print(hex(int(flag, 2))[2:].rstrip('L').decode('hex')) |
class test_package:
def __init__(self):
# constructor
self.f = 1
def calc_string(self, equation):
equation = equation.strip()
if equation.isdigit():
return int(equation)
if '+' in equation:
temp = equation.split('+')
total = 0
... | class Test_Package:
def __init__(self):
self.f = 1
def calc_string(self, equation):
equation = equation.strip()
if equation.isdigit():
return int(equation)
if '+' in equation:
temp = equation.split('+')
total = 0
for x in temp:
... |
def Copy(file1='Weird.txt',file2='Weirdv2.txt'):
f=open(file2,'w')
lst=open(file1,'r').readlines()
for x in lst:
f.write(x)
f.close()
Copy(file1='Weird.txt',file2='Weirdv2.txt')
| def copy(file1='Weird.txt', file2='Weirdv2.txt'):
f = open(file2, 'w')
lst = open(file1, 'r').readlines()
for x in lst:
f.write(x)
f.close()
copy(file1='Weird.txt', file2='Weirdv2.txt') |
# coding: utf-8
def array_key_exists(key, d):
return key in d
if __name__ == '__main__':
search_array = {'first': 1, 'second': 4, '': False}
print(array_key_exists('first', search_array))
| def array_key_exists(key, d):
return key in d
if __name__ == '__main__':
search_array = {'first': 1, 'second': 4, '': False}
print(array_key_exists('first', search_array)) |
# I'm used to create a file which holds names of tables only and to call these names in the notebooks while reading data
# so that only changing this module will be quite efficient in case of any change of data sets to be used.
# Since I create this sample project in my local computer, I don't have access to Hive an... | data_dir = '../data/'
csv_transaction = DATA_DIR + 'transaction.csv'
csv_cust_info = DATA_DIR + 'client.csv'
csv_disp_info = DATA_DIR + 'disp.csv'
csv_account_info = DATA_DIR + 'account.csv'
csv_loan = DATA_DIR + 'loan.csv'
csv_customized_trnx = DATA_DIR + 'customized_trnx_data.csv'
csv_labelled_trnx = DATA_DIR + 'labe... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
class Position(list):
def __init__(self, x: int, y: int):
super().__init__((0, 0))
self.x = x
self.y = y
@property
def x(self):
return self[0]
@x.setter
def x(self, value):
if 0 <= value <= 12:
sel... | class Position(list):
def __init__(self, x: int, y: int):
super().__init__((0, 0))
self.x = x
self.y = y
@property
def x(self):
return self[0]
@x.setter
def x(self, value):
if 0 <= value <= 12:
self[0] = value
return
raise ex... |
class InvalidSignatureError(Exception):
""" """
| class Invalidsignatureerror(Exception):
""" """ |
def merge_sort(arr):
if len(arr) <= 1:
return
mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge_two_sorted_lists(left, right, arr)
def merge_two_sorted_lists(a, b, arr):
len_a = len(a)
len_b = len(b)
i = j = k = 0
w... | def merge_sort(arr):
if len(arr) <= 1:
return
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge_two_sorted_lists(left, right, arr)
def merge_two_sorted_lists(a, b, arr):
len_a = len(a)
len_b = len(b)
i = j = k = 0
while i... |
class BotServiceInterface:
async def start(self) -> None:
raise NotImplementedError
async def stop(self) -> None:
raise NotImplementedError
| class Botserviceinterface:
async def start(self) -> None:
raise NotImplementedError
async def stop(self) -> None:
raise NotImplementedError |
T = int(input())
for _ in range(T):
N, K, x, y = map(int, input().split())
if(x == y):
print(N, N)
else:
if(x<y):
final_cordinates = [[x+N-y, N], [N, N-y+x], [y-x, 0], [0, y-x]]
else:
final_cordinates = [[N, y+N-x], [y+N-x, N], [0, x-y], [x-y, 0]]
resu... | t = int(input())
for _ in range(T):
(n, k, x, y) = map(int, input().split())
if x == y:
print(N, N)
else:
if x < y:
final_cordinates = [[x + N - y, N], [N, N - y + x], [y - x, 0], [0, y - x]]
else:
final_cordinates = [[N, y + N - x], [y + N - x, N], [0, x - y]... |
def main(sam1, sam2):
# FilterSam1ByReadNamesFromSam2
outsamfile = '.'.join(sam1.split('.')[:-1] + ['RNAReadsConnectedDNAOver300winExtIES', 'sam'])
readnames = []
with open(sam2, 'r') as FILE:
for line in FILE:
if line[0] != '@':
readnames.append(line.strip()... | def main(sam1, sam2):
outsamfile = '.'.join(sam1.split('.')[:-1] + ['RNAReadsConnectedDNAOver300winExtIES', 'sam'])
readnames = []
with open(sam2, 'r') as file:
for line in FILE:
if line[0] != '@':
readnames.append(line.strip().split('\t')[0])
print('Number of reads i... |
lyrNames = ['admin_0.geom', 'admin_1.geom', 'admin_2.geom', 'admin_3.geom',
'postal_0.geom', 'postal_1.geom', 'postal_2.geom', 'postal_3.geom', 'postal_4.geom', 'postal_5.geom']
root = QgsProject.instance().layerTreeRoot()
model = iface.layerTreeView().layerTreeModel()
for lyrName in lyrNames:
lyr = QgsProject... | lyr_names = ['admin_0.geom', 'admin_1.geom', 'admin_2.geom', 'admin_3.geom', 'postal_0.geom', 'postal_1.geom', 'postal_2.geom', 'postal_3.geom', 'postal_4.geom', 'postal_5.geom']
root = QgsProject.instance().layerTreeRoot()
model = iface.layerTreeView().layerTreeModel()
for lyr_name in lyrNames:
lyr = QgsProject.in... |
class Solution:
def peakIndexInMountainArray(self, A):
length = len(A)
left = 0
right = length - 1
mid = int((right - left + 1) / 2)
while not (A[mid - 1] < A[mid] and A[mid] > A[mid + 1]):
print(mid, A[mid])
if A[mid] > A[mid - 1]:
lef... | class Solution:
def peak_index_in_mountain_array(self, A):
length = len(A)
left = 0
right = length - 1
mid = int((right - left + 1) / 2)
while not (A[mid - 1] < A[mid] and A[mid] > A[mid + 1]):
print(mid, A[mid])
if A[mid] > A[mid - 1]:
... |
dataset = dict(
user_file='./datasets/raw/traindata/user_features_data.csv',
video_file='./datasets/raw/traindata/video_features_data.csv',
# training_behavior_file='./datasets/raw/traindata/history_behavior_light.csv',
training_behavior_file='./datasets/raw/traindata/history_behavior_data.csv',
tes... | dataset = dict(user_file='./datasets/raw/traindata/user_features_data.csv', video_file='./datasets/raw/traindata/video_features_data.csv', training_behavior_file='./datasets/raw/traindata/history_behavior_data.csv', test_behavior_file='./datasets/raw/testdata/test.csv', save_dir='./datasets/array', video=dict(fill_nan=... |
#!/usr/bin/python3
file_to_write = open('converted_csv.txt', 'w+')
file_to_convert = open('test-csv.csv', 'r')
data = ''
with file_to_convert as myfile:
data = myfile.read()
data = data.replace("\n", ",")
data1 = data[0:239].lower()
data2 = data[240:479].lower()
data3 = data[480:719].lower()
data4 = data[720:-... | file_to_write = open('converted_csv.txt', 'w+')
file_to_convert = open('test-csv.csv', 'r')
data = ''
with file_to_convert as myfile:
data = myfile.read()
data = data.replace('\n', ',')
data1 = data[0:239].lower()
data2 = data[240:479].lower()
data3 = data[480:719].lower()
data4 = data[720:-1].lower()
print(len(dat... |
data = [word.lower() for word in input().split()]
odd_dict = {}
for word in data:
if word in odd_dict:
odd_dict[word] += 1
else:
odd_dict[word] = 1
for word, value in odd_dict.items():
if odd_dict[word] % 2 != 0:
print(word, end=" ")
| data = [word.lower() for word in input().split()]
odd_dict = {}
for word in data:
if word in odd_dict:
odd_dict[word] += 1
else:
odd_dict[word] = 1
for (word, value) in odd_dict.items():
if odd_dict[word] % 2 != 0:
print(word, end=' ') |
def readLine(line):
return [ int(c) for c in line.split(' ') ]
def jump(x, y):
# exactly one step of length 1 => exactly one of the numbers even
if x % 2 == y % 2 and (x != 0 or y != 0):
return 'IMPOSSIBLE'
if x == 0:
if y == 1:
return 'N'
if y == -1:
... | def read_line(line):
return [int(c) for c in line.split(' ')]
def jump(x, y):
if x % 2 == y % 2 and (x != 0 or y != 0):
return 'IMPOSSIBLE'
if x == 0:
if y == 1:
return 'N'
if y == -1:
return 'S'
if y == 0:
if x == 1:
return 'E'
... |
N, M = map(int,input().split())
for i in range(1,N,2):
print('-' * int((M-(3*i))/2) + i*'.|.' + '-' * int((M-(3*i))/2))
print('-' * int((M-7)/2) + "WELCOME" + '-' * int((M-7)/2))
for i in range(N-2,-1,-2):
print('-' * int((M - (3 * i)) / 2) + i * '.|.' + '-' * int((M - (3 * i)) / 2)) | (n, m) = map(int, input().split())
for i in range(1, N, 2):
print('-' * int((M - 3 * i) / 2) + i * '.|.' + '-' * int((M - 3 * i) / 2))
print('-' * int((M - 7) / 2) + 'WELCOME' + '-' * int((M - 7) / 2))
for i in range(N - 2, -1, -2):
print('-' * int((M - 3 * i) / 2) + i * '.|.' + '-' * int((M - 3 * i) / 2)) |
ambiguous_codes = {
"R": {"A", "G"},
"Y": {"C", "T"},
"S": {"G", "C"},
"W": {"A", "T"},
"K": {"G", "T"},
"M": {"A", "C"},
"B": {"C", "G", "T"},
"D": {"A", "G", "T"},
"H": {"A", "C", "T"},
"V": {"A", "C", "G"},
"N": {"A", "C", "G", "T"},
}
rev_ambiguous_codes = {"".join(sorte... | ambiguous_codes = {'R': {'A', 'G'}, 'Y': {'C', 'T'}, 'S': {'G', 'C'}, 'W': {'A', 'T'}, 'K': {'G', 'T'}, 'M': {'A', 'C'}, 'B': {'C', 'G', 'T'}, 'D': {'A', 'G', 'T'}, 'H': {'A', 'C', 'T'}, 'V': {'A', 'C', 'G'}, 'N': {'A', 'C', 'G', 'T'}}
rev_ambiguous_codes = {''.join(sorted(list(v))): k for (k, v) in ambiguous_codes.ite... |
MOD = 1000000007
n = int(input())
k = 1
L = []
for i in range(2,n+1):
k *= i
k %= MOD
L.append(k)
k2 = 1
for i in range(n-1):
k2 *= 2
k2%= MOD
print((k - k2 + MOD*MOD)%MOD) | mod = 1000000007
n = int(input())
k = 1
l = []
for i in range(2, n + 1):
k *= i
k %= MOD
L.append(k)
k2 = 1
for i in range(n - 1):
k2 *= 2
k2 %= MOD
print((k - k2 + MOD * MOD) % MOD) |
def outer(mynum):
def inner(a1):
return mynum ** a1
return inner
obj1 = outer(6)
obj2 = outer(5)
print(obj1(2))
print(obj2(3))
| def outer(mynum):
def inner(a1):
return mynum ** a1
return inner
obj1 = outer(6)
obj2 = outer(5)
print(obj1(2))
print(obj2(3)) |
#!/usr/bin/env python3
def main():
p1 = 0
p2 = 0
try:
with open('../input.txt', 'r') as fin:
d = fin.read().splitlines()
passes = []
for line in d:
seat_id = get_seat_id(line)
passes.append(seat_id)
p1 = seat_id if ... | def main():
p1 = 0
p2 = 0
try:
with open('../input.txt', 'r') as fin:
d = fin.read().splitlines()
passes = []
for line in d:
seat_id = get_seat_id(line)
passes.append(seat_id)
p1 = seat_id if seat_id > p1 else p1
... |
class Stack(object):
def __init__(self, checker=None):
self.__stack = []
self.__checker = checker
@property
def depth(self):
return len(self.__stack)
@property
def empty(self):
return self.depth == 0
@property
def top(self):
return self.__stack[0]
... | class Stack(object):
def __init__(self, checker=None):
self.__stack = []
self.__checker = checker
@property
def depth(self):
return len(self.__stack)
@property
def empty(self):
return self.depth == 0
@property
def top(self):
return self.__stack[0]
... |
# coding:utf-8
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
print("Give me two numbers, I'll divide them.")
print("Print q to exit.")
while True:
number1 = input("First number: ")
if number1 == 'q':
break
number2 = input("Second number: ")
if number2 == ... | try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
print("Give me two numbers, I'll divide them.")
print('Print q to exit.')
while True:
number1 = input('First number: ')
if number1 == 'q':
break
number2 = input('Second number: ')
if number2 == 'q':
br... |
#Program to find area and perimeter of a circle
radius=int(input("Enter the radius of a circle "))
area=3.14*radius**2
perimeter=2*3.14*radius
print("The area of a circle with radius",radius,"is ",area)
print("and the perimeter is",perimeter)
| radius = int(input('Enter the radius of a circle '))
area = 3.14 * radius ** 2
perimeter = 2 * 3.14 * radius
print('The area of a circle with radius', radius, 'is ', area)
print('and the perimeter is', perimeter) |
def test_activate(vf):
vf.run("vf new test")
vf.run("vf activate test")
out, _ = vf.run("which python")
assert out == "{homedir}/.virtualenvs/test/bin/python\n".format(homedir=vf.homedir).encode('utf8')
| def test_activate(vf):
vf.run('vf new test')
vf.run('vf activate test')
(out, _) = vf.run('which python')
assert out == '{homedir}/.virtualenvs/test/bin/python\n'.format(homedir=vf.homedir).encode('utf8') |
# Domotique @Lecanois
def allume(phrase):
talk(phrase)
Parse("http://192.168.1.27/lumieres.php")
def eteins(phrase):
talk(phrase)
Parse("http://192.168.1.27/lumiereoffs.php")
#RELAY CONTROL TO SHUTDOWN SERVO
sleep(0.1)
left.pinMode(53, Arduino.OUTPUT)
left.pinMode(51, Arduino.OUTPUT)
right.pinMode(53, Arduino... | def allume(phrase):
talk(phrase)
parse('http://192.168.1.27/lumieres.php')
def eteins(phrase):
talk(phrase)
parse('http://192.168.1.27/lumiereoffs.php')
sleep(0.1)
left.pinMode(53, Arduino.OUTPUT)
left.pinMode(51, Arduino.OUTPUT)
right.pinMode(53, Arduino.OUTPUT)
right.pinMode(51, Arduino.OUTPUT)
left.... |
def func2():
pass
def func1(n):
num = 0
while num < n:
yield func2
num += 1
for i in func1(100):
i()
| def func2():
pass
def func1(n):
num = 0
while num < n:
yield func2
num += 1
for i in func1(100):
i() |
input()
s = set(map(int,input().split()))
for it in range(int(input())):
line = input().split()
if line[0]=="pop":
s.pop()
elif line[0]=="remove":
s.remove(int(line[1]))
else:
s.discard(int(line[1]))
print(sum(s))
| input()
s = set(map(int, input().split()))
for it in range(int(input())):
line = input().split()
if line[0] == 'pop':
s.pop()
elif line[0] == 'remove':
s.remove(int(line[1]))
else:
s.discard(int(line[1]))
print(sum(s)) |
#take 1st minm element put it on the 1st place.
#take 2nd minm element put it on the 2nd place.
#take nth minm element put it on the nth place.
def get_min(L):
min=L[0]
i=0
idx=i
while(i<len(L)):
if L[i]<min:
min=L[i]
idx=i
i=i+1
return min,idx
#L=[12,13,54,4,4,7]
min,idx=get_min(L)
def s... | def get_min(L):
min = L[0]
i = 0
idx = i
while i < len(L):
if L[i] < min:
min = L[i]
idx = i
i = i + 1
return (min, idx)
(min, idx) = get_min(L)
def selection_sort(L):
for i in range(0, len(L) - 1):
print(L[i:])
(minm, min_idx) = get_min(L... |
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licen... | """
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
"""Top-level package for Speech emotion Recognition."""
__author__ = """Hrithik Chourasia"""
__email__ = 'hrithik8wel@gmail.com'
__version__ = '0.1.0'
| """Top-level package for Speech emotion Recognition."""
__author__ = 'Hrithik Chourasia'
__email__ = 'hrithik8wel@gmail.com'
__version__ = '0.1.0' |
'''
Common implementation of a Linked List.
'''
class Node():
def __init__(self,value,next_pointer):
self.value = value
self.next = next_pointer
class LinkedList():
def __init__(self, head):
self.next = None #pointer to the next node
self.head_node = Node(hea... | """
Common implementation of a Linked List.
"""
class Node:
def __init__(self, value, next_pointer):
self.value = value
self.next = next_pointer
class Linkedlist:
def __init__(self, head):
self.next = None
self.head_node = node(head, self.next)
self.nodes = [self.hea... |
N = int(input())
for k in range(N):
S = input()
print("Ciencia da Computacao")
| n = int(input())
for k in range(N):
s = input()
print('Ciencia da Computacao') |
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
negative, result = n < 0, 1
n = abs(n)
while n > 0:
base, p = x, 2
while p < n:
base *= base
p *= 2
result *= base
n -= p // 2
return 1 / result if negative else res... | class Solution:
def my_pow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
(negative, result) = (n < 0, 1)
n = abs(n)
while n > 0:
(base, p) = (x, 2)
while p < n:
base *= base
... |
def install(job):
cuisine = job.service.executor.cuisine
name = 'mongod_%s' % job.service.name
cuisine.apps.mongodb.install(start=True, name=name)
def start(job):
cuisine = job.service.executor.cuisine
name = 'mongod_%s' % job.service.name
cuisine.apps.mongodb.start(name)
def stop(job):
... | def install(job):
cuisine = job.service.executor.cuisine
name = 'mongod_%s' % job.service.name
cuisine.apps.mongodb.install(start=True, name=name)
def start(job):
cuisine = job.service.executor.cuisine
name = 'mongod_%s' % job.service.name
cuisine.apps.mongodb.start(name)
def stop(job):
cu... |
def encode_string(clear_text):
cypher = ""
for char in clear_text:
cypher = cypher + character_encode(char)
return cypher
def char_to_num(char):
return ord(char)
def char_to_encoded(char):
encoded = char_to_num(char) + 13
if encoded > 122:
end_of_alpha = ord('z')
be... | def encode_string(clear_text):
cypher = ''
for char in clear_text:
cypher = cypher + character_encode(char)
return cypher
def char_to_num(char):
return ord(char)
def char_to_encoded(char):
encoded = char_to_num(char) + 13
if encoded > 122:
end_of_alpha = ord('z')
begin_... |
# https://www.codewars.com/kata/54ba84be607a92aa900000f1/train/python
# An isogram is a word that has no repeating letters, consecutive or
# non-consecutive. Implement a function that determines whether a
# string that contains only letters is an isogram. Assume the empty
# string is an isogram. Ignore letter case.
... | def is_isogram(string):
arr = []
for e in string:
if e.lower() in arr:
return False
else:
arr.append(e.lower())
return True |
number1 = 7
number2 = 2
print(number1)
print(number2)
# ARITHMATIC OPERATOR
#
# + - * / %
sumRes = number1 + number2
subRes = number1 - number2
multRes = number1 * number2
diviRes = number1 / number2
restRes = number1 % number2
print(sumRes)
print(subRes)
print(multRes)
print(diviRes)
print(restRes)
newVa... | number1 = 7
number2 = 2
print(number1)
print(number2)
sum_res = number1 + number2
sub_res = number1 - number2
mult_res = number1 * number2
divi_res = number1 / number2
rest_res = number1 % number2
print(sumRes)
print(subRes)
print(multRes)
print(diviRes)
print(restRes)
new_value = 3 * (4 + 1 - 2) * 2
print(newValue) |
"""
Class file for the ArmedSwitch class
"""
class ArmedSwitch(object):
"""
ArmedSwitch is a boolean switch that must be explicitly re-armed after
each time it switches, or else it keeps the same state.
"""
# __init__: ArmedSwitch initializer
def __init__(self, switched=False, armed=True):
... | """
Class file for the ArmedSwitch class
"""
class Armedswitch(object):
"""
ArmedSwitch is a boolean switch that must be explicitly re-armed after
each time it switches, or else it keeps the same state.
"""
def __init__(self, switched=False, armed=True):
"""
Initializer for ArmedSw... |
second=50
def func01(first01):
first=10
func02(first01)
return
def func02(first02):
first=20
return
if __name__ == '__main__' :
#first=30
#func01(first)
a=30
b=4.2
c='G'
pass
| second = 50
def func01(first01):
first = 10
func02(first01)
return
def func02(first02):
first = 20
return
if __name__ == '__main__':
a = 30
b = 4.2
c = 'G'
pass |
lights = [True for _ in range(5000000)]
Q = int(input())
queries = []
for _ in range(Q):
queries.append(input().split())
for query in queries:
if(query[0]=='1'):
lights[int(query[1])] = False
elif(query[0]=='2'):
pos = int(query[1])
dist = 0
for dist in ran... | lights = [True for _ in range(5000000)]
q = int(input())
queries = []
for _ in range(Q):
queries.append(input().split())
for query in queries:
if query[0] == '1':
lights[int(query[1])] = False
elif query[0] == '2':
pos = int(query[1])
dist = 0
for dist in range(5000000 - pos)... |
def solve(test, printing = False):
decrypted = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', ',', '?', '(', ')', '!']
... | def solve(test, printing=False):
decrypted = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '?', '(', ')', '!']
encrypted = ['/', '.-', '-...', '-.-.', '-..', '.', '..-... |
"""
Provide a djangoapp for XBlock development
"""
__version__ = '0.5.1'
| """
Provide a djangoapp for XBlock development
"""
__version__ = '0.5.1' |
class Song:
def __init__(self, name):
self.name = name
self.next = None
def next_song(self, song):
self.next = song
def is_repeating_playlist(self):
"""
:returns: (bool) True if the playlist is repeating, False if not.
"""
visited = set()
... | class Song:
def __init__(self, name):
self.name = name
self.next = None
def next_song(self, song):
self.next = song
def is_repeating_playlist(self):
"""
:returns: (bool) True if the playlist is repeating, False if not.
"""
visited = set()
wh... |
class StorageProcessorCacheDirtySize(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_sp_cache_dirty_size(idx_name)
class StorageProcessorCacheDirtySizeColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_sps()
| class Storageprocessorcachedirtysize(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_sp_cache_dirty_size(idx_name)
class Storageprocessorcachedirtysizecolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_sps() |
# 025
# Ask the user to enter their first name. If the length of their first
# name is under five characters, ask them to enter their surname and
# join them together (without a space) and display the name in upper
# case. If the length of the first name is five or more characters,
# display their first name in lower c... | def length(s1: str, l: int=5) -> bool:
if len(s1) < l:
return True
return False
while True:
try:
first_name: str = input('Please enter your first name: ')
if length(first_name):
surname: str = input('Please enter your surname: ')
print(first_name.upper(), surn... |
# To actually have your app use this file, you need to RENAME the file to db_credentials.py
# You will find details about your CS340 database credentials on Canvas.
# the following will be used by the db_connector.py and
# in turn by all the Python code in this codebase to interact with the database
host =... | host = 'carsrusdb.cflvftqirmoz.us-east-1.rds.amazonaws.com'
user = 'masteruser'
passwd = 'carsrusdb'
db = 'carsrusdb' |
{
"12345":{
"condition":{
"Material":["50007747","50335560","425452"],
"Filial":["BR19","BR23","BR40"]
},
"implication": {
"IVAMIRO": ["TESTE"]
},
"date": "2019-01-01",
"user": "99813554",
"description": "this rules was created in order to do somethi... | {'12345': {'condition': {'Material': ['50007747', '50335560', '425452'], 'Filial': ['BR19', 'BR23', 'BR40']}, 'implication': {'IVAMIRO': ['TESTE']}, 'date': '2019-01-01', 'user': '99813554', 'description': 'this rules was created in order to do something and some other thing'}, '713123': {'condition': {'Material': [123... |
{
"targets": [
{
"target_name": "shm",
"sources": [ "shm.cpp" ],
"libraries" : [
"-lrt"
]
}
]
}
| {'targets': [{'target_name': 'shm', 'sources': ['shm.cpp'], 'libraries': ['-lrt']}]} |
def two_list_dictionary(keys, values):
"""Given keys and values, make dictionary of those.
>>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7])
{'x': 9, 'y': 8, 'z': 7}
If there are fewer values than keys, remaining keys should have value
of None:
>>> two_list_dictionary(['a', 'b',... | def two_list_dictionary(keys, values):
"""Given keys and values, make dictionary of those.
>>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7])
{'x': 9, 'y': 8, 'z': 7}
If there are fewer values than keys, remaining keys should have value
of None:
>>> two_list_dictionary(['a', 'b',... |
if __name__=='__main__':
while True:
try:
s=input().split(' ')
a=[]
for itm in s:
a.append(itm[::-1])
print(*a)
except:
break
| if __name__ == '__main__':
while True:
try:
s = input().split(' ')
a = []
for itm in s:
a.append(itm[::-1])
print(*a)
except:
break |
# Released under CC0:
# Summary: https://creativecommons.org/publicdomain/zero/1.0/
# Legal Code: https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt
win_w, win_h = 1000, 600
rec_x = win_w * 0.9
rec_y = win_h / 2
rec_w = win_w * 0.01
rec_h = win_h * 0.2
r = 10
pos = PVector(win_w * 0.1, win_h / 2)
vel = ... | (win_w, win_h) = (1000, 600)
rec_x = win_w * 0.9
rec_y = win_h / 2
rec_w = win_w * 0.01
rec_h = win_h * 0.2
r = 10
pos = p_vector(win_w * 0.1, win_h / 2)
vel = p_vector(6, 7)
def setup():
frame_rate(60)
size(win_w, win_h)
def draw():
global pos, vel, rec_y
rec_y = mouseY - rec_h / 2
refresh()
... |
# Service Lane
# Calculate the maximum width of the vehicle that can pass through a service lane.
#
# https://www.hackerrank.com/challenges/service-lane/problem
#
def serviceLane(width, a, b):
# euh? comment dire...
print(min(width[a:b + 1]))
if __name__ == "__main__":
n, t = map(int, input().split())
... | def service_lane(width, a, b):
print(min(width[a:b + 1]))
if __name__ == '__main__':
(n, t) = map(int, input().split())
width = list(map(int, input().split()))
for _ in range(t):
(a, b) = map(int, input().split())
service_lane(width, a, b) |
class Solution:
def maxProfit(self, prices):
# greedy
profit = 0
for i in range(len(prices)-1):
tmp = prices[i+1] - prices[i]
if tmp > 0:
profit += tmp
return profit
| class Solution:
def max_profit(self, prices):
profit = 0
for i in range(len(prices) - 1):
tmp = prices[i + 1] - prices[i]
if tmp > 0:
profit += tmp
return profit |
"""Bot exceptions module."""
class CameraBotError(Exception):
pass
class ConfigError(Exception):
pass
class UserAuthError(Exception):
pass
class HikvisionCamError(Exception):
pass
class DirectoryWatcherError(Exception):
pass
class APIError(Exception):
pass
class APIRequestError(API... | """Bot exceptions module."""
class Cameraboterror(Exception):
pass
class Configerror(Exception):
pass
class Userautherror(Exception):
pass
class Hikvisioncamerror(Exception):
pass
class Directorywatchererror(Exception):
pass
class Apierror(Exception):
pass
class Apirequesterror(APIError):... |
def sum_zero(n):
zero_sum_array = []
counter = 1
if n % 2 != 0:
zero_sum_array.append(0)
n -= 1
while n:
zero_sum_array.append(counter)
zero_sum_array.append(-counter)
counter += 1
n -= 2
return zero_sum_array
| def sum_zero(n):
zero_sum_array = []
counter = 1
if n % 2 != 0:
zero_sum_array.append(0)
n -= 1
while n:
zero_sum_array.append(counter)
zero_sum_array.append(-counter)
counter += 1
n -= 2
return zero_sum_array |
"""
Desc: Skeleton app to access API's with JWT tokens
Author: [marirs,]
version: 1.0
"""
| """
Desc: Skeleton app to access API's with JWT tokens
Author: [marirs,]
version: 1.0
""" |
# Insertion sort
def insertion_sort(arr):
'''
Sort list using insertion sort.
Return number of comparisons made.
'''
comparisons = 0
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
comparisons += 2
arr[j+1] = arr[j... | def insertion_sort(arr):
"""
Sort list using insertion sort.
Return number of comparisons made.
"""
comparisons = 0
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
comparisons += 2
arr[j + 1] = arr[j]
... |
seat = []
min = 0
max = 5
print(min <= len(seat) < max)
# True
seat.append('person')
seat.append('person')
seat.append('person')
seat.append('person')
seat.append('person')
print(min <= len(seat) < max)
# False
seat.pop()
print(min <= len(seat) < max)
# True | seat = []
min = 0
max = 5
print(min <= len(seat) < max)
seat.append('person')
seat.append('person')
seat.append('person')
seat.append('person')
seat.append('person')
print(min <= len(seat) < max)
seat.pop()
print(min <= len(seat) < max) |
# -*- coding: utf-8 -*-
"""
@author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/
"""
#This is a summary statistic + database query tool
#Define function
def SGapDown(s):
#Percentage measure of how current high is lower than previous low
s['GapDown'] = (s['Low'].shift(1) - s['High'])... | """
@author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/
"""
def s_gap_down(s):
s['GapDown'] = (s['Low'].shift(1) - s['High']) / s['Adj Close'].shift(1)
s['GapDown'] = s['GapDown'][s['GapDown'] > 0]
s['GapDown'] = s['GapDown'].fillna(0)
return s['GapDown'].tail(1) |
"""
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
All given inputs are in lowercase letters a-z.
"""
class Solution:
# Runtime: 32 ms, faster than 92.33% of Python3 online submissions for Lo... | """
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
All given inputs are in lowercase letters a-z.
"""
class Solution:
def longest_common_prefix(self, strs):
if len(strs) == 0:
... |
# Taken from https://github.com/first20hours/google-10000-english/blob/master/google-10000-english-no-swears.txt
# then extracted only words with 5 letters while keeping the order.
# fives_popular = []
fives = [
"aahed",
"aalii",
"aargh",
"aaron",
"abaca",
"abaci",
"aback",
"abada",
... | fives = ['aahed', 'aalii', 'aargh', 'aaron', 'abaca', 'abaci', 'aback', 'abada', 'abaff', 'abaft', 'abaka', 'abama', 'abamp', 'aband', 'abase', 'abash', 'abask', 'abate', 'abaue', 'abave', 'abaze', 'abbas', 'abbey', 'abbes', 'abbie', 'abbot', 'abdal', 'abdat', 'abdom', 'abeam', 'abear', 'abede', 'abele', 'abend', 'aber... |
# Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks.
# Lets say im inserting 1 2 3 to the queue when i remove i have to do 1 2 3
# If I add 1 then all is normal then 2 in a stack would look like 1 2 and pop would go like 2 1
# but if i have two stacks and actively swap them i would h... | class Llist:
value = None
next = None
def __init__(self):
pass
def print_list(self):
if self.next is None:
print(self.value)
return
print(self.value, end=' ')
return self.next.print_list()
class Nclassicstack:
def __init__(self):
se... |
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
... | url = '/constants'
unknown_name = 'unknown constant'
name = 'distributions'
constants_with_specific_name = [{'id': 'YmPDAQAchr39KjECQ', 'name': NAME, 'data': [{'value': 'Canonical-icehouse', 'label': 'Canonical-icehouse'}, {'value': 'Canonical-juno', 'label': 'Canonical-juno'}]}] |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | def id_wrapper(freer):
"""
Classes create with IDWrapper return an ID and then free it upon exit of the
context.
"""
class Wrapper:
def __init__(self, conn):
self.conn = conn
self.id = None
def __enter__(self):
self.id = self.conn.generate_id()
... |
#!/usr/bin/python
ransac_iters = [1000, 5000]
ncc_threshold_s = [0.6, 0.7, 0.8]
ncc_threshold_m = [0.6, 0.7, 0.8]
#search_wsz = [180, 200, 230]
harris_block_sz = [3, 5]
harris_k = [0.04, 0.06]
harris_thr = [0.00001, 0.000001, 0.0000001]
fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_vali... | ransac_iters = [1000, 5000]
ncc_threshold_s = [0.6, 0.7, 0.8]
ncc_threshold_m = [0.6, 0.7, 0.8]
harris_block_sz = [3, 5]
harris_k = [0.04, 0.06]
harris_thr = [1e-05, 1e-06, 1e-07]
fp_runscript = open('/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_validation.sh', 'w')
fp_runscript.write('#!/bin/bash\n\n')
cnt = ... |
##Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
##Last Updated : 19 Oct, 2020
##Given two integers X and Y, the task is to perform the following operations:
##
##Find all prime numbers in the range [X, Y].
##Generate all numbers possible by combining every pair o... | prime = [True for i in range(100001)]
def gen_prime():
p = 2
while p * p <= 100000:
if prime[p] == True:
for i in range(p * p, 100001, p):
prime[i] = False
p += 1
def fibonacci_prime(n1, n2):
gen_prime()
initial = []
for i in range(n1, n2):
if pr... |
print("Hello world!")
print(1 + 2)
print(7 * 6)
print()
print("The end","Or is it?","Keep watching to learn more about Python",3) | print('Hello world!')
print(1 + 2)
print(7 * 6)
print()
print('The end', 'Or is it?', 'Keep watching to learn more about Python', 3) |
p = int(input())
for i in range(0, p):
k, n = map(int, input().split())
days = 0
days += n
for j in range(1, n+1):
days += j
print(k, days)
| p = int(input())
for i in range(0, p):
(k, n) = map(int, input().split())
days = 0
days += n
for j in range(1, n + 1):
days += j
print(k, days) |
n,m = map(int,input().split())
price_number = [0 for _ in range(n)]
for i in range(n):
price_number[i] = list(map(int,input().split()))
price_number.sort()
price = 0
index = 0
while m > 0:
if m >= price_number[index][1]:
price += price_number[index][0]*price_number[index][1]
m -= price_number... | (n, m) = map(int, input().split())
price_number = [0 for _ in range(n)]
for i in range(n):
price_number[i] = list(map(int, input().split()))
price_number.sort()
price = 0
index = 0
while m > 0:
if m >= price_number[index][1]:
price += price_number[index][0] * price_number[index][1]
m -= price_nu... |
data = (
'Xu ', # 0x00
'Ji ', # 0x01
'Mu ', # 0x02
'Chen ', # 0x03
'Xiao ', # 0x04
'Zha ', # 0x05
'Ting ', # 0x06
'Zhen ', # 0x07
'Pei ', # 0x08
'Mei ', # 0x09
'Ling ', # 0x0a
'Qi ', # 0x0b
'Chou ', # 0x0c
'Huo ', # 0x0d
'Sha ', # 0x0e
'Fei ', # 0x0f
'Wen... | data = ('Xu ', 'Ji ', 'Mu ', 'Chen ', 'Xiao ', 'Zha ', 'Ting ', 'Zhen ', 'Pei ', 'Mei ', 'Ling ', 'Qi ', 'Chou ', 'Huo ', 'Sha ', 'Fei ', 'Weng ', 'Zhan ', 'Yin ', 'Ni ', 'Chou ', 'Tun ', 'Lin ', '[?] ', 'Dong ', 'Ying ', 'Wu ', 'Ling ', 'Shuang ', 'Ling ', 'Xia ', 'Hong ', 'Yin ', 'Mo ', 'Mai ', 'Yun ', 'Liu ', 'Meng ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 21:45:36 2018
@author: owner
"""
def isPalindrome(x):
y = x
new = 0
if x.bit_length() > 31 | x < 0:
return False
while y != 0:
remainder = y % 10
new = new * 10 + remainder
y = int(y/10)
return... | """
Created on Wed Feb 14 21:45:36 2018
@author: owner
"""
def is_palindrome(x):
y = x
new = 0
if x.bit_length() > 31 | x < 0:
return False
while y != 0:
remainder = y % 10
new = new * 10 + remainder
y = int(y / 10)
return x == new |
'''
Author : Arnob Mahmud
Mail : arnob.tech.me @ gmail.com
'''
# 1 + 2 + 3 + ...................... + n
num = int(input("Enter the last number : "))
sum = 0
for x in range( 1, num + 1, 1):
sum = sum + x
print("Sum is :", sum)
# 2 + 4 + 6 + ..................... + n
num1 = int(input("Enter last value :")... | """
Author : Arnob Mahmud
Mail : arnob.tech.me @ gmail.com
"""
num = int(input('Enter the last number : '))
sum = 0
for x in range(1, num + 1, 1):
sum = sum + x
print('Sum is :', sum)
num1 = int(input('Enter last value :'))
sum1 = 0
for x in range(2, num1 + 1, 1):
sum1 = sum1 + x
print('Sum is :', sum1)
n... |
# Nice Detective!
# Don't defect first, but try to figure out oppenent if they have defected
def strategy(history, memory):
"""
:history: 2d numpy array of our and opponent past moves
:memory: dict
"""
num_rounds = history.shape[1]
max_defection_threshold = .5
if num_rounds == 0:
... | def strategy(history, memory):
"""
:history: 2d numpy array of our and opponent past moves
:memory: dict
"""
num_rounds = history.shape[1]
max_defection_threshold = 0.5
if num_rounds == 0:
choice = 1
memory = {}
memory['opponent_defections'] = 0
memory['oppone... |
sq = [i**2 for i in range(0, 11)]
# print (sq)
pari = [i for i in sq if i%2 == 0]
print (pari)
| sq = [i ** 2 for i in range(0, 11)]
pari = [i for i in sq if i % 2 == 0]
print(pari) |
class Process:
def __init__(self,name,arrival,burst):
self.name = name
self.arrival_time = arrival
self.burst_time = burst
def set_arrival_time(self,time):
self.arrival_time = time
def get_arrival_time(self):
return self.arrival_time
def get_burst_time(self):
return self.burst_time
def set_burst_time(s... | class Process:
def __init__(self, name, arrival, burst):
self.name = name
self.arrival_time = arrival
self.burst_time = burst
def set_arrival_time(self, time):
self.arrival_time = time
def get_arrival_time(self):
return self.arrival_time
def get_burst_time(sel... |
# Exercise 3: Rewrite the guardian code in the above example without two if statements. Instead, use a compound logical expression using the or logical operator with a single if statement.
fhand = open('mbox-short-edited.txt')
count = 0
for line in fhand:
words = line.split()
#print('Debug:', words)
if len(words) ... | fhand = open('mbox-short-edited.txt')
count = 0
for line in fhand:
words = line.split()
if len(words) >= 3 and words[0] == 'From':
print(words[2]) |
COLUMNS = [
'TIPO_REGISTRO',
'NRO_FILIACAO_MATRIZ_OU_GRUPO_COMERCIAL',
'QTDE_RESUMOS_VENDAS',
'QTDE_COMPROVANTES_VENDAS',
'TOTAL_BRUTO',
'TOTAL_DESCONTO',
'TOTAL_LIQUIDO'
'VL_BRUTO_PREDATADO',
'DESCONTO_PREDATADO',
'LIQUIDO_PREDATADO',
'TOTAL_REGISTROS_ARQUIVO'
] | columns = ['TIPO_REGISTRO', 'NRO_FILIACAO_MATRIZ_OU_GRUPO_COMERCIAL', 'QTDE_RESUMOS_VENDAS', 'QTDE_COMPROVANTES_VENDAS', 'TOTAL_BRUTO', 'TOTAL_DESCONTO', 'TOTAL_LIQUIDOVL_BRUTO_PREDATADO', 'DESCONTO_PREDATADO', 'LIQUIDO_PREDATADO', 'TOTAL_REGISTROS_ARQUIVO'] |
mystr = "abcdcba"
start = 0
last = len(mystr)-1
flag = False
while(start <= last):
if(mystr[start] != mystr[last]):
flag = True
break
start = start + 1
last = last - 1
if(flag == True):
print("Not a palindrome.")
if(flag == False):
print("Palindrome.")
| mystr = 'abcdcba'
start = 0
last = len(mystr) - 1
flag = False
while start <= last:
if mystr[start] != mystr[last]:
flag = True
break
start = start + 1
last = last - 1
if flag == True:
print('Not a palindrome.')
if flag == False:
print('Palindrome.') |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a , b ) :
m = len ( a )
n = len ( b )
lookup = [ [ 0 ] * ( n + 1 ) for i in range ( m + 1 ) ]
for i... | def f_gold(a, b):
m = len(a)
n = len(b)
lookup = [[0] * (n + 1) for i in range(m + 1)]
for i in range(n + 1):
lookup[0][i] = 0
for i in range(m + 1):
lookup[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
... |
n=int(input())
ans=0
for i in range(1,n+1):
ans+=2**i
print(ans) | n = int(input())
ans = 0
for i in range(1, n + 1):
ans += 2 ** i
print(ans) |
#!python
# TBD: children() or children_of() ?
# TBD: provide map/filter/fold functions
"""
type Label = String
data JSP = Lit Label
| Seq Label [JSP]
| Alt Label [JSP]
| Rep Label JSP
Each node has a uid.
* retains identity even if labels change
* lists of tuples of nodeid perm... | """
type Label = String
data JSP = Lit Label
| Seq Label [JSP]
| Alt Label [JSP]
| Rep Label JSP
Each node has a uid.
* retains identity even if labels change
* lists of tuples of nodeid permit graph processing
* what about t.copy()?
* what about serialization?
* why not us... |
def solve(n):
s1 = n * (n + 1) * (2 * n + 1) // 6
s2 = (n * (n + 1) // 2) ** 2
return s2 - s1
# n = 10
n = 100
print(solve(n))
| def solve(n):
s1 = n * (n + 1) * (2 * n + 1) // 6
s2 = (n * (n + 1) // 2) ** 2
return s2 - s1
n = 100
print(solve(n)) |
'''Paths and filenames used by `smartmove` modules. These are not to be changed'''
paths = {
# Contains datalogger data for each experiment to be analyzed
'tag': 'data_tag',
# Contains `.csv` files for field and isotope experiments
'csv': 'data_csv',
# Contains data from CTD measurements
'ctd':... | """Paths and filenames used by `smartmove` modules. These are not to be changed"""
paths = {'tag': 'data_tag', 'csv': 'data_csv', 'ctd': 'data_ctd', 'glide': 'data_glide', 'ann': 'model_ann'}
fnames = {'cfg': {'project': 'cfg_project.yml', 'exp_bounds': 'cfg_experiments.yml', 'glide': 'cfg_glide.yml', 'ann': 'cfg_ann.y... |
#World size determines how big the world map is.
world_size = {
"x" : 5,
"y" : 5
}
currency = "Gold"
MAX_MONSTERS = 10000
| world_size = {'x': 5, 'y': 5}
currency = 'Gold'
max_monsters = 10000 |
# CTCI 1.2: Check permutations
# Given two strings, write a method to decide if one is a permutation of the other.
def isPermutation(s1:str, s2:str)-> bool:
l1 = len(s1)
l2 = len(s2)
if l1 != l2: return False
dict = {}
# O(n)
for c in s1:
if c in dict:
dict[c] += 1
... | def is_permutation(s1: str, s2: str) -> bool:
l1 = len(s1)
l2 = len(s2)
if l1 != l2:
return False
dict = {}
for c in s1:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
for c in s2:
if c in dict:
dict[c] -= 1
else:
... |
# Question Link : https://app.codesignal.com/challenge/LPAySw9MQXCi7934W
# Level : Hard for beginners
# Solution right below :-
def minDistTriplet(a, b, c):
minDist = 2**31
x,y,z=a.pop(),b.pop(),c.pop()
while True:
# 'x' should be max(x,y,z) always
# 'a' should always points to l... | def min_dist_triplet(a, b, c):
min_dist = 2 ** 31
(x, y, z) = (a.pop(), b.pop(), c.pop())
while True:
if y > x and y >= z:
(a, b) = (b, a)
(x, y) = (y, x)
elif z > x and z >= y:
(c, a) = (a, c)
(x, z) = (z, x)
min_dist = min(minDist, x ... |
a = []
for i in range(9):
a.append(int(input()))
print(max(a))
print(a.index(max(a))+1) | a = []
for i in range(9):
a.append(int(input()))
print(max(a))
print(a.index(max(a)) + 1) |
# Code generation format strings for UFC (Unified Form-assembly Code) v. 2.0.5.
# This code is released into the public domain.
#
# The FEniCS Project (http://www.fenicsproject.org/) 2006-2011.
finite_element_combined = """\
/// This class defines the interface for a finite element.
class %(classname)s: public ufc::f... | finite_element_combined = '/// This class defines the interface for a finite element.\n\nclass %(classname)s: public ufc::finite_element\n{%(members)s\npublic:\n\n /// Constructor\n %(classname)s(%(constructor_arguments)s) : ufc::finite_element()%(initializer_list)s\n {\n%(constructor)s\n }\n\n /// Destructor\n v... |
def Dict1():
return {'key1': 'value1'}
def Dict2():
return {'key2': 'value1'}
# print(Dict1().update(Dict2())) # None
d = Dict1()
d.update(Dict2())
print(d)
| def dict1():
return {'key1': 'value1'}
def dict2():
return {'key2': 'value1'}
d = dict1()
d.update(dict2())
print(d) |
expected_output = {
'confd-status': 'Started',
'processes': {
'nesd': {
'state': 'Active',
'status': 'Running'
},
'syncfd': {
'state': 'Active',
'status': 'Running'
},
'ncsshd': {
'state': 'Not Applicable',
'status': 'Running'
},
'dmiauthd': {
's... | expected_output = {'confd-status': 'Started', 'processes': {'nesd': {'state': 'Active', 'status': 'Running'}, 'syncfd': {'state': 'Active', 'status': 'Running'}, 'ncsshd': {'state': 'Not Applicable', 'status': 'Running'}, 'dmiauthd': {'state': 'Active', 'status': 'Running'}, 'nginx': {'state': 'Not Applicable', 'status... |
# List Cycle
# https://www.interviewbit.com/problems/list-cycle/
#
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
#
# Try solving it using constant additional space.
#
# Example :
#
# Input :
#
# ______
# | |
# \/... | class Solution:
def detect_cycle(self, A):
slow = fast = A
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
else:
return None
slow = A
while slow != fast:
slow ... |
step(
"""
alter table image
add column title text,
add column description text
""",
"""
alter table image
drop column description,
drop column title
"""
)
| step('\n alter table image\n add column title text,\n add column description text\n ', '\n alter table image\n drop column description,\n drop column title\n ') |
number = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358907296... | number = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358907296... |
__all__ = (
'UIDValueError',
'ModelFieldError',
'ModelValidationError',
'EmailValidationError',
'PhoneValidationError',
'ForcedBalanceError',
'KeyCloakMigrationError'
)
class UIDValueError(ValueError):
pass
class ModelFieldError(Exception):
pass
class ModelValidationError(Excep... | __all__ = ('UIDValueError', 'ModelFieldError', 'ModelValidationError', 'EmailValidationError', 'PhoneValidationError', 'ForcedBalanceError', 'KeyCloakMigrationError')
class Uidvalueerror(ValueError):
pass
class Modelfielderror(Exception):
pass
class Modelvalidationerror(Exception):
pass
class Emailvalid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.