content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
wordle = open("Wordle.txt", "r")
wordList = []
for line in wordle:
stripped_line = line.strip()
wordList.append(stripped_line)
mutableList = []
outcomeList = []
def blackLetter(letter, list):
for word in list:
if letter in word:
list.remove(word)
def greenLetter(letter, ... | wordle = open('Wordle.txt', 'r')
word_list = []
for line in wordle:
stripped_line = line.strip()
wordList.append(stripped_line)
mutable_list = []
outcome_list = []
def black_letter(letter, list):
for word in list:
if letter in word:
list.remove(word)
def green_letter(letter, location, ... |
weight = []
diff = 0
n = int(input())
for i in range(n):
q, c = map(int, input().split())
if c == 2:
q *= -1
weight.append(q)
diff += q
min_diff = abs(diff)
for i in range(n):
if abs(diff - 2*weight[i]) < min_diff:
min_diff = abs(diff - 2*weight[i])
for j in range(i+1, n):
... | weight = []
diff = 0
n = int(input())
for i in range(n):
(q, c) = map(int, input().split())
if c == 2:
q *= -1
weight.append(q)
diff += q
min_diff = abs(diff)
for i in range(n):
if abs(diff - 2 * weight[i]) < min_diff:
min_diff = abs(diff - 2 * weight[i])
for j in range(i + 1, n)... |
def counting_sort(arr):
# Find min and max values
min_value = min(arr)
max_value = max(arr)
counting_arr = [0]*(max_value-min_value+1)
for num in arr:
counting_arr[num-min_value] += 1
index = 0
for i, count in enumerate(counting_arr):
for _ in range(count):
... | def counting_sort(arr):
min_value = min(arr)
max_value = max(arr)
counting_arr = [0] * (max_value - min_value + 1)
for num in arr:
counting_arr[num - min_value] += 1
index = 0
for (i, count) in enumerate(counting_arr):
for _ in range(count):
arr[index] = min_value + i... |
# [8 kyu] Grasshopper - Terminal Game Move Function
#
# Author: Hsins
# Date: 2019/12/20
def move(position, roll):
return position + 2 * roll
| def move(position, roll):
return position + 2 * roll |
# Go to new line using \n
print('-------------------------------------------------------')
print("My name is\nMaurizio Petrelli")
# Inserting characters using octal values
print('-------------------------------------------------------')
print("\100 \136 \137 \077 \176")
# Inserting characters using hex values
print('... | print('-------------------------------------------------------')
print('My name is\nMaurizio Petrelli')
print('-------------------------------------------------------')
print('@ ^ _ ? ~')
print('-------------------------------------------------------')
print('# $ % & *')
print('-----------------------------------------... |
class RetryOptions:
def __init__(self, firstRetry: int, maxNumber: int):
self.backoffCoefficient: int
self.maxRetryIntervalInMilliseconds: int
self.retryTimeoutInMilliseconds: int
self.firstRetryIntervalInMilliseconds: int = firstRetry
self.maxNumberOfAttempts: int = maxNumb... | class Retryoptions:
def __init__(self, firstRetry: int, maxNumber: int):
self.backoffCoefficient: int
self.maxRetryIntervalInMilliseconds: int
self.retryTimeoutInMilliseconds: int
self.firstRetryIntervalInMilliseconds: int = firstRetry
self.maxNumberOfAttempts: int = maxNumb... |
def rotations(l):
out = []
for i in range(len(l)):
a = shift(l, i)
out += [a]
return out
def shift(l, n):
return l[n:] + l[:n]
if __name__ == '__main__':
l = [0,1,2,3,4]
for x in rotations(l):
print(x) | def rotations(l):
out = []
for i in range(len(l)):
a = shift(l, i)
out += [a]
return out
def shift(l, n):
return l[n:] + l[:n]
if __name__ == '__main__':
l = [0, 1, 2, 3, 4]
for x in rotations(l):
print(x) |
def make_cut(l):
smallest = min(l)
return [
x - smallest
for x
in l
if x - smallest > 0
]
length = int(input())
current = list(
map(
int,
input().split()
)
)
while current:
print(len(current))
current = make_cut(current)
| def make_cut(l):
smallest = min(l)
return [x - smallest for x in l if x - smallest > 0]
length = int(input())
current = list(map(int, input().split()))
while current:
print(len(current))
current = make_cut(current) |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1023/A
def f(ll):
n,k = ll #1e14
f = k//2 + 1
e = min(k-1,n)
return max(0,e-f+1)
l = list(map(int,input().split()))
print(f(l))
| def f(ll):
(n, k) = ll
f = k // 2 + 1
e = min(k - 1, n)
return max(0, e - f + 1)
l = list(map(int, input().split()))
print(f(l)) |
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7/0014/80C4285C-779E-DD11-9889-001617E30CA4.root',
'rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7... | ('rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T_v7/0014/80C4285C-779E-DD11-9889-001617E30CA4.root',)
('rfio:///?svcClass=cmscaf&path=/castor/cern.ch/cms/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_V2P_StreamALCARECOTkAlCosmics0T... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deno_repository():
# Get Deno archive
http_archive(
name = "deno-amd64",
build_file = "//ext/deno:BUILD",
sha256 = "7b883e3c638d21dd1875f0108819f2f13647b866ff24965135e679c743013f46",
type = "zip",
u... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def deno_repository():
http_archive(name='deno-amd64', build_file='//ext/deno:BUILD', sha256='7b883e3c638d21dd1875f0108819f2f13647b866ff24965135e679c743013f46', type='zip', urls=['https://github.com/denoland/deno/releases/download/v1.17.3/deno-x8... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def libevent():
http_archive(
name = "libevent",
build_fi... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def libevent():
http_archive(name='libevent', build_file='//bazel/deps/libevent:build.BUILD', sha256='9b436b404793be621c6e01cea573e1a06b5db26dad25a11c6a8c6f8526ed264c', strip_prefi... |
# jumlah segitiga
n = 123
# panjang alas sebuah segitiga
alas = 30
# tinggi sebuah segitiga
tinggi = 18
# hitung luas sebuah segitiga
luas = alas * tinggi * 1/2
# hitung luas total
luastotal = n * luas
print('luas total : ', luastotal,'satuan luas') | n = 123
alas = 30
tinggi = 18
luas = alas * tinggi * 1 / 2
luastotal = n * luas
print('luas total : ', luastotal, 'satuan luas') |
# http://codingbat.com/prob/p193507
def string_times(str, n):
result = ""
for i in range(0, n):
result += str
return result
| def string_times(str, n):
result = ''
for i in range(0, n):
result += str
return result |
def alternate_case(s):
# Like a Giga Chad
return "".join([char.lower() if char.isupper() else char.upper() for char in s])
# Like a Beta Male
# return s.swapcase()
# EXAMPLE AND TESTING #
input = ["Hello World", "cODEwARS"]
for item in input:
print("\nInput: {0}\nAlternate Case: {1}".format(item,... | def alternate_case(s):
return ''.join([char.lower() if char.isupper() else char.upper() for char in s])
input = ['Hello World', 'cODEwARS']
for item in input:
print('\nInput: {0}\nAlternate Case: {1}'.format(item, alternate_case(item)))
assert alternate_case('Hello World') == 'hELLO wORLD'
assert alternate_case... |
#!/usr/bin/python3
list = ["Armitage", "Backdoor Factory", "BeEF","cisco-auditing-tool",
"cisco-global-exploiter","cisco-ocs","cisco-torch","Commix","crackle",
"exploitdb","jboss-autopwn","Linux Exploit Suggester","Maltego Teeth",
"Metasploit Framework","MSFPC","RouterSploit","SET","ShellNoob","sqlmap",
"THC-IPV6","Ye... | list = ['Armitage', 'Backdoor Factory', 'BeEF', 'cisco-auditing-tool', 'cisco-global-exploiter', 'cisco-ocs', 'cisco-torch', 'Commix', 'crackle', 'exploitdb', 'jboss-autopwn', 'Linux Exploit Suggester', 'Maltego Teeth', 'Metasploit Framework', 'MSFPC', 'RouterSploit', 'SET', 'ShellNoob', 'sqlmap', 'THC-IPV6', 'Yersinia... |
def get_max_coins_helper(matrix, crow, ccol, rows, cols):
cval = matrix[crow][ccol]
if crow == rows - 1 and ccol == cols - 1:
return cval
down, right = cval, cval
if crow < rows - 1:
down += get_max_coins_helper(
matrix, crow + 1, ccol, rows, cols)
if ccol < cols - 1:
... | def get_max_coins_helper(matrix, crow, ccol, rows, cols):
cval = matrix[crow][ccol]
if crow == rows - 1 and ccol == cols - 1:
return cval
(down, right) = (cval, cval)
if crow < rows - 1:
down += get_max_coins_helper(matrix, crow + 1, ccol, rows, cols)
if ccol < cols - 1:
righ... |
class NEC:
def __init__( self ):
self.prompt = '(.*)'
self.timeout = 60
def show(self, *options, **def_args ):
'''Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-s... | class Nec:
def __init__(self):
self.prompt = '(.*)'
self.timeout = 60
def show(self, *options, **def_args):
"""Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-sta... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'CwT'
# document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post">
# <input type="hidden" name="q" value="a"></form>';
# document.getElementById("dynForm").submit();
POST_JS = '<form id=\\"dynamicform\\" action=\\"%s\\" met... | post_js = '<form id=\\"dynamicform\\" action=\\"%s\\" method=\\"post\\">%s</form>'
input_js = '<input type=\\"hidden\\" name=\\"%s\\" value=%s>'
execute_js = 'document.body.innerHTML = "%s"; document.getElementById("dynamicform").submit();'
def post_js(url, data):
input = ''
for (key, value) in data.items():
... |
# data hiding - encapsulation
# this can be achieve by making the attribute or method private
# python doesn't have private keyword so precede
# the attribute/method identifier with an underscore or a double
# this is more effective if object in import or used as a module
# it isn't that effective
# no underscore = pu... | class Person:
__name = ''
__age = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
me = person('John Doe', 32)
print(me._Person__name) |
# Instruksi:
# Buatlah komentar di garis pertama,
# Buat variabel bernama jumlah_pacar yang isinya angka (bukan desimal),
# Buat variabel bernama lagi_galau yang isinya boolean,
# Buat variabel dengan nama terserah anda dan gunakan salah satu dari operator matematika yang telah kita pelajari.
#variabel untuk menyimpan... | jumlah_pacar = 1
lagi_galau = False
umur = 20 |
# About: Implementation of the accumulator program
# in python 3 specialization
# ask to enter string
phrase = input("Enter a string: ")
# initialize total variable with zero
tot = 0
# iterate through the string
for char in phrase :
if char != " " :
tot += 1
# print the result
print(tot) | phrase = input('Enter a string: ')
tot = 0
for char in phrase:
if char != ' ':
tot += 1
print(tot) |
class MapHash:
def __init__(self, maxsize=6):
self.maxsize = maxsize # Real scenario 64.
self.hash = [None] * self.maxsize # Will be a 2D list
def _get_hash_key(self, key):
hash = sum(ord(k) for k in key)
return hash % self.maxsize
def add(self, key, value)... | class Maphash:
def __init__(self, maxsize=6):
self.maxsize = maxsize
self.hash = [None] * self.maxsize
def _get_hash_key(self, key):
hash = sum((ord(k) for k in key))
return hash % self.maxsize
def add(self, key, value):
hash_key = self._get_hash_key(key)
h... |
#Refer AlexNet implementation code, returns last fully connected layer
fc7 = AlexNet(resized, feature_extract=True)
shape = (fc7.get_shape().as_list()[-1], 43)
fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=1e-2))
fc8_b = tf.Variable(tf.zeros(43))
logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b)
probs = tf.... | fc7 = alex_net(resized, feature_extract=True)
shape = (fc7.get_shape().as_list()[-1], 43)
fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=0.01))
fc8_b = tf.Variable(tf.zeros(43))
logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b)
probs = tf.nn.softmax(logits) |
def isSubsetSum(arr, n, sum):
'''
Returns true if there exists a subset
with given sum in arr[]
'''
# The value of subset[i%2][j] will be true
# if there exists a subset of sum j in
# arr[0, 1, ...., i-1]
subset = [[False for j in range(sum + 1)] for i in range(3)]
for i in range(n... | def is_subset_sum(arr, n, sum):
"""
Returns true if there exists a subset
with given sum in arr[]
"""
subset = [[False for j in range(sum + 1)] for i in range(3)]
for i in range(n + 1):
for j in range(sum + 1):
if j == 0:
subset[i % 2][j] = True
el... |
tup = ('a','b',1,2,3)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
| tup = ('a', 'b', 1, 2, 3)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4]) |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
final = list()
# ----------------------------------------------------
if len(nums)==1:
return [[],nums]
if len(nums)==0:
return []
# ----------------------------------------------------... | class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
final = list()
if len(nums) == 1:
return [[], nums]
if len(nums) == 0:
return []
def pop(cut):
if not cut:
return
else:
for i in range(... |
# -*- coding: utf-8 -*-
# @Time: 2020/7/3 10:21
# @Author: GraceKoo
# @File: interview_33.py
# @Desc: https://leetcode-cn.com/problems/chou-shu-lcof/
class Solution:
def nthUglyNumber(self, n: int) -> int:
if n <= 0:
return 0
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):... | class Solution:
def nth_ugly_number(self, n: int) -> int:
if n <= 0:
return 0
(dp, a, b, c) = ([1] * n, 0, 0, 0)
for i in range(1, n):
min_ugly = min(dp[a] * 2, dp[b] * 3, dp[c] * 5)
dp[i] = min_ugly
if min_ugly == dp[a] * 2:
a... |
# Solution for the SafeCracker 50 Puzzle from Creative Crafthouse
# By: Eric Pollinger
# 9/11/2016
#
# Function to handle the addition of a given slice
def add(slice):
if row1Outer[(index1 + slice) % 16] != -1:
valRow1 = row1Outer[(index1 + slice) % 16]
else:
valRow1 = row0Inner[slice]
... | def add(slice):
if row1Outer[(index1 + slice) % 16] != -1:
val_row1 = row1Outer[(index1 + slice) % 16]
else:
val_row1 = row0Inner[slice]
if row2Outer[(index2 + slice) % 16] != -1:
val_row2 = row2Outer[(index2 + slice) % 16]
else:
val_row2 = row1Inner[(index1 + slice) % 16... |
# test __getattr__ on module
# ensure that does_not_exist doesn't exist to start with
this = __import__(__name__)
try:
this.does_not_exist
assert False
except AttributeError:
pass
# define __getattr__
def __getattr__(attr):
if attr == 'does_not_exist':
return False
raise AttributeError
# ... | this = __import__(__name__)
try:
this.does_not_exist
assert False
except AttributeError:
pass
def __getattr__(attr):
if attr == 'does_not_exist':
return False
raise AttributeError
if not hasattr(this, 'does_not_exist'):
print('SKIP')
raise SystemExit
print(this.does_not_exist) |
#Cristian Chitiva
#cychitivav@unal.edu.co
#12/Sept/2018
myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list
myList.append([4, 5]) #Add sublist [4, 5] to myList
myList.insert(2,"f") #Add "f" in the position 2
print(myList)
myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort() #So... | my_list = ['Hi', 5, 6, 3.4, 'i']
myList.append([4, 5])
myList.insert(2, 'f')
print(myList)
my_list = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455]
myList.sort()
print(myList)
myList.sort(reverse=True)
print(myList)
myList.extend([5, 77])
print(myList)
my_list = []
for value in range(0, 50):
myList.append(val... |
sample = ["abc", "xyz", "aba", "1221"]
def stringCounter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print("The amount of string that meet the criteria is:",stringCounter(sample)) | sample = ['abc', 'xyz', 'aba', '1221']
def string_counter(items):
amount = 0
for i in items:
if len(i) >= 2 and i[0] == i[-1]:
amount += 1
return amount
print('The amount of string that meet the criteria is:', string_counter(sample)) |
# Uri Online Judge 1079
N = int(input())
for i in range(0,N):
Numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2*num1+3*num2+5*num3)/10).__round__(1)) | n = int(input())
for i in range(0, N):
numbers = input()
num1 = float(Numbers.split()[0])
num2 = float(Numbers.split()[1])
num3 = float(Numbers.split()[2])
print(((2 * num1 + 3 * num2 + 5 * num3) / 10).__round__(1)) |
entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsedParams = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if co... | entity_id = data.get('entity_id')
command = data.get('command')
params = str(data.get('params'))
parsed_params = []
for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'):
rect = []
for c in z.split(','):
rect.append(int(c))
parsedParams.append(rect)
if com... |
def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter
| def rank_filter(func):
def func_filter(local_rank=-1, *args, **kwargs):
if local_rank < 1:
return func(*args, **kwargs)
else:
pass
return func_filter |
tot=coe=rat=sap=0
for i in range(int(input())):
n,s=input().split()
n=int(n)
tot+=n
if s=='C':coe+=n
elif s=='R':rat+=n
elif s=='S':sap+=n
print(f"Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}")
p=(coe/tot)*100
print("Percentual de coelhos: %.2f"%p,e... | tot = coe = rat = sap = 0
for i in range(int(input())):
(n, s) = input().split()
n = int(n)
tot += n
if s == 'C':
coe += n
elif s == 'R':
rat += n
elif s == 'S':
sap += n
print(f'Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}')... |
[ ## this file was manually modified by jt
{
'functor' : {
'description' : [ "The function always returns a value of the same type than the entry.",
"Take care that for integers the value returned can differ by one unit",
"from \c ceil((a+b)/2.0) o... | [{'functor': {'description': ['The function always returns a value of the same type than the entry.', 'Take care that for integers the value returned can differ by one unit', 'from \\c ceil((a+b)/2.0) or \\c floor((a+b)/2.0), but is always one of', 'the two'], 'module': 'boost', 'arity': '2', 'call_types': [], 'ret_ari... |
# Audit Event Outcomes
AUDIT_SUCCESS = "0"
AUDIT_MINOR_FAILURE = "4"
AUDIT_SERIOUS_FAILURE = "8"
AUDIT_MAJOR_FAILURE = "12"
| audit_success = '0'
audit_minor_failure = '4'
audit_serious_failure = '8'
audit_major_failure = '12' |
#771. Jewels and Stones
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# count = 0
# jewl = {}
# for i in jewels:
# if i not in jewl:
# jewl[i] = 0
# for j in stones:
# if j in jewl:
# count += 1
... | class Solution:
def num_jewels_in_stones(self, jewels: str, stones: str) -> int:
count = 0
jewl = set(jewels)
for s in stones:
if s in jewl:
count += 1
return count |
class MaxPQ:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self, ):
m = self.pq[0]
self.pq[0], self.pq[-1] = self.pq[-1], self.pq[0]
self.pq = se... | class Maxpq:
def __init__(self):
self.pq = []
def insert(self, v):
self.pq.append(v)
self.swim(len(self.pq) - 1)
def max(self):
return self.pq[0]
def del_max(self):
m = self.pq[0]
(self.pq[0], self.pq[-1]) = (self.pq[-1], self.pq[0])
self.pq = ... |
BOT_TOKEN: str = "ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM"
SPOTIFY_ID: str = ""
SPOTIFY_SECRET: str = ""
BOT_PREFIX = "$"
EMBED_COLOR = 0x4dd4d0 #replace after'0x' with desired hex code ex. '#ff0188' >> '0xff0188'
SUPPORTED_EXTENSIONS = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '... | bot_token: str = 'ODg4MzAyMzkwNTMxNDg1Njk2.YUQuEQ.UO4oyY9Zk4u1W5f-VpPLkkQ70TM'
spotify_id: str = ''
spotify_secret: str = ''
bot_prefix = '$'
embed_color = 5100752
supported_extensions = ('.webm', '.mp4', '.mp3', '.avi', '.wav', '.m4v', '.ogg', '.mov')
max_song_preload = 5
cookie_path = '/config/cookies/cookies.txt'
gl... |
class IncompatibleAttribute(Exception):
pass
class IncompatibleDataException(Exception):
pass
class UndefinedROI(Exception):
pass
class InvalidSubscriber(Exception):
pass
class InvalidMessage(Exception):
pass
| class Incompatibleattribute(Exception):
pass
class Incompatibledataexception(Exception):
pass
class Undefinedroi(Exception):
pass
class Invalidsubscriber(Exception):
pass
class Invalidmessage(Exception):
pass |
# Enter script code
message = "kubectl exec -it <cursor> -- bash"
keyboard.send_keys("kubectl exec -it ")
keyboard.send_keys("<shift>+<ctrl>+v")
time.sleep(0.1)
keyboard.send_keys(" -- bash")
| message = 'kubectl exec -it <cursor> -- bash'
keyboard.send_keys('kubectl exec -it ')
keyboard.send_keys('<shift>+<ctrl>+v')
time.sleep(0.1)
keyboard.send_keys(' -- bash') |
'''
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
'''
#!/bin/python3
# Complete the 'diagonalD... | """
Topic : Algorithms
Subtopic : Diagonal Difference
Language : Python
Problem Statement : Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Url : https://www.hackerrank.com/challenges/diagonal-difference/problem
"""
def diagonal_difference(arr):
n = l... |
class ParsnipException(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr("[%s] %s - %s" % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class LoginError(ParsnipException):pa... | class Parsnipexception(Exception):
def __init__(self, msg, webtexter=None):
self.args = (msg, webtexter)
self.msg = msg
self.webtexter = webtexter
def __str__(self):
return repr('[%s] %s - %s' % (self.webtexter.NETWORK_NAME, self.webtexter.phone_number, self.msg))
class Logine... |
def soma(x,y):
return print(x + y)
def sub(x,y):
return print(x - y)
def mult(x,y):
return print(x * y)
def div(x,y):
return print(x / y)
soma(3,8)
sub(10,5)
mult(3,9)
div(15,7) | def soma(x, y):
return print(x + y)
def sub(x, y):
return print(x - y)
def mult(x, y):
return print(x * y)
def div(x, y):
return print(x / y)
soma(3, 8)
sub(10, 5)
mult(3, 9)
div(15, 7) |
class DeviceLog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def getStatus(self):
if self.t... | class Devicelog:
def __init__(self, deviceId, deviceName, temperature, location, recordDate):
self.deviceId = deviceId
self.deviceName = deviceName
self.temperature = temperature
self.location = location
self.recordDate = recordDate
def get_status(self):
if self... |
class NeighborResult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = []
| class Neighborresult:
def __init__(self):
self.solutions = []
self.choose_path = []
self.current_num = 0
self.curr_solved_gates = [] |
'''
@brief this class reflect action decision regarding condition
'''
class EventAction():
'''
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
'''
def __init__(self, cond="", to=... | """
@brief this class reflect action decision regarding condition
"""
class Eventaction:
"""
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
"""
def __init__(self, cond='', to='... |
age = int(input("How old are you ?"))
#if age >= 16 and age <= 65:
#if 16 <= age <= 65:
if age in range(16,66):
print ("Have a good day at work.")
elif age > 100 or age <= 0:
print ("Nice Try. This program is not dumb.")
endkey = input ("Press enter to exit")
else:
print (f"Enjoy your free time, ... | age = int(input('How old are you ?'))
if age in range(16, 66):
print('Have a good day at work.')
elif age > 100 or age <= 0:
print('Nice Try. This program is not dumb.')
endkey = input('Press enter to exit')
else:
print(f'Enjoy your free time, you need to work for us after {65 - age} years.')
print('-' ... |
class Solution:
def longestPalindrome(self, s: str) -> int:
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
res = 0
for _, n in d.items():
res += n - (n & 1)
return res + 1 if res < len(s) e... | class Solution:
def longest_palindrome(self, s: str) -> int:
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
res = 0
for (_, n) in d.items():
res += n - (n & 1)
return res + 1 if res < len(s... |
# OpenWeatherMap API Key
weather_api_key = "f4695ec49ac558195fc591f0d450c34c"
# Google API Key
g_key = "AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk"
| weather_api_key = 'f4695ec49ac558195fc591f0d450c34c'
g_key = 'AIzaSyAyIq5hhFN-Y0M16Ltie3YuwpDiKWx8tCk' |
class ArgumentError(Exception):
def __init__(self, argument_name: str, *args) -> None:
super().__init__(*args)
self.argument_name = argument_name
@property
def argument_name(self) -> str:
return self.__argument_name
@argument_name.setter
def argument_name(self, value: s... | class Argumenterror(Exception):
def __init__(self, argument_name: str, *args) -> None:
super().__init__(*args)
self.argument_name = argument_name
@property
def argument_name(self) -> str:
return self.__argument_name
@argument_name.setter
def argument_name(self, value: str)... |
BOT_NAME = "placement"
SPIDER_MODULES = ["placement.spiders"]
NEWSPIDER_MODULE = "placement.spiders"
ROBOTSTXT_OBEY = True
CONCURRENT_REQUESTS = 16
DUPEFILTER_DEBUG = True
EXTENSIONS = {"spidermon.contrib.scrapy.extensions.Spidermon": 500}
SPIDERMON_ENABLED = True
ITEM_PIPELINES = {"spidermon.contrib.scrapy.pipeli... | bot_name = 'placement'
spider_modules = ['placement.spiders']
newspider_module = 'placement.spiders'
robotstxt_obey = True
concurrent_requests = 16
dupefilter_debug = True
extensions = {'spidermon.contrib.scrapy.extensions.Spidermon': 500}
spidermon_enabled = True
item_pipelines = {'spidermon.contrib.scrapy.pipelines.I... |
def star_pattern(n):
for i in range(n):
for j in range(i+1):
print("*",end=" ")
print()
star_pattern(5)
'''
star_pattern(5)
*
* *
* * *
* * * *
* * * * *
'''
| def star_pattern(n):
for i in range(n):
for j in range(i + 1):
print('*', end=' ')
print()
star_pattern(5)
'\n star_pattern(5)\n *\n * *\n * * *\n * * * *\n * * * * *\n ' |
# 1461. Check If a String Contains All Binary Codes of Size K
# User Accepted:2806
# User Tried:4007
# Total Accepted:2876
# Total Submissions:9725
# Difficulty:Medium
# Given a binary string s and an integer k.
# Return True if any binary code of length k is a substring of s. Otherwise, return False.
# Example 1:
# ... | class Solution:
def has_all_codes(self, s: str, k: int) -> bool:
for i in range(2 ** k):
tmp = str(bin(i))[2:]
if len(tmp) < k:
tmp = '0' * (k - len(tmp)) + tmp
if tmp in s:
continue
else:
return False
r... |
n = int(input())
v = []
for i in range(n): v.append(int(input()))
s = sorted(set(v))
for i in s: print(f'{i} aparece {v.count(i)} vez (es)')
| n = int(input())
v = []
for i in range(n):
v.append(int(input()))
s = sorted(set(v))
for i in s:
print(f'{i} aparece {v.count(i)} vez (es)') |
expected_output = {
"vrf": {
"VRF1": {
"address_family": {
"ipv4": {
"instance": {
"1": {
"areas": {
"0.0.0.1": {
"sham_links": {
... | expected_output = {'vrf': {'VRF1': {'address_family': {'ipv4': {'instance': {'1': {'areas': {'0.0.0.1': {'sham_links': {'10.21.33.33 10.151.22.22': {'cost': 111, 'dcbitless_lsa_count': 1, 'donotage_lsa': 'not allowed', 'dead_interval': 13, 'demand_circuit': True, 'hello_interval': 3, 'hello_timer': '00:00:00:772', 'if_... |
pkgname = "cargo-bootstrap"
pkgver = "1.60.0"
pkgrel = 0
# satisfy runtime dependencies
hostmakedepends = ["curl"]
depends = ["!cargo"]
pkgdesc = "Bootstrap binaries of Rust package manager"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT OR Apache-2.0"
url = "https://rust-lang.org"
source = f"https://ftp.oct... | pkgname = 'cargo-bootstrap'
pkgver = '1.60.0'
pkgrel = 0
hostmakedepends = ['curl']
depends = ['!cargo']
pkgdesc = 'Bootstrap binaries of Rust package manager'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT OR Apache-2.0'
url = 'https://rust-lang.org'
source = f'https://ftp.octaforge.org/chimera/distfiles/ca... |
# m=wrf_hydro_ens_sim.members[0]
# dir(m)
# Change restart frequency to hourly in hydro namelist
att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'rst_dt')
# The values can be a scalar (uniform across the ensemble) or a list of length N (ensemble size).
values = 60
wrf_hydro_ens_sim.set_member_diffs(att_tuple, valu... | att_tuple = ('base_hydro_namelist', 'hydro_nlist', 'rst_dt')
values = 60
wrf_hydro_ens_sim.set_member_diffs(att_tuple, values)
wrf_hydro_ens_sim.member_diffs
[mm.base_hydro_namelist['hydro_nlist']['rst_dt'] for mm in wrf_hydro_ens_sim.members]
att_tuple = ('base_hrldas_namelist', 'noahlsm_offline', 'restart_frequency_h... |
def main () :
i = 1
fib = 1
target = 10
temp = 0
while (i < target) :
temp = fib
fib += temp
i+=1
print(fib)
return 0
if __name__ == '__main__':
main()
| def main():
i = 1
fib = 1
target = 10
temp = 0
while i < target:
temp = fib
fib += temp
i += 1
print(fib)
return 0
if __name__ == '__main__':
main() |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
greed_p = 0
size_p = 0
count = 0
while greed_p < len(g) and size_p < len(s):
if g[greed_p] <= s[size_p]:
count += 1
greed_p ... | class Solution:
def find_content_children(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
greed_p = 0
size_p = 0
count = 0
while greed_p < len(g) and size_p < len(s):
if g[greed_p] <= s[size_p]:
count += 1
greed... |
data = {
"publication-date": {
"year": {
"value": "2020"},
"month": {"value": "01"}},
"short-description": "With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Androm... | data = {'publication-date': {'year': {'value': '2020'}, 'month': {'value': '01'}}, 'short-description': 'With a central surface brightness of 29.3 mag arcsec, and half-light radius of r_half=3.1^{+0.9}_{-1.1} kpc, Andromeda XIX (And XIX) is an extremely diffuse satellite of Andromeda.', 'external-ids': {'external-id': ... |
# This is a sample Python script.
def test_print_hi():
assert True
| def test_print_hi():
assert True |
hours = input('Enter Hours \n')
rate = input('Enter Rate\n')
hours = int(hours)
rate = float(rate)
if (hours <= 40):
pay = rate*hours
else:
extra_time = hours - 40
pay = (rate*hours) + ((rate*extra_time)/2)
print('Pay: ', pay)
| hours = input('Enter Hours \n')
rate = input('Enter Rate\n')
hours = int(hours)
rate = float(rate)
if hours <= 40:
pay = rate * hours
else:
extra_time = hours - 40
pay = rate * hours + rate * extra_time / 2
print('Pay: ', pay) |
def get_schema():
return {
'type': 'object',
'properties': {
'connections': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
... | def get_schema():
return {'type': 'object', 'properties': {'connections': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string'}, 'path': {'type': 'string'}, 'driver': {'type': 'string'}, 'server': {'type': 'string'}, 'database': {'type': 'string'}, 'name_col': {'type': 'string'}, '... |
def main():
mainFile = open("index.html", 'r', encoding='utf-8')
writeFile = open("index_pasted.html", 'w+', encoding='utf-8')
classId = 'class="internal"'
cssId = '<link rel='
for line in mainFile:
if (classId in line):
pasteScript(line, writeFile)
elif (cssId in line):... | def main():
main_file = open('index.html', 'r', encoding='utf-8')
write_file = open('index_pasted.html', 'w+', encoding='utf-8')
class_id = 'class="internal"'
css_id = '<link rel='
for line in mainFile:
if classId in line:
paste_script(line, writeFile)
elif cssId in line:... |
def main():
seed = 0x1234
e = [0x62d5, 0x7b27, 0xc5d4, 0x11c4, 0x5d67, 0xa356, 0x5f84,
0xbd67, 0xad04, 0x9a64, 0xefa6, 0x94d6, 0x2434, 0x0178]
flag = ""
for index in range(14):
for i in range(0x7f-0x20):
c = chr(0x20+i)
res = encode(c, index, seed)
if... | def main():
seed = 4660
e = [25301, 31527, 50644, 4548, 23911, 41814, 24452, 48487, 44292, 39524, 61350, 38102, 9268, 376]
flag = ''
for index in range(14):
for i in range(127 - 32):
c = chr(32 + i)
res = encode(c, index, seed)
if res == e[index]:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
file1=open('data/u_Lvoid_20.txt',encoding='utf-8')
file2=open('temp2/void.txt','w',encoding='utf-8')
count=0
for line in file1:
count=count+1
if(line[0]=='R'):# 'line' here is a string
line_list=line.split( ) # 'line_list' is a list of small strings=['R4... | file1 = open('data/u_Lvoid_20.txt', encoding='utf-8')
file2 = open('temp2/void.txt', 'w', encoding='utf-8')
count = 0
for line in file1:
count = count + 1
if line[0] == 'R':
line_list = line.split()
branch = line_list[0].split('-')
branch0 = branch[0].split('R')
branch[0] = branc... |
def climbingLeaderboard(scores, alice):
scores = list(reversed(sorted(set(scores))))
r, rank = len(scores), []
for a in alice:
while (r > 0) and (a >= scores[r - 1]):
r -= 1
rank.append(r + 1)
return rank | def climbing_leaderboard(scores, alice):
scores = list(reversed(sorted(set(scores))))
(r, rank) = (len(scores), [])
for a in alice:
while r > 0 and a >= scores[r - 1]:
r -= 1
rank.append(r + 1)
return rank |
screen = {
"bg": "blue",
"rows": 0,
"columns": 0,
"columnspan": 4,
"padx": 5,
"pady": 5,
}
input = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
button = {
"bg": "blue",
"fg": "red",
"fs": "20px",
}
| screen = {'bg': 'blue', 'rows': 0, 'columns': 0, 'columnspan': 4, 'padx': 5, 'pady': 5}
input = {'bg': 'blue', 'fg': 'red', 'fs': '20px'}
button = {'bg': 'blue', 'fg': 'red', 'fs': '20px'} |
# 3. Single layered 4 inputs and 3 outputs(Looping)
mInputs = [3, 4, 1, 2]
mWeights = [[0.2, -0.4, 0.6, 0.4],
[0.4, 0.3, -0.1, 0.8],
[0.7, 0.6, 0.3, -0.3]]
mBias1 = [3, 4, 2]
layer_output = []
for neuron_weights, neuron_bias in zip(mWeights, mBias1):
neuron_output = 0
for n_inputs, ... | m_inputs = [3, 4, 1, 2]
m_weights = [[0.2, -0.4, 0.6, 0.4], [0.4, 0.3, -0.1, 0.8], [0.7, 0.6, 0.3, -0.3]]
m_bias1 = [3, 4, 2]
layer_output = []
for (neuron_weights, neuron_bias) in zip(mWeights, mBias1):
neuron_output = 0
for (n_inputs, n_weights) in zip(mInputs, neuron_weights):
neuron_output += n_inpu... |
# reading 2 numbers from the keyboard and printing maximum value
r = int(input("Enter the first number: "))
s = int(input("Enter the second number: "))
x = r if r>s else s
print(x)
| r = int(input('Enter the first number: '))
s = int(input('Enter the second number: '))
x = r if r > s else s
print(x) |
def main():
STRING = "aababbabbaaba"
compressed = compress(STRING)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
def compress(string):
encode = {} # string -> code
known = ""
count = 0
result = []
for letter in string:
if known + letter in... | def main():
string = 'aababbabbaaba'
compressed = compress(STRING)
print(compressed)
decompressed = decompress(compressed)
print(decompressed)
def compress(string):
encode = {}
known = ''
count = 0
result = []
for letter in string:
if known + letter in encode:
... |
# When one class does the work of two, awkwardness results.
class Person:
def __init__(self, name, office_area_code, office_number):
self.name = name
self.office_area_code = office_area_code
self.office_number = office_number
def telephone_number(self):
return "%d-%d" % (s... | class Person:
def __init__(self, name, office_area_code, office_number):
self.name = name
self.office_area_code = office_area_code
self.office_number = office_number
def telephone_number(self):
return '%d-%d' % (self.office_area_code, self.office_number)
if __name__ == '__main_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class OpenError(StandardError):
def __init__(self, error_code, error, error_info):
self.error_code = error_code
self.error = error
self.error_info = error_info
StandardError.__init__(self, error)
def __str__(self):
return 'Erro... | class Openerror(StandardError):
def __init__(self, error_code, error, error_info):
self.error_code = error_code
self.error = error
self.error_info = error_info
StandardError.__init__(self, error)
def __str__(self):
return 'Error: %s: %s, request: %s' % (self.error_code,... |
table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58**i
return (r - add) ^ xor
def enc(x):
x = (x ^ xor) + add... | table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58 ** i
return r - add ^ xor
def enc(x):
x = (x ^ xor) + add
... |
#
# @lc app=leetcode id=838 lang=python3
#
# [838] Push Dominoes
#
# @lc code=start
class Solution:
def pushDominoes(self, dominoes: str) -> str:
l = 0
ans = []
dominoes = 'L' + dominoes + 'R'
for r in range(1, len(dominoes)):
if dominoes[r] == '.':
conti... | class Solution:
def push_dominoes(self, dominoes: str) -> str:
l = 0
ans = []
dominoes = 'L' + dominoes + 'R'
for r in range(1, len(dominoes)):
if dominoes[r] == '.':
continue
cnt = r - l - 1
if l > 0:
ans.append(do... |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_univals(node):
if node.right is None and node.left is None:
return node.val, True, 1
l_val, l_is_unival, l_univals = count_univals(node.left)
r_val... | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_univals(node):
if node.right is None and node.left is None:
return (node.val, True, 1)
(l_val, l_is_unival, l_univals) = count_univals(node.left)
(r_... |
# Python Tuples
# Ordered, Immutable collection of items which allows Duplicate Members
# We can put the data, which will not change throughout the program, in a Tuple
# Tuples can be called as "Immutable Python Lists" or "Constant Python Lists"
employeeTuple = ("Sam", "Sam" "Mike", "John", "Harry", "Tom", "Sean", "Ju... | employee_tuple = ('Sam', 'SamMike', 'John', 'Harry', 'Tom', 'Sean', 'Justin')
print(type(employeeTuple))
print(isinstance(employeeTuple, tuple))
for employee_name in employeeTuple:
print('Employee: ' + employeeName)
print('**********************************************************')
print(employeeTuple[0])
print(le... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
class BuiltinOperator(object):
ADD = 0
AVERAGE_POOL_2D = 1
CONCATENATION = 2
CONV_2D = 3
DEPTHWISE_CONV_2D = 4
EMBEDDING_LOOKUP = 7
FULLY_CONNECTED = 9
HASHTABLE_LOOKUP = 10
L2_NORMALIZATION = ... | class Builtinoperator(object):
add = 0
average_pool_2_d = 1
concatenation = 2
conv_2_d = 3
depthwise_conv_2_d = 4
embedding_lookup = 7
fully_connected = 9
hashtable_lookup = 10
l2_normalization = 11
l2_pool_2_d = 12
local_response_normalization = 13
logistic = 14
lsh_... |
class Table(object):
def __init__(self, name):
self.name = name
self.columns = []
def createColumn(self, column):
self.columns.append(column)
def readColumn(self, name):
for value in self.columns:
if value.name == name:
return value
... | class Table(object):
def __init__(self, name):
self.name = name
self.columns = []
def create_column(self, column):
self.columns.append(column)
def read_column(self, name):
for value in self.columns:
if value.name == name:
return value
def u... |
class Config:
api_host = "https://api.frame.io"
default_page_size = 50
default_concurrency = 5
| class Config:
api_host = 'https://api.frame.io'
default_page_size = 50
default_concurrency = 5 |
# Introductory examples
name = 'Maurizio'
surname = 'Petrelli'
print('-------------------------------------------------')
print('My name is {}'.format(name))
print('-------------------------------------------------')
print('My name is {} and my surname is {}'.format(name, surname))
print('------------------------------... | name = 'Maurizio'
surname = 'Petrelli'
print('-------------------------------------------------')
print('My name is {}'.format(name))
print('-------------------------------------------------')
print('My name is {} and my surname is {}'.format(name, surname))
print('-------------------------------------------------')
pi... |
'''
Created on Dec 18, 2016
@author: rch
'''
| """
Created on Dec 18, 2016
@author: rch
""" |
#!/usr/bin/env python
# coding=utf-8
class BaseException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return '<%s %s>' % (self.__class__.__name__, self.code)
| class Baseexception(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return '<%s %s>' % (self.__class__.__name__, self.code) |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_cdecl',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompilerTool': {
'Calling... | {'targets': [{'target_name': 'test_cdecl', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvention': 0}}, 'sources': ['calling-convention.cc', 'calling-convention-cdecl.def']}, {'target_name': 'test_fastcall', 'type': 'loadable_module', 'msvs_settings': {'VCCLCompilerTool': {'CallingConvent... |
#
# PySNMP MIB module RBT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueEr... | def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueError
... |
# Homework #6. Loops
print("--- Task #1. 10 monkeys")
# Task #1. Write a program that output the following string: "1 monkey 2 monkeys ... 10 monkeys".
for x in range(1, 11):
if x == 1:
monkey = f"{x} monkey "
else:
monkey = monkey + f"{x} monkeys "
print(monkey.strip())
print("\n--- Task #2. Countdow... | print('--- Task #1. 10 monkeys')
for x in range(1, 11):
if x == 1:
monkey = f'{x} monkey '
else:
monkey = monkey + f'{x} monkeys '
print(monkey.strip())
print('\n--- Task #2. Countdown timer')
for x in range(10, 0, -1):
print(str(x) + ' seconds...')
print()
print('\n--- Task #3')
n = int(inp... |
#
# PySNMP MIB module TRANGO-APEX-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGO-APEX-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
# -*- coding: utf-8 -*-
i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3
| i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3 |
def process(N):
temp = str(N)
temp = temp.replace('4','2')
res1 = int(temp)
res2 = N-res1
return res1,res2
T = int(input())
for t in range(T):
N = int(input())
res1,res2 = process(N)
print('Case #{}: {} {}'.format(t+1,res1,res2)) | def process(N):
temp = str(N)
temp = temp.replace('4', '2')
res1 = int(temp)
res2 = N - res1
return (res1, res2)
t = int(input())
for t in range(T):
n = int(input())
(res1, res2) = process(N)
print('Case #{}: {} {}'.format(t + 1, res1, res2)) |
class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinke... | class T:
work_request = 1
work_reply = 2
reduce = 3
barrier = 4
token = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinked... |
# Types
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
# Exp = Union[Symbol, Exp]
def atom(token):
"Numbers become numbers; every other token i... | symbol = str
list = list
number = (int, float)
def atom(token):
"""Numbers become numbers; every other token is a symbol."""
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return symbol(token) |
def GetInfoMsg():
infoMsg = "This python snippet is triggered by the 'cmd' property.\r\n"
infoMsg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == "__main__":
print(GetInfoMsg()) | def get_info_msg():
info_msg = "This python snippet is triggered by the 'cmd' property.\r\n"
info_msg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == '__main__':
print(get_info_msg()) |
def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect
| def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect |
# Definition 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
class Solution:
def getLonelyNodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(no... | class Solution:
def get_lonely_nodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(node, is_lonely):
if node is None:
return
if is_lonely:
lonely_nodes.append(node.val)
if (node.left is None) ^ (node.right is None)... |
# -*- coding: utf-8 -*-
__title__ = "flloat"
__description__ = "A Python implementation of the FLLOAT library."
__url__ = "https://github.com/marcofavorito/flloat.git"
__version__ = "1.0.0a0"
__author__ = "Marco Favorito"
__author_email__ = "marco.favorito@gmail.com"
__license__ = "MIT license"
__copyright__ = "2019 M... | __title__ = 'flloat'
__description__ = 'A Python implementation of the FLLOAT library.'
__url__ = 'https://github.com/marcofavorito/flloat.git'
__version__ = '1.0.0a0'
__author__ = 'Marco Favorito'
__author_email__ = 'marco.favorito@gmail.com'
__license__ = 'MIT license'
__copyright__ = '2019 Marco Favorito' |
class Solution:
def rotatedDigits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
els... | class Solution:
def rotated_digits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
else... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.