content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def sum_multidimensional_list_v1(lst):
sum_nums = 0
for row in range(len(lst)):
for col in range(len(lst[row])):
sum_nums += lst[row][col]
return sum_nums
def sum_multidimensional_list_v2(lst):
sum_nums = 0
for row in lst:
for col in row:
sum_nums += col
... | def sum_multidimensional_list_v1(lst):
sum_nums = 0
for row in range(len(lst)):
for col in range(len(lst[row])):
sum_nums += lst[row][col]
return sum_nums
def sum_multidimensional_list_v2(lst):
sum_nums = 0
for row in lst:
for col in row:
sum_nums += col
... |
__version_info__ = ('3', '5', '1')
__version__ = '.'.join(__version_info__)
class TwilioException(Exception):
pass
class TwilioRestException(TwilioException):
def __init__(self, status, uri, msg="", code=None):
self.uri = uri
self.status = status
self.msg = msg
self.code = c... | __version_info__ = ('3', '5', '1')
__version__ = '.'.join(__version_info__)
class Twilioexception(Exception):
pass
class Twiliorestexception(TwilioException):
def __init__(self, status, uri, msg='', code=None):
self.uri = uri
self.status = status
self.msg = msg
self.code = cod... |
"""
URL: https://codeforces.com/problemset/problem/112/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
s1 = input().lower()
s2 = input().lower()
if s1 == s2:
print(0)
elif s1 < s2:
print(-1)
else:
print(1)
| """
URL: https://codeforces.com/problemset/problem/112/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
s1 = input().lower()
s2 = input().lower()
if s1 == s2:
print(0)
elif s1 < s2:
print(-1)
else:
print(1) |
###exercicio 50
s = 0
for c in range (0, 6):
n = int(input('Digite um numero: '))
if n%2 == 0:
s += n
print ('{}'.format(s))
print ('Fim!!!') | s = 0
for c in range(0, 6):
n = int(input('Digite um numero: '))
if n % 2 == 0:
s += n
print('{}'.format(s))
print('Fim!!!') |
total = 0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
| total = 0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total) |
#Using the range function we create a list of numbers from 0 to 99 https://docs.python.org/2/library/functions.html#range
#Each number in the list is FizzBuzz tested
#If the number is a multiple of 3 and a multiple of 5 - print "FizzBuzz"
#If the number is only a multiple of 3 - print "Fizz"
#If the number is onl... | for i in range(100):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i) |
class Foo:
[mix_Case, var2] = range(2)
def bar():
'''
>>> class Foo():
... mix_Case = 0
'''
pass
| class Foo:
[mix__case, var2] = range(2)
def bar():
"""
>>> class Foo():
... mix_Case = 0
"""
pass |
""" TEMPORARY FIX """
def pause(*args):
print("TRYING TO PAUSE")
def stop(*args):
print("TRYING TO STOP") | """ TEMPORARY FIX """
def pause(*args):
print('TRYING TO PAUSE')
def stop(*args):
print('TRYING TO STOP') |
def print_to_file(file, cases):
print(len(cases), file=file)
for arr in cases:
print(len(arr), file=file)
print(*arr, file=file)
| def print_to_file(file, cases):
print(len(cases), file=file)
for arr in cases:
print(len(arr), file=file)
print(*arr, file=file) |
FEATURES = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3141965, 47.6598870],
[-122.3132940, 47.6598762],
],
... | features = {'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'geometry': {'type': 'LineString', 'coordinates': [[-122.3141965, 47.659887], [-122.313294, 47.6598762]]}, 'properties': {}}, {'type': 'Feature', 'geometry': {'type': 'LineString', 'coordinates': [[-122.3144401, 47.6598872], [-122.3141965, 47.659... |
#
# Nidan
#
# (C) 2017 Michele <o-zone@zerozone.it> Pinassi
class Config: pass
| class Config:
pass |
class CyclicDependencyError(ValueError):
pass
def topological_sort_as_sets(dependency_graph):
"""
Variation of Kahn's algorithm (1962) that returns sets.
Take a dependency graph as a dictionary of node => dependencies.
Yield sets of items in topological order, where the first set conta... | class Cyclicdependencyerror(ValueError):
pass
def topological_sort_as_sets(dependency_graph):
"""
Variation of Kahn's algorithm (1962) that returns sets.
Take a dependency graph as a dictionary of node => dependencies.
Yield sets of items in topological order, where the first set contains
all... |
# Given a binary matrix A, we want to flip the image horizontally, then invert
# it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image means that each 0 is replaced by ... | class Solution:
def flip_and_invert_image(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return [[1 - v for v in row[::-1]] for row in A] |
'''
This problem was asked by Google.
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact ... | """
This problem was asked by Google.
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact ... |
def lazyproperty(fn):
attr_name = '__' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
| def lazyproperty(fn):
attr_name = '__' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop |
stud = {
'Madhan':24,
'Raj':30,
'Narayanan':29
}
for s1 in stud.keys():
print(s1)
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key,value in phone_numbers.items():
print("{} has phone number {}".format(key,value))
names = {
'Girija':53,
'Subramania... | stud = {'Madhan': 24, 'Raj': 30, 'Narayanan': 29}
for s1 in stud.keys():
print(s1)
phone_numbers = {'John Smith': '+37682929928', 'Marry Simpons': '+423998200919'}
for (key, value) in phone_numbers.items():
print('{} has phone number {}'.format(key, value))
names = {'Girija': 53, 'Subramanian': 62, 'Narayanan':... |
"""load gtest third party"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repo():
http_archive(
name = "com_google_googletest",
sha256 = "353571c2440176ded91c2de6d6cd88ddd41401d14692ec1f99e35d013feda55a",
urls = ["https://github.com/google/googletest/archive/refs... | """load gtest third party"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def repo():
http_archive(name='com_google_googletest', sha256='353571c2440176ded91c2de6d6cd88ddd41401d14692ec1f99e35d013feda55a', urls=['https://github.com/google/googletest/archive/refs/tags/release-1.11.0.zip'], str... |
# -*- coding: utf-8 -*-
latest_posts = db(Posts).select(orderby=~Posts.created_on, limitby=(0,5))
most_liked = db(Posts).select(orderby=~Posts.likes, limitby=(0,5))
all_categories = db(Categories).select(limitby=(0,5)) | latest_posts = db(Posts).select(orderby=~Posts.created_on, limitby=(0, 5))
most_liked = db(Posts).select(orderby=~Posts.likes, limitby=(0, 5))
all_categories = db(Categories).select(limitby=(0, 5)) |
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[2])
spam2 = [['fish', 'shark'], 'bat', 'rat', 'elephant']
print(spam2[0])
print(spam2[0][1])
spam[2:4] = ['CAT', 'MOOSE', 'BEAR']
print(spam)
del spam[2]
print(spam)
print('MOOSE' in spam)
# Iterate over lists by item or index
for item in spam:
print(item)... | spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[2])
spam2 = [['fish', 'shark'], 'bat', 'rat', 'elephant']
print(spam2[0])
print(spam2[0][1])
spam[2:4] = ['CAT', 'MOOSE', 'BEAR']
print(spam)
del spam[2]
print(spam)
print('MOOSE' in spam)
for item in spam:
print(item)
for i in range(0, len(spam)):
print(spam[... |
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preord... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarytree:
def __init__(self, root):
self.root = node(root)
def print_tree(self, traversal_type):
if traversal_type == 'preorder':
return self.preorder_... |
def pattern(n):
if n==0:
return ""
res=[]
for i in range(n-1):
res.append(" "*(n-1)+str((i+1)%10))
temp="".join(str(i%10) for i in range(1, n))
res.append(temp+str(n%10)+temp[::-1])
for i in range(n-1, 0, -1):
res.append(" "*(n-1)+str(i%10))
return "\n".join(res)+"\n... | def pattern(n):
if n == 0:
return ''
res = []
for i in range(n - 1):
res.append(' ' * (n - 1) + str((i + 1) % 10))
temp = ''.join((str(i % 10) for i in range(1, n)))
res.append(temp + str(n % 10) + temp[::-1])
for i in range(n - 1, 0, -1):
res.append(' ' * (n - 1) + str(i... |
# ------------------------------
# 63. Unique Paths II
#
# Description:
# Follow up for "Unique Paths":
#
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
# For example,
# There is one obstacle i... | class Solution(object):
def unique_paths_with_obstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not obstacleGrid or not obstacleGrid[0] or obstacleGrid[0][0] == 1:
return 0
for m in range(len(obstacleGrid)):
... |
class Config:
gateId = 0
route = ""
port = "COM3"
def __init__(self, gateId, route):
self.gateId=gateId
self.route=route
| class Config:
gate_id = 0
route = ''
port = 'COM3'
def __init__(self, gateId, route):
self.gateId = gateId
self.route = route |
# linked list class
# class for "node" or in common terms "element"
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None # points to the head of the linked list
def insert_at_begining(self, d... | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_begining(self, data):
node = node(data, self.head)
self.head = node
def insert_at_end(self, data):
... |
"""
https://www.youtube.com/watch?v=UflHuQj6MVA&list=RDCMUCnxhETjJtTPs37hOZ7vQ88g&index=2
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
"""
def longest_palindromic_substring(s):
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]
# all strings of length 1 are palindrome
s... | """
https://www.youtube.com/watch?v=UflHuQj6MVA&list=RDCMUCnxhETjJtTPs37hOZ7vQ88g&index=2
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
"""
def longest_palindromic_substring(s):
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]
start = 0
max_len = 1
for i in range(n)... |
n = int(input())
matrix = [list(map(int, input().split(" "))) for _ in range(n)]
total = 0
for i in range(n):
value = matrix[i][i]
total += value
print(total) | n = int(input())
matrix = [list(map(int, input().split(' '))) for _ in range(n)]
total = 0
for i in range(n):
value = matrix[i][i]
total += value
print(total) |
PROBLEM_PID_MAX_LENGTH = 32
PROBLEM_TITLE_MAX_LENGTH = 128
PROBLEM_SECTION_MAX_LENGTH = 4096
PROBLEM_SAMPLE_MAX_LENGTH = 1024 | problem_pid_max_length = 32
problem_title_max_length = 128
problem_section_max_length = 4096
problem_sample_max_length = 1024 |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/200/B
'''
n = int(input())
props = list(map(int, input().split()))
total = sum([p/100 for p in props])
print((total/n)*100)
| __author__ = 'shukkkur'
'\nhttps://codeforces.com/problemset/problem/200/B\n'
n = int(input())
props = list(map(int, input().split()))
total = sum([p / 100 for p in props])
print(total / n * 100) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
prev = None
curr = head
length = 0
while curr:
curr = cur... | class Solution:
def is_palindrome(self, head: ListNode) -> bool:
prev = None
curr = head
length = 0
while curr:
curr = curr.next
length += 1
half = length // 2
curr = head
for _ in range(half):
next = curr.next
... |
#!/usr/bin/env python3
"""
Initializaiton
+--------------------------------------------------------------------------+
| Copyright 2019 St. Jude Children's Research Hospital |
| |
| Licensed under a modified version of the Apa... | """
Initializaiton
+--------------------------------------------------------------------------+
| Copyright 2019 St. Jude Children's Research Hospital |
| |
| Licensed under a modified version of the Apache License, Version 2.... |
# Learn python - Full Course for Beginners [Tutorial]
# https://www.youtube.com/watch?v=rfscVS0vtbw
# freeCodeCamp.org
# Course developed by Mike Dane.
# Exercise: While Loop
# Date: 30 Aug 2021
# A while loop is a structure that allows code to be executed multiple times until condition is false
# a loop condition , ... | i = 1
while i <= 10:
print(i)
i += 1
print('Done with loop')
secret_word = 'giraffe'
guess = ''
while guess != secret_word:
guess = input('Enter guess: ')
print('You win!')
secret_word = 'giraffe'
guess = ''
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and (not out_of_gu... |
# for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# self.right = right
# self.right = right
# self.right = right
# self.right = right
# self.right =... | class Solution:
def delete_node(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
left = root.left
right = root.right
if root.val == key:
if right is None:
root = left
return root
... |
def process(status):
status_info = {}
status_info['name'] = status.pos.name
status_info['target'] = status.target
return status_info
| def process(status):
status_info = {}
status_info['name'] = status.pos.name
status_info['target'] = status.target
return status_info |
__author__ = 'Ahmed Hani Ibrahim'
class TextEncoder(object):
@classmethod
def encode(cls, categories):
categories_matrix = [[0 for i in range(0, len(categories))] for j in range(0, len(categories))]
true_index = 0
for i in range(0, len(categories)):
categories[i][true_ind... | __author__ = 'Ahmed Hani Ibrahim'
class Textencoder(object):
@classmethod
def encode(cls, categories):
categories_matrix = [[0 for i in range(0, len(categories))] for j in range(0, len(categories))]
true_index = 0
for i in range(0, len(categories)):
categories[i][true_index... |
TRAIN_CONTAINERS = [
'plate',
'cube_concave',
'table_top',
'bowl_small',
'tray',
'open_box',
'cube',
'torus',
]
TEST_CONTAINERS = [
'pan_tefal',
'marble_cube',
'basket',
'checkerboard_table',
]
CONTAINER_CONFIGS = {
'plate': {
'container_position_low': (.50,... | train_containers = ['plate', 'cube_concave', 'table_top', 'bowl_small', 'tray', 'open_box', 'cube', 'torus']
test_containers = ['pan_tefal', 'marble_cube', 'basket', 'checkerboard_table']
container_configs = {'plate': {'container_position_low': (0.5, 0.22, -0.3), 'container_position_high': (0.7, 0.26, -0.3), 'container... |
# -*- coding: utf-8 -*-
class Solution:
def maxProfit(self, prices):
minimum_price = float('inf')
maximum_profit = 0
for price in prices:
if price < minimum_price:
minimum_price = price
if price - minimum_price > maximum_profit:
maxi... | class Solution:
def max_profit(self, prices):
minimum_price = float('inf')
maximum_profit = 0
for price in prices:
if price < minimum_price:
minimum_price = price
if price - minimum_price > maximum_profit:
maximum_profit = price - mini... |
# Program : Find the number of vowels in the string.
# Input : string = "Nature"
# Output : 3
# Explanation : The string "Nature" has 3 vowels in it, ie, 'a', 'u' and 'e'.
# Language : Python3
# O(n) time | O(1) space
def length_of_string(number):
# Initialize the vowel list.
vowels = ["a", "e", "i", "o", "u"... | def length_of_string(number):
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
for ch in string:
if ch in vowels:
count = count + 1
return count
if __name__ == '__main__':
string = 'Nature'
answer = length_of_string(string)
print(answer) |
def reverse_integer(n):
reversed = 0
remainder = 0
while n > 0:
remainder = n % 10
reversed = reversed * 10 + remainder
n = n // 10
return reversed
if __name__ == "__main__":
print(reverse_integer(12345))
| def reverse_integer(n):
reversed = 0
remainder = 0
while n > 0:
remainder = n % 10
reversed = reversed * 10 + remainder
n = n // 10
return reversed
if __name__ == '__main__':
print(reverse_integer(12345)) |
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade # between 0 - 100
def get_grade(self):
return self.grade
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max... | class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def get_grade(self):
return self.grade
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students
s... |
class IRobotCreateError(Exception):
def __init__(self, errorCode = 0, errorMsg = ""):
self.errorCode = errorCode
self.errorMsg = errorMsg
# self.super()
class ErrorCode():
SerialPortNotFound = 1
SerialConnectionTimeout = 2
ConfigFileError = 3
ConfigFileCorrupted = 4
Va... | class Irobotcreateerror(Exception):
def __init__(self, errorCode=0, errorMsg=''):
self.errorCode = errorCode
self.errorMsg = errorMsg
class Errorcode:
serial_port_not_found = 1
serial_connection_timeout = 2
config_file_error = 3
config_file_corrupted = 4
value_out_of_range = 5 |
t=0.0
dt=0.05
cx=0
cy=0
r=180
rs=[(x+2)*1.1 for x in range(500)]
dr=-1
wiperon=True
sopa=255
wopa=40
sc=[255,255,255]
wc=[0,0,0]
fpd=10
def setup():
global cx,cy
size(1280,720)
background(0)
stroke(sc[0],sc[1],sc[2],sopa)
cx=width/2
cy=height/2
def wipe():
fill(wc[0],wc[1],wc[2],wopa)
... | t = 0.0
dt = 0.05
cx = 0
cy = 0
r = 180
rs = [(x + 2) * 1.1 for x in range(500)]
dr = -1
wiperon = True
sopa = 255
wopa = 40
sc = [255, 255, 255]
wc = [0, 0, 0]
fpd = 10
def setup():
global cx, cy
size(1280, 720)
background(0)
stroke(sc[0], sc[1], sc[2], sopa)
cx = width / 2
cy = height / 2
de... |
"""Column Mapping base class."""
class ColumnMapSolver:
"""Base Solver for the data lineage problem of column dependency."""
def fit(self, list_of_databases):
"""Fit this solver.
Args:
list_of_databases (list):
List of tuples containing ``MetaData`` instnces and t... | """Column Mapping base class."""
class Columnmapsolver:
"""Base Solver for the data lineage problem of column dependency."""
def fit(self, list_of_databases):
"""Fit this solver.
Args:
list_of_databases (list):
List of tuples containing ``MetaData`` instnces and ta... |
with open('multiplos4.txt', 'w') as multiplos:
pares = open('pares.txt')
for l in pares.readlines():
num = l.replace('\n', '')
if int(num) % 4 == 0:
multiplos.write(f'{num}\n')
| with open('multiplos4.txt', 'w') as multiplos:
pares = open('pares.txt')
for l in pares.readlines():
num = l.replace('\n', '')
if int(num) % 4 == 0:
multiplos.write(f'{num}\n') |
class BaseSecretEngine:
def __init__(self, config_d):
self.name = config_d['secret_engine_name']
self.default = config_d.get("default", False)
def encrypt(self, data, **context):
raise NotImplementedError
def decrypt(self, data, **context):
raise NotImplementedError
| class Basesecretengine:
def __init__(self, config_d):
self.name = config_d['secret_engine_name']
self.default = config_d.get('default', False)
def encrypt(self, data, **context):
raise NotImplementedError
def decrypt(self, data, **context):
raise NotImplementedError |
n,k,*x=map(int,open(0).read().split())
def distance(l,r):
return min(
abs(l)+abs(r-l),
abs(r)+abs(r-l))
a=[]
for i in range(n-k+1):
a.append(distance(x[i],x[i+k-1]))
print(min(a))
| (n, k, *x) = map(int, open(0).read().split())
def distance(l, r):
return min(abs(l) + abs(r - l), abs(r) + abs(r - l))
a = []
for i in range(n - k + 1):
a.append(distance(x[i], x[i + k - 1]))
print(min(a)) |
"""
Script testing 14.4.1 control from OWASP ASVS 4.0:
'Verify that every HTTP response contains a Content-Type header. Also
specify a safe character set (e.g., UTF-8, ISO-8859-1) if the content types are
text/*, /+xml and application/xml. Content must match with the provided
Content-Type header.'
The script will rai... | """
Script testing 14.4.1 control from OWASP ASVS 4.0:
'Verify that every HTTP response contains a Content-Type header. Also
specify a safe character set (e.g., UTF-8, ISO-8859-1) if the content types are
text/*, /+xml and application/xml. Content must match with the provided
Content-Type header.'
The script will rai... |
# plot a KDE for each attribute
def plot_single_kde(data, attr):
data[[attr]].plot.kde(figsize=(4,2), legend=None)
ax = plt.gca()
ax.set_xlim([data[attr].min(), data[attr].max()])
ax.set_xlabel(attr, fontsize=14)
ax.set_ylabel('Density', fontsize=14)
for attr in data.columns:
plot_single_kde(d... | def plot_single_kde(data, attr):
data[[attr]].plot.kde(figsize=(4, 2), legend=None)
ax = plt.gca()
ax.set_xlim([data[attr].min(), data[attr].max()])
ax.set_xlabel(attr, fontsize=14)
ax.set_ylabel('Density', fontsize=14)
for attr in data.columns:
plot_single_kde(data, attr) |
# Solution
# O(n) time / O(n) space
def sunsetViews(buildings, direction):
buildingsWithSunsetViews = []
startIdx = 0 if direction == "WEST" else len(buildings) - 1
step = 1 if direction == "WEST" else - 1
idx = startIdx
runningMaxHeight = 0
while idx >= 0 and idx < len(buildings):
bu... | def sunset_views(buildings, direction):
buildings_with_sunset_views = []
start_idx = 0 if direction == 'WEST' else len(buildings) - 1
step = 1 if direction == 'WEST' else -1
idx = startIdx
running_max_height = 0
while idx >= 0 and idx < len(buildings):
building_height = buildings[idx]
... |
N=int(input())
M,K=list(map(int,input().split()))
L = list(map(int,input().split()))
L.sort(reverse = True)
S = M*K
for i,j in enumerate(L):
S -= j
if S<=0:
print(i+1)
break
else:
print("STRESS") | n = int(input())
(m, k) = list(map(int, input().split()))
l = list(map(int, input().split()))
L.sort(reverse=True)
s = M * K
for (i, j) in enumerate(L):
s -= j
if S <= 0:
print(i + 1)
break
else:
print('STRESS') |
#!/usr/bin/env python3
while True:
n = int(input("Please enter an Integer: "))
if n < 0:
continue #there will retrun while running
elif n == 0:
break
print("Square is ", n ** 2)
print("Goodbye")
| while True:
n = int(input('Please enter an Integer: '))
if n < 0:
continue
elif n == 0:
break
print('Square is ', n ** 2)
print('Goodbye') |
class Bucket():
'''Utility class for Manber-Myers algorithm.'''
def __init__(self,prefix,stringT):
self.prefix = prefix # one or more letters
self.stringT = stringT # needed for shortcut sort
self.suffixes = [] # array of int
def __str__(self):
viz = ""
viz = viz +... | class Bucket:
"""Utility class for Manber-Myers algorithm."""
def __init__(self, prefix, stringT):
self.prefix = prefix
self.stringT = stringT
self.suffixes = []
def __str__(self):
viz = ''
viz = viz + str(self.prefix)
viz = viz + ' '
viz = viz + str... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.status
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Status(object):
"""Implementation of the 'Status' enum.
TODO: type enum description here.
Attributes:
UNKNOWN: TOD... | """
idfy_rest_client.models.status
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Status(object):
"""Implementation of the 'Status' enum.
TODO: type enum description here.
Attributes:
UNKNOWN: TODO: type description here.
SUCCESS... |
arr = [9, 5, 1, 4, 0, 7]
def quick_sort_v1(arr, l, r):
if l >= r:
return
x = l
y = r
base = arr[l]
while x <= y:
while x <= y and arr[y] > base:
y = y - 1
while x <= y and arr[y] < base:
x = x + 1
if x <= y:
arr[y], arr[x] = arr[x... | arr = [9, 5, 1, 4, 0, 7]
def quick_sort_v1(arr, l, r):
if l >= r:
return
x = l
y = r
base = arr[l]
while x <= y:
while x <= y and arr[y] > base:
y = y - 1
while x <= y and arr[y] < base:
x = x + 1
if x <= y:
(arr[y], arr[x]) = (arr... |
# -*- python -*-
load("@drake//tools/skylark:drake_py.bzl", "py_test_isolated")
def install_lint(
existing_rules = None):
"""Within the current package, checks that any install rules are
depended-on by Drake's master //:install rule.
"""
if existing_rules == None:
existing_rules = nati... | load('@drake//tools/skylark:drake_py.bzl', 'py_test_isolated')
def install_lint(existing_rules=None):
"""Within the current package, checks that any install rules are
depended-on by Drake's master //:install rule.
"""
if existing_rules == None:
existing_rules = native.existing_rules().values()
... |
schema = [
{
"attributes": {
"L": [
{
"M": {
"attr_name": {
"S": "wave_name"
},
"attr_type": {
"S": "wave"
}... | schema = [{'attributes': {'L': [{'M': {'attr_name': {'S': 'wave_name'}, 'attr_type': {'S': 'wave'}}}, {'M': {'attr_name': {'S': 'wave_status'}, 'attr_type': {'S': 'wave'}}}, {'M': {'attr_name': {'S': 'wave_start_time'}, 'attr_type': {'S': 'wave'}}}, {'M': {'attr_name': {'S': 'wave_end_time'}, 'attr_type': {'S': 'wave'}... |
print ("Enter a value" )
a = int (input())
print ("Enter b value" )
b = int (input())
print ("value of a is",a)
print ("value of b is",b)
print ("value of a+b value is", a+b)
print ("value of a-b value is", a-b)
print ("value of a*b value is", a*b)
print ("value of a/b value is", a/b) | print('Enter a value')
a = int(input())
print('Enter b value')
b = int(input())
print('value of a is', a)
print('value of b is', b)
print('value of a+b value is', a + b)
print('value of a-b value is', a - b)
print('value of a*b value is', a * b)
print('value of a/b value is', a / b) |
i = 0
while (i < 50):
print(i)
i = i + 1 | i = 0
while i < 50:
print(i)
i = i + 1 |
for i in range(int(input())):
n,base=input().split()
base=str(base)
aux=0
print("Case %d:"%(i+1))
if base=="bin":
aux=int(n, 2)
print("%d dec"%aux)
aux=hex(aux).replace('0x','')
print("%s hex"%aux)
elif base=="dec":
n=int(n)
aux=hex(n).replace('0x'... | for i in range(int(input())):
(n, base) = input().split()
base = str(base)
aux = 0
print('Case %d:' % (i + 1))
if base == 'bin':
aux = int(n, 2)
print('%d dec' % aux)
aux = hex(aux).replace('0x', '')
print('%s hex' % aux)
elif base == 'dec':
n = int(n)
... |
DATABASES = {
'postgresql_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'quickdb',
'USER': 'sonarsource',
'PASSWORD': '1234', # Noncompliant
'HOST': 'localhost',
'PORT': '5432'
}
}
| databases = {'postgresql_db': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'quickdb', 'USER': 'sonarsource', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432'}} |
class Solution:
def partition(self, s: str) -> List[List[str]]:
def is_palindrome(s:str):
if s == s[::-1]:
return True
else:
return False
path = []
res = []
size = len(s)
def backtracking(s, start):
nonlocal ... | class Solution:
def partition(self, s: str) -> List[List[str]]:
def is_palindrome(s: str):
if s == s[::-1]:
return True
else:
return False
path = []
res = []
size = len(s)
def backtracking(s, start):
nonlo... |
# O(n) time and space where n is number of chars
def get_longest_unique_substring(s):
start_index = 0
end_index = 0
answer = 0
char_to_position = {}
for i,let in enumerate(s):
if let not in char_to_position:
char_to_position[let] = i
elif char_to_position[let] >= start_in... | def get_longest_unique_substring(s):
start_index = 0
end_index = 0
answer = 0
char_to_position = {}
for (i, let) in enumerate(s):
if let not in char_to_position:
char_to_position[let] = i
elif char_to_position[let] >= start_index:
start_index = char_to_positio... |
#How to reverse a number
num = int(input("Enter the number : "))
rev_num = 0
while(num>0):
#logic
rem = num%10
rev_num= (rev_num*10)+rem
num = num//10
print("Result : ",rev_num)
| num = int(input('Enter the number : '))
rev_num = 0
while num > 0:
rem = num % 10
rev_num = rev_num * 10 + rem
num = num // 10
print('Result : ', rev_num) |
def colored(string, color):
"""
Returns the given string wrapped with a ANSI escape code that gives it color when printed to a terminal.
Args:
string: String to be colored.
color: Chosen color for the string. Can be 'r' for red, 'g' for green, 'y' for yellow, 'b' for blue, 'p' for
... | def colored(string, color):
"""
Returns the given string wrapped with a ANSI escape code that gives it color when printed to a terminal.
Args:
string: String to be colored.
color: Chosen color for the string. Can be 'r' for red, 'g' for green, 'y' for yellow, 'b' for blue, 'p' for
... |
load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_android_library")
load(":databinding_aar.bzl", "databinding_aar")
load(":databinding_classinfo.bzl", "direct_class_infos")
load("@io_bazel_rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library")
load(":databinding_r_deps.bzl", "extract_r_txt_deps")
load(":databinding_stubs... | load('@io_bazel_rules_kotlin//kotlin:kotlin.bzl', 'kt_android_library')
load(':databinding_aar.bzl', 'databinding_aar')
load(':databinding_classinfo.bzl', 'direct_class_infos')
load('@io_bazel_rules_kotlin//kotlin:jvm.bzl', 'kt_jvm_library')
load(':databinding_r_deps.bzl', 'extract_r_txt_deps')
load(':databinding_stubs... |
expected_output = {
"program": {
"auto_ip_ring": {
"instance": {
"default": {
"active": "0/RSP1/CPU0",
"active_state": "RUNNING",
"group": "central-services",
"jid": "1156",
"sta... | expected_output = {'program': {'auto_ip_ring': {'instance': {'default': {'active': '0/RSP1/CPU0', 'active_state': 'RUNNING', 'group': 'central-services', 'jid': '1156', 'standby': '0/RSP0/CPU0', 'standby_state': 'RUNNING'}}}, 'bfd': {'instance': {'default': {'active': '0/RSP1/CPU0', 'active_state': 'RUNNING', 'group': ... |
def get_formatted_name(first, middle, last):
"""Generate a neatly formatted full name"""
full_name=f"{first} {middle} {last}"
return full_name.title()
"""this version works for people with middle name but breaks for people with only first and last names""" | def get_formatted_name(first, middle, last):
"""Generate a neatly formatted full name"""
full_name = f'{first} {middle} {last}'
return full_name.title()
'this version works for people with middle name but breaks for people with only first and last names' |
name = input("Please enter your first name: ")
age = int(input("How old are you, {0}? ".format(name)))
print(age)
# if age >= 18:
# print("You are old enough to vote")
# print("Please put an X in the box")
# else:
# print("Please come back in {0} years".format(18-age))
if age < 18:
print("Please come back in {... | name = input('Please enter your first name: ')
age = int(input('How old are you, {0}? '.format(name)))
print(age)
if age < 18:
print('Please come back in {0} years'.format(18 - age))
elif age == 900:
print('Sorry, Yoda you die in Return of the Jedi')
else:
print('You are old enough to vote')
print('Plea... |
states_of_america = ["Delware","Pennsylvanai","Mary land","Texas","New Jersey"]
print(states_of_america[0]) # Be careful for index out of range error
print(states_of_america[-1])
states_of_america.append("Hawaii")
print(states_of_america)
states_of_america.extend(["Rakshith","Dheer"])
print(states_of_america)
# Y... | states_of_america = ['Delware', 'Pennsylvanai', 'Mary land', 'Texas', 'New Jersey']
print(states_of_america[0])
print(states_of_america[-1])
states_of_america.append('Hawaii')
print(states_of_america)
states_of_america.extend(['Rakshith', 'Dheer'])
print(states_of_america) |
#declaring and formatting multiples variables as integer.
num01 = int(input('Type the first number: '))
num02 = int(input('Type the second number: '))
s = num01 + num02
#showing to user the sum of numbers.
print('The sum of {} and {} is: {}' .format(num01, num02, s)) | num01 = int(input('Type the first number: '))
num02 = int(input('Type the second number: '))
s = num01 + num02
print('The sum of {} and {} is: {}'.format(num01, num02, s)) |
# Write a Python program to find whether a given number (accept from the user) is even or odd,
# prints True if its even and False if its odd.
n = int(input("Enter a number: "))
print(n % 2 == 0)
| n = int(input('Enter a number: '))
print(n % 2 == 0) |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class PathResponse(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the val... | class Pathresponse(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'detai... |
sm.setSpeakerID(1012100)
sm.sendNext("Hello, #h #. I've heard plenty about you from Mai. You are interested in becoming a Bowman, right? My name is Athena Pierce, Bowman Job Instructor. Nice to meet you!")
sm.sendSay("How much do you know about Bowmen? We use bows or crossbows to attack enemies at long range, mainly. W... | sm.setSpeakerID(1012100)
sm.sendNext("Hello, #h #. I've heard plenty about you from Mai. You are interested in becoming a Bowman, right? My name is Athena Pierce, Bowman Job Instructor. Nice to meet you!")
sm.sendSay("How much do you know about Bowmen? We use bows or crossbows to attack enemies at long range, mainly. W... |
# Author: Senuri Fernando
a = int(input()) # take user input
b = int(input()) # take user input
print(a+b) # addition
print(a-b) # subtraction
print(a*b) # multiplication
| a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b) |
n, x, xpmin = [int(e) for e in input().split()]
for i in range(n):
xp, q = [int(e) for e in input().split()]
if xp >= xpmin:
print(xp + x, q + 1)
else:
print(xp, q)
| (n, x, xpmin) = [int(e) for e in input().split()]
for i in range(n):
(xp, q) = [int(e) for e in input().split()]
if xp >= xpmin:
print(xp + x, q + 1)
else:
print(xp, q) |
"""
https://leetcode.com/problems/thousand-separator/
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Example 3:
Input: n = 123456789
Output: "123.456.789"
Example 4:
Input: n = 0
Ou... | """
https://leetcode.com/problems/thousand-separator/
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Example 3:
Input: n = 123456789
Output: "123.456.789"
Example 4:
Input: n = 0
Ou... |
class Invalid:
def __init__(self):
self.equivalence_class = "INVALID"
def __str__(self):
return self.equivalence_class
| class Invalid:
def __init__(self):
self.equivalence_class = 'INVALID'
def __str__(self):
return self.equivalence_class |
# Copyright 2019-2021 Wingify Software Pvt. Ltd.
#
# 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 agr... | """ Various settings_file for testings
Notes:
Abbreviations: T = percentTraffic
W = weight split
AB = VISUAL_AB
FT = FEATURE_TEST
FR = FEATURE_ROLLOUT
IFEF = isFeatureEnabled is False
WS = With Seg... |
class Solution:
"""
@param n: an integer
@return: if n is a power of three
"""
def isPowerOfThree(self, n):
# Write your code here
if n == 0:
return False
while n > 1:
if n % 3 != 0:
return False
n = n / 3
return Tr... | class Solution:
"""
@param n: an integer
@return: if n is a power of three
"""
def is_power_of_three(self, n):
if n == 0:
return False
while n > 1:
if n % 3 != 0:
return False
n = n / 3
return True |
abstract_user = {
"id": "",
"name": "",
"email": "",
"avatar": "",
"raw": "",
"provider": "",
}
| abstract_user = {'id': '', 'name': '', 'email': '', 'avatar': '', 'raw': '', 'provider': ''} |
# Read lines of text from STDIN.
def Beriflapp():
while True:
# Reading the input from the user
i = input("What is the value of 2+8 = ")
# Only exits when meets the condition
if i == '10':
break
print("The value", i, "is the wrong answer. Try again")
... | def beriflapp():
while True:
i = input('What is the value of 2+8 = ')
if i == '10':
break
print('The value', i, 'is the wrong answer. Try again')
print('The value', i, 'is the right answer')
while True:
i = input('What is the value of 4+1 = ')
if i == '5':... |
# -*- coding: utf-8 -*-
'''
Manage grains on the minion
===========================
This state allows for grains to be set.
Grains set or altered this way are stored in the 'grains'
file on the minions, by default at: /etc/salt/grains
Note: This does NOT override any grains set in the minion file.
'''
def present(n... | """
Manage grains on the minion
===========================
This state allows for grains to be set.
Grains set or altered this way are stored in the 'grains'
file on the minions, by default at: /etc/salt/grains
Note: This does NOT override any grains set in the minion file.
"""
def present(name, value):
"""
... |
"""
Multiples of 3 and 5
====================
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
https://projecteuler.net/problem=1
"""
print(sum([n for n in range(1, 1000) if n % 3 ... | """
Multiples of 3 and 5
====================
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
https://projecteuler.net/problem=1
"""
print(sum([n for n in range(1, 1000) if n % 3 ... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | class Environment(object):
def __init__(self, version_label=None, status=None, app_name=None, health=None, id=None, date_updated=None, platform=None, description=None, name=None, date_created=None, tier=None, cname=None, option_settings=None, is_abortable=False, environment_links=None, environment_arn=None):
... |
'''
Basic Binary Tree in Array Representation
Referred from:
www.javatpoint.com/program-to-implement-binary-tree-using-the-linked-list
'''
class Node:
def __init__(self, key):
self.value = key
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root =... | """
Basic Binary Tree in Array Representation
Referred from:
www.javatpoint.com/program-to-implement-binary-tree-using-the-linked-list
"""
class Node:
def __init__(self, key):
self.value = key
self.left = None
self.right = None
class Binarytree:
def __init__(self):
self.root... |
people = [
{
'name': 'Lucas',
'age': 27,
'gender': 'Male',
},
{
'name': 'Miguel',
'age': 4,
'gender': 'Male',
},
{
'name': 'Adriana',
'age': 27,
'gender': 'Female',
},
]
for person in people:
for field, data in person.i... | people = [{'name': 'Lucas', 'age': 27, 'gender': 'Male'}, {'name': 'Miguel', 'age': 4, 'gender': 'Male'}, {'name': 'Adriana', 'age': 27, 'gender': 'Female'}]
for person in people:
for (field, data) in person.items():
print(f'{field.title()}: {data}')
print('{:=^20}'.format('')) |
class Solution:
def noOfWays(self, M, N, X):
# code here
if X > M * N:
return 0
ways = [[0 for _ in range(M * N + 1)] for _ in range(N + 1)]
for i in range(1, M + 1):
ways[1][i] = 1
for i in range(2, N + 1):
f... | class Solution:
def no_of_ways(self, M, N, X):
if X > M * N:
return 0
ways = [[0 for _ in range(M * N + 1)] for _ in range(N + 1)]
for i in range(1, M + 1):
ways[1][i] = 1
for i in range(2, N + 1):
for j in range(1, X + 1):
for k i... |
a_1 = -6
b_1 = -6
a = -5
b = -5
m = 255
n = 255
m_add_1 = 100000
n_add_1 = 100000
if __name__ == '__main__':
print(a_1 is b_1)
print(a is b)
print(m is n)
print(m_add_1 is n_add_1)
| a_1 = -6
b_1 = -6
a = -5
b = -5
m = 255
n = 255
m_add_1 = 100000
n_add_1 = 100000
if __name__ == '__main__':
print(a_1 is b_1)
print(a is b)
print(m is n)
print(m_add_1 is n_add_1) |
def hex_to_int(hex):
assert hex.startswith('0x')
hex = hex[2:]
total = 0
for h in hex:
total *= 16
total += '0123456789abcdef'.index(h)
return total
def byte_to_uint(byte):
total = 0
for c in byte:
total *= 2
if c == '1':
total += 1
return tot... | def hex_to_int(hex):
assert hex.startswith('0x')
hex = hex[2:]
total = 0
for h in hex:
total *= 16
total += '0123456789abcdef'.index(h)
return total
def byte_to_uint(byte):
total = 0
for c in byte:
total *= 2
if c == '1':
total += 1
return tot... |
#stores the current state of the register machine for the interpreter
class RMState:
def __init__(self, REGS):
self.b = 1
self.acc = 0
self.REGS = REGS
self.ended = False
| class Rmstate:
def __init__(self, REGS):
self.b = 1
self.acc = 0
self.REGS = REGS
self.ended = False |
class Tower:
__slots__ = 'rings', 'capacity'
def __init__(self, cap: int):
self.rings = list()
self.capacity = cap
def add(self, ring_size:int):
if len(self.rings) >= self.capacity:
raise IndexError('Tower already at max capacity')
if (len(self.rings) > 0) and (... | class Tower:
__slots__ = ('rings', 'capacity')
def __init__(self, cap: int):
self.rings = list()
self.capacity = cap
def add(self, ring_size: int):
if len(self.rings) >= self.capacity:
raise index_error('Tower already at max capacity')
if len(self.rings) > 0 and... |
{
'targets' : [
{
'target_name' : 'test',
'type' : 'executable',
'sources' : [
'<!@(find *.cc)',
'<!@(find *.h)'
],
'include_dirs' : [
],
'libraries' : [
],
'conditions' : [
['OS=="mac"', {
'xcode_settings': {
'A... | {'targets': [{'target_name': 'test', 'type': 'executable', 'sources': ['<!@(find *.cc)', '<!@(find *.h)'], 'include_dirs': [], 'libraries': [], 'conditions': [['OS=="mac"', {'xcode_settings': {'ARCHS': '$(ARCHS_STANDARD_64_BIT)'}, 'link_settings': {'libraries': []}}]]}]} |
class ShorteningErrorException(Exception):
def __init__(self, message=None):
super().__init__(f'There was an error on trying to short the url: '
f'{message}')
class ExpandingErrorException(Exception):
def __init__(self, message=None):
super().__init__(f'There w... | class Shorteningerrorexception(Exception):
def __init__(self, message=None):
super().__init__(f'There was an error on trying to short the url: {message}')
class Expandingerrorexception(Exception):
def __init__(self, message=None):
super().__init__(f'There was an error on trying to expand the ... |
#
# PySNMP MIB module CISCO-VISM-CAS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VISM-CAS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
#
# PySNMP MIB module CISCO-WIRELESS-P2P-BPI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WIRELESS-P2P-BPI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:05:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f"):
self.name = name
self.fmt = fmt
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
... | class Averagemeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
... |
class Solution:
def maximum69Number (self, num: int) -> int:
n = 1000
m = num
#// as it is mentioned constraint as num < 10^4
while m:
if((m//n) == 6):
num += n*3
break
m = m%n
n = n/10
return int(num)
... | class Solution:
def maximum69_number(self, num: int) -> int:
n = 1000
m = num
while m:
if m // n == 6:
num += n * 3
break
m = m % n
n = n / 10
return int(num) |
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
# how to fill the table
n1 = len(nums1)
n2 = len(nums2)
dp = [[-math.inf] * (n2 + 1) for _ in range(n1 + 1)]
for i in range(n1 - 1, -1, -1):
for j in range(n2 - 1, -1, -1):
... | class Solution:
def max_dot_product(self, nums1: List[int], nums2: List[int]) -> int:
n1 = len(nums1)
n2 = len(nums2)
dp = [[-math.inf] * (n2 + 1) for _ in range(n1 + 1)]
for i in range(n1 - 1, -1, -1):
for j in range(n2 - 1, -1, -1):
dp[i][j] = max(nums1... |
#
# PySNMP MIB module ADTRAN-IF-PERF-HISTORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-IF-PERF-HISTORY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:14:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (ad_gen_aos_conformance, ad_gen_aos_common) = mibBuilder.importSymbols('ADTRAN-AOS', 'adGenAOSConformance', 'adGenAOSCommon')
(ad_identity,) = mibBuilder.importSymbols('ADTRAN-MIB', 'adIdentity')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
... |
# coding=utf-8
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
"default": {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'mysql',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'root',
'NAME': 'cloudsky_backend'
... | databases = {'default': {'ENGINE': 'django.db.backends.mysql', 'HOST': 'mysql', 'PORT': 3306, 'USER': 'root', 'PASSWORD': 'root', 'NAME': 'cloudsky_backend'}}
caches = {'default': {'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis:6379', 'OPTIONS': {'CLIENT_CLASS': 'django_redis.client.DefaultClien... |
while True:
try:
s = input()
# s = 'haha'
print(s)
except :
# print(e)
break | while True:
try:
s = input()
print(s)
except:
break |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.