content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def Sequential_Search(elements):
for i in range (len(elements)): #outer loop for comparison
for j in range (len(elements)):#inner loop to compare against outer loop
pos = 0
found = False
while pos < len(elements) and not found:
if j == i:
... | def sequential__search(elements):
for i in range(len(elements)):
for j in range(len(elements)):
pos = 0
found = False
while pos < len(elements) and (not found):
if j == i:
continue
else:
pos = pos + 1... |
def palcheck(s):
ns=""
for i in s:
ns=i+ns
if s==ns:
return True
return False
def cod(s):
l=len(s)
for i in range(2,l):
if palcheck(s[:i]):
t1=s[:i]
k=s[i:]
break
t=len(k)
for j in range(2... | def palcheck(s):
ns = ''
for i in s:
ns = i + ns
if s == ns:
return True
return False
def cod(s):
l = len(s)
for i in range(2, l):
if palcheck(s[:i]):
t1 = s[:i]
k = s[i:]
break
t = len(k)
for j in range(2, t):
if palch... |
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
strs = []
tmp = ''
for s in paragraph:
if s in '!? \';.,':
if tmp:
strs.append(tmp)
tmp = ''
else:
tmp += s.lowe... | class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
strs = []
tmp = ''
for s in paragraph:
if s in "!? ';.,":
if tmp:
strs.append(tmp)
tmp = ''
else:
tmp += s.lo... |
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
dp = []
dp.append(nums[0])
dp.append(max(nums[0], nums[1]))
for i in range(2, len(nums)):
dp.append(max(nums[i] + d... | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
dp = []
dp.append(nums[0])
dp.append(max(nums[0], nums[1]))
for i in range(2, len(nums)):
dp.append(max(nums[i] + ... |
def foo(x, y):
s = x + y
if s > 10:
print("s>10")
elif s > 5:
print("s>5")
else:
print("less")
print("over")
def bar():
s = 1 + 2
if s > 10:
print("s>10")
elif s > 5:
print("s>5")
else:
print("less")
print("over")
| def foo(x, y):
s = x + y
if s > 10:
print('s>10')
elif s > 5:
print('s>5')
else:
print('less')
print('over')
def bar():
s = 1 + 2
if s > 10:
print('s>10')
elif s > 5:
print('s>5')
else:
print('less')
print('over') |
#coding:utf-8
'''
filename:arabic2roman.py
chap:6
subject:6
conditions:translate Arabic numerals to Roman numerals
solution:class Arabic2Roman
'''
class Arabic2Roman:
trans = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
# 'I(a)X(b)V(c)I(d)'
trans_unit = {1:(0,0,0,1),2:... | """
filename:arabic2roman.py
chap:6
subject:6
conditions:translate Arabic numerals to Roman numerals
solution:class Arabic2Roman
"""
class Arabic2Roman:
trans = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
trans_unit = {1: (0, 0, 0, 1), 2: (0, 0, 0, 2), 3: (0, 0, 0,... |
# AARD: function: __main__
# AARD: #1:1 -> #1:2 :: defs: %1 / uses: [@1 5:4-5:10] { call }
# AARD: #1:2 -> #1:3, #1:4 :: defs: / uses: %1 [@1 5:4-5:10]
if test():
# AARD: #1:3 -> #1:4 :: defs: %2 / uses: [@1 7:5-7:12]
foo = 3
# AARD: #1:4 -> :: defs: %3 / uses: [@1 10:1-10:8] { call }
print()
... | if test():
foo = 3
print() |
class Node:
def __init__(self, value):
self._value = value
self._parent = None
self._children = []
@property
def value(self):
return self._value
@property
def children(self):
return self._children
@property
def parent(self):
return self._par... | class Node:
def __init__(self, value):
self._value = value
self._parent = None
self._children = []
@property
def value(self):
return self._value
@property
def children(self):
return self._children
@property
def parent(self):
return self._pa... |
class Env:
def __init__(self):
self.played = False
def getTime(self):
pass
def playWavFile(self, file):
pass
def wavWasPlayed(self):
self.played = True
def resetWav(self):
self.played = False
| class Env:
def __init__(self):
self.played = False
def get_time(self):
pass
def play_wav_file(self, file):
pass
def wav_was_played(self):
self.played = True
def reset_wav(self):
self.played = False |
algorithm_parameter = {
'type': 'object',
'required': ['name', 'value'],
'properties': {
'name': {
'description': 'Name of algorithm parameter',
'type': 'string',
},
'value': {
'description': 'Value of algorithm parameter',
'oneOf': [
... | algorithm_parameter = {'type': 'object', 'required': ['name', 'value'], 'properties': {'name': {'description': 'Name of algorithm parameter', 'type': 'string'}, 'value': {'description': 'Value of algorithm parameter', 'oneOf': [{'type': 'number'}, {'type': 'string'}]}}}
algorithm_launch_spec = {'type': 'object', 'requi... |
class solve_day(object):
with open('inputs/day02.txt', 'r') as f:
data = f.readlines()
def part1(self):
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
code = []
## locations
# 1 - grid[0][0]
# 2 - grid[0][1]
# 3 - grid[0][2]
... | class Solve_Day(object):
with open('inputs/day02.txt', 'r') as f:
data = f.readlines()
def part1(self):
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
code = []
position = [0, 0]
for (i, d) in enumerate(self.data):
d = d.strip()
if i == 0:
... |
class IntegerStack(list):
def __init__(self):
stack = [] * 128
self.extend(stack)
def depth(self):
return len(self)
def tos(self):
return self[-1]
def push(self, v):
self.append(v)
def dup(self):
self.append(self[-1])
def drop(self):
s... | class Integerstack(list):
def __init__(self):
stack = [] * 128
self.extend(stack)
def depth(self):
return len(self)
def tos(self):
return self[-1]
def push(self, v):
self.append(v)
def dup(self):
self.append(self[-1])
def drop(self):
... |
digit_mapping = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f']
}
def get_letter_strings(number_string):
if not number_string:
return
if len(number_string) == 1:
return digit_mapping[number_string[0]]
possible_strings = list()
current_letters = digit_mapping[number_string[0]]
... | digit_mapping = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f']}
def get_letter_strings(number_string):
if not number_string:
return
if len(number_string) == 1:
return digit_mapping[number_string[0]]
possible_strings = list()
current_letters = digit_mapping[number_string[0]]
strings_of_... |
class Solution:
def minTaps(self, n: int, A: List[int]) -> int:
dp = [math.inf] * (n + 1)
for i in range(0, n + 1):
left = max(0, i - A[i])
use = (dp[left] + 1) if i - A[i] > 0 else 1
dp[i] = min(dp[i], use)
for j in range(i, min(i + A[i] + 1, n + 1)):... | class Solution:
def min_taps(self, n: int, A: List[int]) -> int:
dp = [math.inf] * (n + 1)
for i in range(0, n + 1):
left = max(0, i - A[i])
use = dp[left] + 1 if i - A[i] > 0 else 1
dp[i] = min(dp[i], use)
for j in range(i, min(i + A[i] + 1, n + 1)):... |
def fibo_recur(n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
return fibo_recur(n-1) + fibo_recur(n-2)
def fibo_dp(n, dp=dict()):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
if n in dp:
return dp[n]
dp[n... | def fibo_recur(n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
return fibo_recur(n - 1) + fibo_recur(n - 2)
def fibo_dp(n, dp=dict()):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
if n in dp:
return dp[n]
dp[n] = fibo_... |
class Square:
def __init__(self, sideLength = 0):
self.sideLength = sideLength
def area_square(self):
return self.sideLength ** 2
def perimeter_square(self):
return self.sideLength * 4
class Triangle:
def __init__(self, base : float, height : float):
self.base = b... | class Square:
def __init__(self, sideLength=0):
self.sideLength = sideLength
def area_square(self):
return self.sideLength ** 2
def perimeter_square(self):
return self.sideLength * 4
class Triangle:
def __init__(self, base: float, height: float):
self.base = base
... |
#! /usr/bin/python3
def parse():
prev_data_S = "-1,-1,-1,-1,-1"
prev_none_vga_data = "0"
while(1):
f_read = open("temp.txt","r")
data = f_read.read()
f_read.close()
data_S = data.split('S')
if(len(data_S)>2):
none_vga_data = data_S[2].split('T')
... | def parse():
prev_data_s = '-1,-1,-1,-1,-1'
prev_none_vga_data = '0'
while 1:
f_read = open('temp.txt', 'r')
data = f_read.read()
f_read.close()
data_s = data.split('S')
if len(data_S) > 2:
none_vga_data = data_S[2].split('T')
while len(data_S)... |
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class DictList(dict):
def __setitem__(self, key, value):
try:
... | class Color:
purple = '\x1b[95m'
cyan = '\x1b[96m'
darkcyan = '\x1b[36m'
blue = '\x1b[94m'
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
bold = '\x1b[1m'
underline = '\x1b[4m'
end = '\x1b[0m'
class Dictlist(dict):
def __setitem__(self, key, value):
try:
... |
### Do something - what - print
### Data source? - what data is being printed?
### Output device? - where the data is being printed?
### I think these are rather good questions, it would be cool
### to specify these in the code
print("Hello, World!\nI'm Ante")
| print("Hello, World!\nI'm Ante") |
input_size = 512
model = dict(
type='SingleStageDetector',
backbone=dict(
type='SSDVGG',
depth=16,
with_last_pool=False,
ceil_mode=True,
out_indices=(3, 4),
out_feature_indices=(22, 34),
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab:... | input_size = 512
model = dict(type='SingleStageDetector', backbone=dict(type='SSDVGG', depth=16, with_last_pool=False, ceil_mode=True, out_indices=(3, 4), out_feature_indices=(22, 34), init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://vgg16_caffe')), neck=dict(type='SSDNeck', in_channels=(512, 1024), out_channe... |
'''
LEADERS OF AN ARRAY
The task is to find all leaders in an array, where
a leader is an array element which is greater than all the elements
on its right side
'''
print("Enter the size of array : ")
num = int(input())
a = []
print("Enter array elements")
for i in range(0, num):
a.append(int(... | """
LEADERS OF AN ARRAY
The task is to find all leaders in an array, where
a leader is an array element which is greater than all the elements
on its right side
"""
print('Enter the size of array : ')
num = int(input())
a = []
print('Enter array elements')
for i in range(0, num):
a.append(int(input... |
# |---------------------|
# <module> | |
# |---------------------|
#
# |---------------------|
# print_n | s--->'Hello' n--->2 | |
# |---------------------|
#
# |---------------------|
# print_n | s--->'Hello' n--->1 ... | def print_n(s, n):
if n <= 0:
return
print(s)
print_n(s, n - 1)
print_n('Hello', 2) |
num_waves = 3
num_eqn = 3
# Conserved quantities
pressure = 0
x_velocity = 1
y_velocity = 2
| num_waves = 3
num_eqn = 3
pressure = 0
x_velocity = 1
y_velocity = 2 |
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
... | class Rangequery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
(i, n) = (1, len(_data[0]))
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= ... |
# Source and destination file names.
test_source = "compact_lists.txt"
test_destination = "compact_lists.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html"
# Settings
# local copy of stylesheets:
# (Test runs in ``docutils/test/``, we need relative p... | test_source = 'compact_lists.txt'
test_destination = 'compact_lists.html'
reader_name = 'standalone'
parser_name = 'rst'
writer_name = 'html'
settings_overrides['stylesheet_dirs'] = ('.', 'functional/input/data') |
#!/usr/bin/env python
dic = {'nome': 'Shirley Manson', 'banda': 'Garbage'}
print(dic['nome'])
del dic
dic = {'Yes': ['Close To The Edge', 'Fragile'],
'Genesis': ['Foxtrot', 'The Nursery Crime'],
'ELP': ['Brain Salad Surgery']}
print(dic['Yes'])
| dic = {'nome': 'Shirley Manson', 'banda': 'Garbage'}
print(dic['nome'])
del dic
dic = {'Yes': ['Close To The Edge', 'Fragile'], 'Genesis': ['Foxtrot', 'The Nursery Crime'], 'ELP': ['Brain Salad Surgery']}
print(dic['Yes']) |
class DictHelper:
@staticmethod
def split_path(path):
if isinstance(path, str):
path = path.split(" ")
elif isinstance(path, int):
path = str(path)
filename, *rpath = path
return (filename, rpath)
@staticmethod
def get_dict_by_path(dict_var, pa... | class Dicthelper:
@staticmethod
def split_path(path):
if isinstance(path, str):
path = path.split(' ')
elif isinstance(path, int):
path = str(path)
(filename, *rpath) = path
return (filename, rpath)
@staticmethod
def get_dict_by_path(dict_var, pa... |
'''
A program for warshall algorithm.It is a shortest path algorithm which is used to find the
distance from source node,which is the first node,to all the other nodes.
If there is no direct distance between two vertices then it is considered as -1
'''
def warshall(g,ver):
dist = list(map(lambda i: list(map(... | """
A program for warshall algorithm.It is a shortest path algorithm which is used to find the
distance from source node,which is the first node,to all the other nodes.
If there is no direct distance between two vertices then it is considered as -1
"""
def warshall(g, ver):
dist = list(map(lambda i: list(map(lamb... |
#-------------------------------------------------------------------------------
# importation
#-------------------------------------------------------------------------------
# Main class Ml_tools
class ml_tools:
def __init__(self):
pass | class Ml_Tools:
def __init__(self):
pass |
text = " I love apples very much "
# The number of characters in the text
text_size = len(text)
# Initialize a pointer to the position of the first character of 'text'
pos = 0
# This is a flag to indicate whether the character we are comparing
# to is a white space or not
is_space = text[0].isspace()
# Start toke... | text = ' I love apples very much '
text_size = len(text)
pos = 0
is_space = text[0].isspace()
for (i, char) in enumerate(text):
is_current_space = char.isspace()
if is_current_space != is_space:
print(text[pos:i])
if is_current_space:
pos = i + 1
else:
pos = i
... |
# PyJS does not support weak references,
# so this module provides stubs with usual references
typecls = __builtins__.TypeClass
class ReferenceType(typecls):
pass
class CallableProxyType(typecls):
pass
class ProxyType(typecls):
pass
ProxyTypes = (ProxyType, CallableProxyType)
WeakValueDictionary = dict
... | typecls = __builtins__.TypeClass
class Referencetype(typecls):
pass
class Callableproxytype(typecls):
pass
class Proxytype(typecls):
pass
proxy_types = (ProxyType, CallableProxyType)
weak_value_dictionary = dict
weak_key_dictionary = dict |
#
# PySNMP MIB module TCP-ESTATS-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/TCP-ESTATS-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:31:06 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)
#
... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class Client:
def __init__(self, client_id):
self.client_id = client_id
self.available = 0
self.held = 0
self.total = 0
self.locked = False
def get_client_id(self):
return self.client_id
def get_available(self):
return self.available
def lock... | class Client:
def __init__(self, client_id):
self.client_id = client_id
self.available = 0
self.held = 0
self.total = 0
self.locked = False
def get_client_id(self):
return self.client_id
def get_available(self):
return self.available
def lock_c... |
description = 'W&T Box * 0-10V * Nr. 2'
includes = []
_wutbox = 'wut-0-10-02'
_wutbox_dev = _wutbox.replace('-','_')
devices = {
_wutbox_dev +'_1': device('nicos_mlz.sans1.devices.wut.WutValue',
hostname = _wutbox + '.sans1.frm2',
port = '1',
description = 'input 1 voltage',
fmtstr... | description = 'W&T Box * 0-10V * Nr. 2'
includes = []
_wutbox = 'wut-0-10-02'
_wutbox_dev = _wutbox.replace('-', '_')
devices = {_wutbox_dev + '_1': device('nicos_mlz.sans1.devices.wut.WutValue', hostname=_wutbox + '.sans1.frm2', port='1', description='input 1 voltage', fmtstr='%.3F', lowlevel=False, loglevel='info', p... |
#!/usr/bin/env python
NAME = 'FortiWeb (Fortinet)'
def is_waf(self):
if self.matchcookie(r'^FORTIWAFSID='):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, responsepage = r
# Found a site running a tweaked version of Fortiweb... | name = 'FortiWeb (Fortinet)'
def is_waf(self):
if self.matchcookie('^FORTIWAFSID='):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, responsepage) = r
if all((m in responsepage for m in (b'fgd_icon', b'Web Page Blocked', b'UR... |
def checkResult(netSales, eps):
try:
crfo = float(netSales[0])
except:
crfo = 0.0
try:
prfo = float(netSales[1])
except:
prfo = 0.0
try:
lrfo = float(netSales[2])
except:
lrfo = 0.0
try:
cqe = float(eps[0])
except:
cqe = 0.0... | def check_result(netSales, eps):
try:
crfo = float(netSales[0])
except:
crfo = 0.0
try:
prfo = float(netSales[1])
except:
prfo = 0.0
try:
lrfo = float(netSales[2])
except:
lrfo = 0.0
try:
cqe = float(eps[0])
except:
cqe = 0.... |
'''
A centered decagonal number is a centered figurate number that represents
a decagon with a dot in the center and all other dots surrounding the center
dot in successive decagonal layers.
The centered decagonal number for n is given by the formula
5n^2+5n+1
'''
def centeredDecagonal (num):... | """
A centered decagonal number is a centered figurate number that represents
a decagon with a dot in the center and all other dots surrounding the center
dot in successive decagonal layers.
The centered decagonal number for n is given by the formula
5n^2+5n+1
"""
def centered_decagonal(num):... |
# class Solution:
# def convert(self, s: str, numRows: int) -> str:
# lst = []
# N = len(s)
# print (N//(2*numRows-2))
# [lst.append([s[i]]) for i in range(numRows)]
# step = 2*numRows-2
# for k in range(N//step):
# if k:
# [lst[i].append(s... | class Solution:
def convert(self, s: str, numRows: int) -> str:
(lst, idx) = ([], 0)
(p_down, p_up) = (0, numRows - 2)
n = len(s)
if numRows == 1 or N <= 2 or numRows >= N:
return s
[lst.append(s[i]) for i in range(numRows)]
idx += numRows
while i... |
NO_RESET = 0b0
BATCH_RESET = 0b1
EPOCH_RESET = 0b10
NONE_METER = 'none'
SCALAR_METER = 'scalar'
TEXT_METER = 'text'
IMAGE_METER = 'image'
HIST_METER = 'hist'
GRAPH_METER = 'graph'
AUDIO_METER = 'audio'
| no_reset = 0
batch_reset = 1
epoch_reset = 2
none_meter = 'none'
scalar_meter = 'scalar'
text_meter = 'text'
image_meter = 'image'
hist_meter = 'hist'
graph_meter = 'graph'
audio_meter = 'audio' |
lower=100
upper=999
for num in range(lower,upper+1):
order=len(str(num))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**order
temp//=10
if num==sum:
print(num)
| lower = 100
upper = 999
for num in range(lower, upper + 1):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num) |
def is_interesting(number, awesome_phrases):
if number<98: return 0
elif check(number, awesome_phrases) and number>=100: return 2
for i in range(number+1, number+3):
if i>=100 and check(i, awesome_phrases):
return 1
return 0
def check(n, awesome_phrases):
return equal(n) or all_z... | def is_interesting(number, awesome_phrases):
if number < 98:
return 0
elif check(number, awesome_phrases) and number >= 100:
return 2
for i in range(number + 1, number + 3):
if i >= 100 and check(i, awesome_phrases):
return 1
return 0
def check(n, awesome_phrases):
... |
with open('input', 'r') as expense_report:
expenses = [ int(a.strip()) for a in expense_report.readlines() ]
expenses = sorted(expenses)
def part1():
for a in expenses:
for b in expenses:
if a + b == 2020:
print(f"{a} + {b} = 2020, {a} * {b} = {a * b}")
... | with open('input', 'r') as expense_report:
expenses = [int(a.strip()) for a in expense_report.readlines()]
expenses = sorted(expenses)
def part1():
for a in expenses:
for b in expenses:
if a + b == 2020:
print(f'{a} + {b} = 2020, {a} * {b} = {a * b}')
ret... |
##
# \file exceptions.py
# \brief User-specific exceptions
#
# \author Michael Ebner (michael.ebner.14@ucl.ac.uk)
# \date June 2017
#
##
# Error handling in case the directory does not contain valid nifti file
# \date 2017-06-14 11:11:37+0100
#
class InputFilesNotValid(Exception):
##
# \... | class Inputfilesnotvalid(Exception):
def __init__(self, directory):
self.directory = directory
def __str__(self):
error = "Folder '%s' does not contain valid nifti files." % self.directory
return error
class Objectnotcreated(Exception):
def __init__(self, function_call):
... |
# Testing
with open("stuck_in_a_rut.in") as file1:
N = int(file1.readline().strip())
cows = [[value if index == 0 else int(value) for index, value in enumerate(i.strip().split())] for i in file1.readlines()]
# Actual
# N = int(input())
# cow_numbers = [input() for _ in range(N)]
# cows = [[value if index == ... | with open('stuck_in_a_rut.in') as file1:
n = int(file1.readline().strip())
cows = [[value if index == 0 else int(value) for (index, value) in enumerate(i.strip().split())] for i in file1.readlines()]
future_path = {}
(max_x, max_y) = (max(cows, key=lambda x: x[1])[1], max(cows, key=lambda x: x[2])[2])
for i in ... |
# Time: O(max(h, k))
# Space: O(h)
# 230
# Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
#
# Note:
# You may assume k is always valid, 1 <= k <= BST's total elements.
#
# Follow up:
# What if the BST is modified (insert/delete operations) often and
# you need to find... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kth_smallest(self, root, k):
stack = [(root, False)]
while stack:
(cur, visited) = stack.pop()
if cur:
if visited:
... |
height = int(input("Height: "))
width = int(input("Width: "))
for i in range(height):
for j in range(width):
print("* ",end='')
print()
| height = int(input('Height: '))
width = int(input('Width: '))
for i in range(height):
for j in range(width):
print('* ', end='')
print() |
shader_assignment = []
for shadingEngine in renderPartition.inputs():
if not shadingEngine.members():
continue
if shadingEngine.name() == 'initialShadingGroup':
continue
nameSE = shadingEngine.name()
nameSH = shadingEngine.surfaceShader.inputs()[0].name()
shader_assignment.appe... | shader_assignment = []
for shading_engine in renderPartition.inputs():
if not shadingEngine.members():
continue
if shadingEngine.name() == 'initialShadingGroup':
continue
name_se = shadingEngine.name()
name_sh = shadingEngine.surfaceShader.inputs()[0].name()
shader_assignment.append(... |
# Python - 2.7.6
Test.assert_equals(calculate_tip(30, 'poor'), 2)
Test.assert_equals(calculate_tip(20, 'Excellent'), 4)
Test.assert_equals(calculate_tip(20, 'hi'), 'Rating not recognised')
Test.assert_equals(calculate_tip(107.65, 'GReat'), 17)
Test.assert_equals(calculate_tip(20, 'great!'), 'Rating not recognised')
| Test.assert_equals(calculate_tip(30, 'poor'), 2)
Test.assert_equals(calculate_tip(20, 'Excellent'), 4)
Test.assert_equals(calculate_tip(20, 'hi'), 'Rating not recognised')
Test.assert_equals(calculate_tip(107.65, 'GReat'), 17)
Test.assert_equals(calculate_tip(20, 'great!'), 'Rating not recognised') |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned abo... | {'name': 'Website Webkul Addons', 'summary': 'Manage Webkul Website Addons', 'category': 'Website', 'version': '2.0.1', 'author': 'Webkul Software Pvt. Ltd.', 'website': 'https://store.webkul.com/Odoo.html', 'description': 'Website Webkul Addons', 'live_test_url': 'http://odoodemo.webkul.com/?module=website_webkul_addo... |
#------------------------------------------------------------------------------
# simple_universe/room.py
# Copyright 2011 Joseph Schilz
# Licensed under Apache v2
#------------------------------------------------------------------------------
class SimpleRoom(object):
ID = [-1, -1]
exits = []
desc... | class Simpleroom(object):
id = [-1, -1]
exits = []
description = ''
def __init__(self, ID=[-1, -1], exits=False, description=False, contents=False):
self.ID = ID
self.exits = exits
self.description = description
self.THIS_WORLD = False
self.contents = []
... |
def example_bytes_slice():
word = b'the lazy brown dog jumped'
for i in range(10):
# Memoryview slicing is 10x faster than bytes slicing
if word[0:i] == 'the':
return True
def example_bytes_slice_as_arg(word: bytes):
for i in range(10):
# Memoryview slicing is 10x faster... | def example_bytes_slice():
word = b'the lazy brown dog jumped'
for i in range(10):
if word[0:i] == 'the':
return True
def example_bytes_slice_as_arg(word: bytes):
for i in range(10):
if word[0:i] == 'the':
return True |
prve_stiri = [2, 3, 5, 7]
def je_prastevilo(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return n > 1
def trunctable_z_desne(n):
for indeks in range(1, len(str(n))):
if not je_prastevilo(int(str(n)[0:indeks])):
return False
return n... | prve_stiri = [2, 3, 5, 7]
def je_prastevilo(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return n > 1
def trunctable_z_desne(n):
for indeks in range(1, len(str(n))):
if not je_prastevilo(int(str(n)[0:indeks])):
return False
return n... |
low=1
high=2
third=0
sum=0
temp=0
while(third<4000000):
third=low+high
if(third%2==0):
sum+=third
low=high
high=third
print(sum+2)
| low = 1
high = 2
third = 0
sum = 0
temp = 0
while third < 4000000:
third = low + high
if third % 2 == 0:
sum += third
low = high
high = third
print(sum + 2) |
#Skill: array iteration
#You are given an array of integers. Return the smallest positive integer that is not present in the array. The array may contain duplicate entries.
#For example, the input [3, 4, -1, 1] should return 2 because it is the smallest positive integer that doesn't exist in the array.
#Your solution... | class Solution:
def first_missing_positive(self, nums):
low = (1 << 31) - 1
high = 0
for i in nums:
if low > i and i > 0:
low = i
if high < i:
high = i
first_miss = low + 1
searchmiss = firstMiss
found = False
... |
class Solution:
def maxProfit(self, inventory: List[int], orders: int) -> int:
# [5, 5, 2]
inventory.sort(reverse=True)
inventory.append(0)
ans = 0
idx = 0
n = len(inventory)
while orders:
# find the first index such that inv[j] < inv[i]
... | class Solution:
def max_profit(self, inventory: List[int], orders: int) -> int:
inventory.sort(reverse=True)
inventory.append(0)
ans = 0
idx = 0
n = len(inventory)
while orders:
(lo, hi) = (idx + 1, n - 1)
while lo < hi:
mid = ... |
'''
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3... | """
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 ... |
def maven_dependencies(callback):
callback({"artifact": "antlr:antlr:2.7.6", "lang": "java", "sha1": "cf4f67dae5df4f9932ae7810f4548ef3e14dd35e", "repository": "https://repo.maven.apache.org/maven2/", "name": "antlr_antlr", "actual": "@antlr_antlr//jar", "bind": "jar/antlr/antlr"})
callback({"artifact": "aopalli... | def maven_dependencies(callback):
callback({'artifact': 'antlr:antlr:2.7.6', 'lang': 'java', 'sha1': 'cf4f67dae5df4f9932ae7810f4548ef3e14dd35e', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'antlr_antlr', 'actual': '@antlr_antlr//jar', 'bind': 'jar/antlr/antlr'})
callback({'artifact': 'aopalli... |
def solve(lines):
longest_intersec = []
for line in lines:
(r1, r2) = line.split("-")
(r1_start, r1_end) = map(int, r1.split(","))
(r2_start, r2_end) = map(int, r2.split(","))
current_longest_intersec = set(range(r1_start, r1_end + 1)) & set(range(r2_start, r2_end + 1))
i... | def solve(lines):
longest_intersec = []
for line in lines:
(r1, r2) = line.split('-')
(r1_start, r1_end) = map(int, r1.split(','))
(r2_start, r2_end) = map(int, r2.split(','))
current_longest_intersec = set(range(r1_start, r1_end + 1)) & set(range(r2_start, r2_end + 1))
i... |
def make_dist():
return default_python_distribution(
python_version="3.8"
)
def make_exe(dist):
policy = dist.make_python_packaging_policy()
policy.extension_module_filter = "all"
# policy.file_scanner_classify_files = True
policy.allow_files = True
policy.file_scanner_emit_files = ... | def make_dist():
return default_python_distribution(python_version='3.8')
def make_exe(dist):
policy = dist.make_python_packaging_policy()
policy.extension_module_filter = 'all'
policy.allow_files = True
policy.file_scanner_emit_files = True
policy.resources_location = 'in-memory'
python_co... |
def double(num):
return num * 2
# way 1
multiply = lambda x,y: x*y
print(multiply(5,10))
# way 2
print((lambda x,y: x+y)(6, 82))
numbers = [23, 73, 62, 3]
added = [ x*2 for x in numbers]
print(added)
added = [double(x) for x in numbers]
print(added)
added = [ (lambda x: x*2)(x) for x in numbers]
print(added)
... | def double(num):
return num * 2
multiply = lambda x, y: x * y
print(multiply(5, 10))
print((lambda x, y: x + y)(6, 82))
numbers = [23, 73, 62, 3]
added = [x * 2 for x in numbers]
print(added)
added = [double(x) for x in numbers]
print(added)
added = [(lambda x: x * 2)(x) for x in numbers]
print(added)
added = map(d... |
class AspectManager(object):
def __init__(self):
super(AspectManager, self).__init__()
def get_module_hooker(self, name):
return None
def load_aspects(self):
pass
| class Aspectmanager(object):
def __init__(self):
super(AspectManager, self).__init__()
def get_module_hooker(self, name):
return None
def load_aspects(self):
pass |
SECRET_KEY = 'example'
TIME_ZONE = 'Asia/Shanghai'
DEFAULT_XFILES_FACTOR = 0
URL_PREFIX = '/'
LOG_DIR = '/var/log/graphite'
GRAPHITE_ROOT = '/opt/graphite'
CONF_DIR = '/etc/graphite'
DASHBOARD_CONF = '/etc/graphite/dashboard.conf'
GRAPHTEMPLATES_CONF = '/etc/graphite/graphTemplates.conf'
# STORAGE_DIR = '/opt/graphite/... | secret_key = 'example'
time_zone = 'Asia/Shanghai'
default_xfiles_factor = 0
url_prefix = '/'
log_dir = '/var/log/graphite'
graphite_root = '/opt/graphite'
conf_dir = '/etc/graphite'
dashboard_conf = '/etc/graphite/dashboard.conf'
graphtemplates_conf = '/etc/graphite/graphTemplates.conf'
storage_finders = ('graphite.gr... |
n = int(input("Enter a number: "))
for x in range(1,16):
print(n,"x",x,"=",(n*x))
| n = int(input('Enter a number: '))
for x in range(1, 16):
print(n, 'x', x, '=', n * x) |
#
# PySNMP MIB module TIMETRA-LLDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-LLDP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:11:14 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, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
class kdtree:
def __init__(self, points, dimensions):
self.dimensions = dimensions
self.tree = self._build([(i, p) for i,p in enumerate(points)])
def closest(self, point):
return self._closest(self.tree, point)
def _build(self,points, depth=0):
n = len(point... | class Kdtree:
def __init__(self, points, dimensions):
self.dimensions = dimensions
self.tree = self._build([(i, p) for (i, p) in enumerate(points)])
def closest(self, point):
return self._closest(self.tree, point)
def _build(self, points, depth=0):
n = len(points)
... |
def A_type_annotation(integer: int, boolean: bool, string: str):
pass
def B_annotation_as_documentation(argument: 'One of the usages in PEP-3107'):
pass
def C_annotation_and_default(integer: int=42, list_: list=None):
pass
def D_annotated_kw_only_args(*, kwo: int, with_default: str='value'):
pass
... | def a_type_annotation(integer: int, boolean: bool, string: str):
pass
def b_annotation_as_documentation(argument: 'One of the usages in PEP-3107'):
pass
def c_annotation_and_default(integer: int=42, list_: list=None):
pass
def d_annotated_kw_only_args(*, kwo: int, with_default: str='value'):
pass
de... |
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ans = ""
prev = 0
for sp in spaces:
ans += s[prev:sp] + " "
prev = sp
return ans + s[prev:]
| class Solution:
def add_spaces(self, s: str, spaces: List[int]) -> str:
ans = ''
prev = 0
for sp in spaces:
ans += s[prev:sp] + ' '
prev = sp
return ans + s[prev:] |
print('Congratulations on running this script!!')
msg = 'hello world'
print(msg)
| print('Congratulations on running this script!!')
msg = 'hello world'
print(msg) |
def test_post_sub_category(app, client):
mock_request_data = {
"category_fk": "47314685-54c1-4863-9918-09f58b981eea",
"name": "teste",
"description": "testado testando"
}
response = client.post('/sub_categorys', json=mock_request_data)
assert response.status_code == 201
expec... | def test_post_sub_category(app, client):
mock_request_data = {'category_fk': '47314685-54c1-4863-9918-09f58b981eea', 'name': 'teste', 'description': 'testado testando'}
response = client.post('/sub_categorys', json=mock_request_data)
assert response.status_code == 201
expected = 'successfully registered... |
# %%
class WalletSwiss:
coversion_rates = {"usd" :1.10, "gpd": 0.81, "euro": 0.95, "yen": 123.84 }
#shows swiss conversion rates for each each currency starting at $1
def __init__(self,currency_amount):
self.currency_amount = currency_amount
self.currency_type = "franc"
def convert_currenc... | class Walletswiss:
coversion_rates = {'usd': 1.1, 'gpd': 0.81, 'euro': 0.95, 'yen': 123.84}
def __init__(self, currency_amount):
self.currency_amount = currency_amount
self.currency_type = 'franc'
def convert_currency(self, currency_type):
conversion_rate = WalletSwiss.coversion_ra... |
#
# from src/whrnd.c
#
# void init_rnd(int, int, int) to whrnd; .init
# double rnd(void) to whrnd; .__call__
#
class whrnd:
def __init__(self, x=1, y=1, z=1):
self.init(x, y, z)
def init(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __call__(self):
self.x = 171 * (self.x... | class Whrnd:
def __init__(self, x=1, y=1, z=1):
self.init(x, y, z)
def init(self, x, y, z):
(self.x, self.y, self.z) = (x, y, z)
def __call__(self):
self.x = 171 * (self.x % 177) - 2 * (self.x // 177)
self.y = 172 * (self.y % 176) - 35 * (self.y // 176)
self.z = 17... |
#
# PySNMP MIB module DNOS-DCBX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DNOS-DCBX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:51:23 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... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
description = 'system setup'
group = 'lowlevel'
display_order = 90
sysconfig = dict(
cache = 'localhost',
instrument = 'NEUTRA',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink', 'livesink', 'asciisink', 'shuttersink'],
notifiers = ['email'],
)
requires = ['shutters']
modules = [
'nic... | description = 'system setup'
group = 'lowlevel'
display_order = 90
sysconfig = dict(cache='localhost', instrument='NEUTRA', experiment='Exp', datasinks=['conssink', 'dmnsink', 'livesink', 'asciisink', 'shuttersink'], notifiers=['email'])
requires = ['shutters']
modules = ['nicos.commands.standard', 'nicos_sinq.commands... |
'''
Log in color from
https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
usage :
import log
log.info("Hello World")
log.err("System Error")
'''
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD ... | """
Log in color from
https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
usage :
import log
log.info("Hello World")
log.err("System Error")
"""
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold ... |
#!/usr/bin/python
#
# Provides __ROR4__, __ROR8__, __ROL4__ and __ROL8__ functions.
#
# Author: Satoshi Tanda
#
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2014 tandasat
#
# Permission is hereby granted, free of charge, to any person obtaini... | def _rol(val, bits, bit_size):
return val << bits % bit_size & 2 ** bit_size - 1 | (val & 2 ** bit_size - 1) >> bit_size - bits % bit_size
def _ror(val, bits, bit_size):
return (val & 2 ** bit_size - 1) >> bits % bit_size | val << bit_size - bits % bit_size & 2 ** bit_size - 1
__ror4__ = lambda val, bits: _ror... |
'''
PARTITION PROBLEM
The problem is to identify if a given set of n elements can be divided
into two separate subsets such that sum of elements of both the subsets
is equal.
'''
def check(a, total, ind):
if total == 0:
return True
if ind == -1 or total < 0:
return False
if a[ind] > total:... | """
PARTITION PROBLEM
The problem is to identify if a given set of n elements can be divided
into two separate subsets such that sum of elements of both the subsets
is equal.
"""
def check(a, total, ind):
if total == 0:
return True
if ind == -1 or total < 0:
return False
if a[ind] > total:... |
n = int(input())
arr = list(map(str, input().split()))[:n]
ans = ""
for i in range(len(arr)):
ans += chr(int(arr[i], 16))
print(ans) | n = int(input())
arr = list(map(str, input().split()))[:n]
ans = ''
for i in range(len(arr)):
ans += chr(int(arr[i], 16))
print(ans) |
# File: D (Python 2.4)
GAME_DURATION = 300
GAME_COUNTDOWN = 10
GAME_OFF = 0
GAME_ON = 1
COOP_MODE = 0
TEAM_MODE = 1
FREE_MODE = 2
SHIP_DEPOSIT = 0
AV_DEPOSIT = 1
AV_MAX_CARRY = 200
GameTypes = [
'Cooperative',
'Team vs. Team',
'Free For All']
TeamNames = [
'Red',
'Blue',
'Green',
'Orange',
... | game_duration = 300
game_countdown = 10
game_off = 0
game_on = 1
coop_mode = 0
team_mode = 1
free_mode = 2
ship_deposit = 0
av_deposit = 1
av_max_carry = 200
game_types = ['Cooperative', 'Team vs. Team', 'Free For All']
team_names = ['Red', 'Blue', 'Green', 'Orange', 'England', 'France', 'Iraq']
team_colors = [(0.588, ... |
#program to find the position of the second occurrence of a given string in another given string.
def find_string(txt, str1):
return txt.find(str1, txt.find(str1)+1)
print(find_string("The quick brown fox jumps over the lazy dog", "the"))
print(find_string("the quick brown fox jumps over the lazy dog", "the")) | def find_string(txt, str1):
return txt.find(str1, txt.find(str1) + 1)
print(find_string('The quick brown fox jumps over the lazy dog', 'the'))
print(find_string('the quick brown fox jumps over the lazy dog', 'the')) |
lines = []
header = "| "
for multiplikator in range(1,11):
line = "|" + f"{multiplikator}".rjust(3)
header += "|" + f"{multiplikator}".rjust(3)
for multiplikand in range(1,11):
line += "|" + f"{multiplikator * multiplikand}".rjust(3)
lines.append("|---" + "+---"*10 + "|")
lines.append(lin... | lines = []
header = '| '
for multiplikator in range(1, 11):
line = '|' + f'{multiplikator}'.rjust(3)
header += '|' + f'{multiplikator}'.rjust(3)
for multiplikand in range(1, 11):
line += '|' + f'{multiplikator * multiplikand}'.rjust(3)
lines.append('|---' + '+---' * 10 + '|')
lines.append(... |
def foo(a, b):
return a + b
print("%d" % 10, end='')
| def foo(a, b):
return a + b
print('%d' % 10, end='') |
def test_training():
pass
| def test_training():
pass |
files = "newsequence.txt"
write = "compress.txt"
reverse = "reversed.txt"
seq = dict()
global key_max
#Stores the sequence in a dictionary
def store_seq(key, value):
if key not in seq:
seq.update({key:value})
#breaks each line down into sequences and counts the number of occurence of each sequence
def c... | files = 'newsequence.txt'
write = 'compress.txt'
reverse = 'reversed.txt'
seq = dict()
global key_max
def store_seq(key, value):
if key not in seq:
seq.update({key: value})
def check_exists(data):
data = data.strip()
size = len(data)
start = 0
endpoint = size - 7
dna = open(files, 'r')... |
man = 1
wives = man * 7
madai = wives * 7
cats = madai * 7
kitties = cats * 7
total = man + wives + madai + cats + kitties
print(total)
| man = 1
wives = man * 7
madai = wives * 7
cats = madai * 7
kitties = cats * 7
total = man + wives + madai + cats + kitties
print(total) |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-gwascatalog'
ES_DOC_TYPE = 'variant'
API_PREFIX = 'gwascatalog'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-gwascatalog'
es_doc_type = 'variant'
api_prefix = 'gwascatalog'
api_version = '' |
def sumall(upto):
sumupto = 0
for i in range(1, upto + 1):
sumupto = sumupto + i
return sumupto
print("The sum of the values from 1 to 50 inclusive is: ", sumall(50))
print("The sum of the values from 1 to 5 inclusive is: ", sumall(5))
print("The sum of the values from 1 to 10 inclusive is: ", s... | def sumall(upto):
sumupto = 0
for i in range(1, upto + 1):
sumupto = sumupto + i
return sumupto
print('The sum of the values from 1 to 50 inclusive is: ', sumall(50))
print('The sum of the values from 1 to 5 inclusive is: ', sumall(5))
print('The sum of the values from 1 to 10 inclusive is: ', sumal... |
class BatchClassifier:
# Implement methods of this class to use it in main.py
def train(self, filenames, image_classes):
'''
Train the classifier.
:param filenames: the list of filenames to be used for training
:type filenames: [str]
:param image_classes: a mapping of... | class Batchclassifier:
def train(self, filenames, image_classes):
"""
Train the classifier.
:param filenames: the list of filenames to be used for training
:type filenames: [str]
:param image_classes: a mapping of filename to class
:type image_classes: {str: int}
... |
carros = ["audi", "bmw", "ferrari","honda"]
for carro in carros:
if carro == "bmw":
print(carro.upper())
else:
print(carro.title()) | carros = ['audi', 'bmw', 'ferrari', 'honda']
for carro in carros:
if carro == 'bmw':
print(carro.upper())
else:
print(carro.title()) |
setup(
name="earthinversion",
version="1.0.0",
description="Go to earthinversion blog",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/earthinversion/",
author="Utpal Kumar",
author_email="office@earthinversion.com",
license="MIT",
... | setup(name='earthinversion', version='1.0.0', description='Go to earthinversion blog', long_description=README, long_description_content_type='text/markdown', url='https://github.com/earthinversion/', author='Utpal Kumar', author_email='office@earthinversion.com', license='MIT', classifiers=['License :: OSI Approved ::... |
API_LOGIN = "/users/sign_in"
API_DEVICE_RELATIONS = "/device_relations"
API_SYSTEMS = "/systems"
API_ZONES = "/zones"
API_EVENTS = "/events"
# 2020-04-18: extracted from https://airzonecloud.com/assets/application-506494af86e686bf472b872d02048b42.js
MODES_CONVERTER = {
"0": {"name": "stop", "description": "Stop"}... | api_login = '/users/sign_in'
api_device_relations = '/device_relations'
api_systems = '/systems'
api_zones = '/zones'
api_events = '/events'
modes_converter = {'0': {'name': 'stop', 'description': 'Stop'}, '1': {'name': 'cool-air', 'description': 'Air cooling'}, '2': {'name': 'heat-radiant', 'description': 'Radiant hea... |
'''
The MADLIBS QUIZ
Use string concatenation (putting strings together)
Ex: I ama traveling to ____ using ___ and its carrying ____ passegers for ____ kilometers
Thank you for watching ________ channel please ________
'''
youtube_channel = ""
print("thank you for watching " + youtube_channel + "Channel ")
prin... | """
The MADLIBS QUIZ
Use string concatenation (putting strings together)
Ex: I ama traveling to ____ using ___ and its carrying ____ passegers for ____ kilometers
Thank you for watching ________ channel please ________
"""
youtube_channel = ''
print('thank you for watching ' + youtube_channel + 'Channel ')
print(... |
# PEMDAS is followed for calculations.
# Exponentiation
print("2^2 = " + str(2 ** 2))
# Division always returns a float
print ("1 / 2 = " + str(1 / 2))
# For integer division, use double forward-slashes
print ("1 // 2 = " + str(1 // 2))
# Modulo is like division except it returns the remainder
print ("10 % 3 = " + ... | print('2^2 = ' + str(2 ** 2))
print('1 / 2 = ' + str(1 / 2))
print('1 // 2 = ' + str(1 // 2))
print('10 % 3 = ' + str(10 % 3)) |
class Solution:
def fib(self, n: int) -> int:
prev, cur = 0, 1
if n == 0:
return prev
if n == 1:
return cur
for i in range(n):
prev, cur = cur, prev + cur
return prev
| class Solution:
def fib(self, n: int) -> int:
(prev, cur) = (0, 1)
if n == 0:
return prev
if n == 1:
return cur
for i in range(n):
(prev, cur) = (cur, prev + cur)
return prev |
def test_countries_and_timezones(app_adm):
app_adm.home_page.open_countries()
country_page = app_adm.country_page
countries_list = country_page.get_countries()
sorted_countries = sorted(countries_list)
for country in range(len(countries_list)):
assert countries_list[country] == sorted_countr... | def test_countries_and_timezones(app_adm):
app_adm.home_page.open_countries()
country_page = app_adm.country_page
countries_list = country_page.get_countries()
sorted_countries = sorted(countries_list)
for country in range(len(countries_list)):
assert countries_list[country] == sorted_countr... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.node_count = 0
def __str__(self):
curr = self.head
temp = []
while curr is not None:
temp.append(str(curr.... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
self.node_count = 0
def __str__(self):
curr = self.head
temp = []
while curr is not None:
temp.append(str(cur... |
class HowLongToBeatEntry:
def __init__(self,detailId,gameName,description,playableOn,imageUrl,timeLabels,gameplayMain,gameplayMainExtra,gameplayCompletionist):
self.detailId = detailId
self.gameName = gameName
self.description = description
self.playableOn = playableOn
self.i... | class Howlongtobeatentry:
def __init__(self, detailId, gameName, description, playableOn, imageUrl, timeLabels, gameplayMain, gameplayMainExtra, gameplayCompletionist):
self.detailId = detailId
self.gameName = gameName
self.description = description
self.playableOn = playableOn
... |
class MyDeque:
def __init__(self, max_size):
self.max_size = max_size
self.items = [None] * self.max_size
self.size = 0
self.head = 0
self.tail = 0
def push_back(self, value):
if self.size == self.max_size:
raise IndexError('error')
self.item... | class Mydeque:
def __init__(self, max_size):
self.max_size = max_size
self.items = [None] * self.max_size
self.size = 0
self.head = 0
self.tail = 0
def push_back(self, value):
if self.size == self.max_size:
raise index_error('error')
self.ite... |
def findadjacent(y,x):
global horizontal
global vertical
global map
countlocal=0
for richtingy in range(-1,2):
for richtingx in range(-1,2):
if richtingx!=0 or richtingy!=0:
offsetcounter=0
found=0
while found==0:
... | def findadjacent(y, x):
global horizontal
global vertical
global map
countlocal = 0
for richtingy in range(-1, 2):
for richtingx in range(-1, 2):
if richtingx != 0 or richtingy != 0:
offsetcounter = 0
found = 0
while found == 0:
... |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
ans=[]
st=set()
for i in range(0,len(nums)-2):
for j in range(i+1,len(nums)-2):
l=j+1
r=len(nums)-1
while(l<r):
... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
ans = []
st = set()
for i in range(0, len(nums) - 2):
for j in range(i + 1, len(nums) - 2):
l = j + 1
r = len(nums) - 1
while ... |
n = int(input("Please enter a positive integer : "))
print(n)
while n != 1:
n = n // 2 if n % 2 == 0 else 3*n + 1
print(n)
| n = int(input('Please enter a positive integer : '))
print(n)
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
print(n) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.