content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
table = []
n, m = map(int, input().split())
for i in range(n):
row = list(map(int, input().split()))
table.append(row)
k = int(input())
table.sort(key=lambda x: x[k])
for row in table:
print(*row)
| table = []
(n, m) = map(int, input().split())
for i in range(n):
row = list(map(int, input().split()))
table.append(row)
k = int(input())
table.sort(key=lambda x: x[k])
for row in table:
print(*row) |
class Company:
def __init__(self):
self.ticker = ''
self.name = ''
self.rating = ''
self.rating_date = ''
self.piotroski_f_score = '0.0'
self.base_link = ''
self.p_e = '0.0'
self.p_bv = '0.0'
self.p_bv_g = '0.0'
self.p_s = '0.0'
... | class Company:
def __init__(self):
self.ticker = ''
self.name = ''
self.rating = ''
self.rating_date = ''
self.piotroski_f_score = '0.0'
self.base_link = ''
self.p_e = '0.0'
self.p_bv = '0.0'
self.p_bv_g = '0.0'
self.p_s = '0.0'
... |
__version__ = '0.3.0'
__author__ = 'Ian Dennis Miller'
__email__ = 'iandennismiller@gmail.com'
__url__ = 'http://diamond-methods.org/puppet-diamond.html'
| __version__ = '0.3.0'
__author__ = 'Ian Dennis Miller'
__email__ = 'iandennismiller@gmail.com'
__url__ = 'http://diamond-methods.org/puppet-diamond.html' |
__author__ = 'Pat and Tony'
#abstract class for the Observer interface
class Observer(object):
#must be implemented in all subclasses
def notify(self, msg):
pass | __author__ = 'Pat and Tony'
class Observer(object):
def notify(self, msg):
pass |
def solution(N, A):
result = [0] * N
max_num, max_counter = 0, 0
for num in A:
if num == N + 1:
max_counter = max_num
else:
result[num-1] = max(result[num-1], max_counter)
result[num-1] += 1
max_num = max(max_num, result[num-1])
for ... | def solution(N, A):
result = [0] * N
(max_num, max_counter) = (0, 0)
for num in A:
if num == N + 1:
max_counter = max_num
else:
result[num - 1] = max(result[num - 1], max_counter)
result[num - 1] += 1
max_num = max(max_num, result[num - 1])
... |
def can_build(env, platform):
return env["tools"] and env["module_raycast_enabled"]
def configure(env):
pass
| def can_build(env, platform):
return env['tools'] and env['module_raycast_enabled']
def configure(env):
pass |
'''
A test suite of unit tests for the plantpredict-python package.
It is assumed that the plantpredict package is in the python path, and `mock` is installed. Note: mock could not be installed through conda, used pip instead.
To run all tests, from the `tests` directory, do:
```
python -m unittest discover -v
```
... | """
A test suite of unit tests for the plantpredict-python package.
It is assumed that the plantpredict package is in the python path, and `mock` is installed. Note: mock could not be installed through conda, used pip instead.
To run all tests, from the `tests` directory, do:
```
python -m unittest discover -v
```
... |
class Animal:
fur_color = "Orange"
def speak(self):
raise NotImplementedError
def eat(self):
pass
def chase(self):
pass
class HouseCat(Animal):
def speak(self):
print("Meeeeowwww")
cat = HouseCat()
cat.speak()
| class Animal:
fur_color = 'Orange'
def speak(self):
raise NotImplementedError
def eat(self):
pass
def chase(self):
pass
class Housecat(Animal):
def speak(self):
print('Meeeeowwww')
cat = house_cat()
cat.speak() |
#// 26 bits block id, 8 bits shift distance, 4 bits last key byte, 5 bits storage, 21 bits value
print( " DELME sz 1751672936 keysz 26728 b 9816750e idx 422567")
def prt(b):
print( " block id ", b >> 38 )
print( " shift ", (b >> 30) & 0xFF )
print( " key ", (b >> 26) & 0xF )
print( " storage ", (b >... | print(' DELME sz 1751672936 keysz 26728 b 9816750e idx 422567')
def prt(b):
print(' block id ', b >> 38)
print(' shift ', b >> 30 & 255)
print(' key ', b >> 26 & 15)
print(' storage ', b >> 21 & 31)
print(' value ', b >> 0 & 2097151)
prt(2551602861)
prt(3625344685) |
#Websites to crawling For the News Paper, with white list and black list
WhiteListURLS = {
'Hoy': 'http://hoy.com.do/encuestas/',
'Listin Diario': 'https://www.listindiario.com/encuestas',
'La Informacion': 'http://www.lainformacion.com.do/modulos/encuestas/encuestas_anteriores.php?idEnc=744',
'La Bazuc... | white_list_urls = {'Hoy': 'http://hoy.com.do/encuestas/', 'Listin Diario': 'https://www.listindiario.com/encuestas', 'La Informacion': 'http://www.lainformacion.com.do/modulos/encuestas/encuestas_anteriores.php?idEnc=744', 'La Bazuca': 'http://www.labazuca.com/encuestas/', 'El Nacional': 'http://elnacional.com.do/encue... |
def mod_brightness(colour, modifier):
red = min(int(((colour & 0xff0000) >> 16) * modifier), 0xff)
green = min(int(((colour & 0x00ff00) >> 8) * modifier), 0xff)
blue = min(int((colour & 0x0000ff) * modifier), 0xff)
return red << 16 | green << 8 | blue
def int_scale_flag(flag_name, max_size)... | def mod_brightness(colour, modifier):
red = min(int(((colour & 16711680) >> 16) * modifier), 255)
green = min(int(((colour & 65280) >> 8) * modifier), 255)
blue = min(int((colour & 255) * modifier), 255)
return red << 16 | green << 8 | blue
def int_scale_flag(flag_name, max_size):
flag = bmp_data(f... |
def Musical_era_question_1():
score_number = 0
what_key_str = "minor"
#print ("Can you identify this key?")
a=input("Can you identify this key? \n Question 1: What is the key of this song?")
#import audio file of We're Going Wrong here
if "minor" in a:
score_number = 1
return sco... | def musical_era_question_1():
score_number = 0
what_key_str = 'minor'
a = input('Can you identify this key? \n Question 1: What is the key of this song?')
if 'minor' in a:
score_number = 1
return (score_number, what_key_str, 'Correct!')
else:
score_number = 0
return (... |
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print ("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee",
"Corn", "Banana", "Girl", "Boy"]
while len (stuff) != 10:
next_one = more_stuff.pop()
pri... | ten_things = 'Apples Oranges Crows Telephone Light Sugar'
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
while len(stuff) != 10:
next_one = more_stuff.pop()
print('Adding ', next_... |
def _generate_variables(repository_ctx, build_info):
repository_ctx.template(
"generate_variables.py",
repository_ctx.path(Label("//support/bazel:generate_variables.py")),
{},
)
python_interpreter = repository_ctx.attr.python_interpreter
if repository_ctx.attr.python_interpreter... | def _generate_variables(repository_ctx, build_info):
repository_ctx.template('generate_variables.py', repository_ctx.path(label('//support/bazel:generate_variables.py')), {})
python_interpreter = repository_ctx.attr.python_interpreter
if repository_ctx.attr.python_interpreter_target != None:
python_... |
def check_bc(self, p=None):
# check that boundary conditions are satisfied
if self.nconstraints == 0:
# no boundary conditions
return True
if p is None:
# use random parameter vector
p = np.random.randn(self.dof)
coeff = self.get_block_coeff(p)
lhs = np.polyval(... | def check_bc(self, p=None):
if self.nconstraints == 0:
return True
if p is None:
p = np.random.randn(self.dof)
coeff = self.get_block_coeff(p)
lhs = np.polyval(coeff, 0)[1:]
rhs = list(map(np.polyval, coeff.T, np.diff(self.breakpoints[:-1])))
assert np.allclose(lhs, rhs) |
_exports = [
"all_resources",
"carbon_per_mmbtu",
"carbon_per_mwh",
"carbon_resources",
"clean_resources",
"label2type",
"nox_per_mwh",
"renewable_resources",
"so2_per_mwh",
"type2color",
"type2hatchcolor",
"type2label",
]
type2color = {
"wind": "xkcd:green",
"so... | _exports = ['all_resources', 'carbon_per_mmbtu', 'carbon_per_mwh', 'carbon_resources', 'clean_resources', 'label2type', 'nox_per_mwh', 'renewable_resources', 'so2_per_mwh', 'type2color', 'type2hatchcolor', 'type2label']
type2color = {'wind': 'xkcd:green', 'solar': 'xkcd:amber', 'hydro': 'xkcd:light blue', 'ng': 'xkcd:o... |
def is_divisible(num, divs):
return all([num % div == 0 for div in divs])
# MAIN
start = int(input('Start of range: '))
end = int(input('End of range: '))
divs = list(
map(
lambda i: int(i),
input('Type in the divisors, separated by commas: ').split(',')
)
)
divisibles = [n for n in range(start, end) if is_div... | def is_divisible(num, divs):
return all([num % div == 0 for div in divs])
start = int(input('Start of range: '))
end = int(input('End of range: '))
divs = list(map(lambda i: int(i), input('Type in the divisors, separated by commas: ').split(',')))
divisibles = [n for n in range(start, end) if is_divisible(n, divs)]... |
coordinates_E0E1E1 = ((126, 114),
(126, 116), (126, 117), (126, 118), (127, 114), (127, 120), (128, 114), (128, 115), (128, 119), (128, 121), (129, 105), (129, 108), (129, 115), (129, 120), (129, 121), (130, 101), (130, 103), (130, 104), (130, 109), (130, 120), (130, 121), (131, 101), (131, 105), (131, 106), (131, 10... | coordinates_e0_e1_e1 = ((126, 114), (126, 116), (126, 117), (126, 118), (127, 114), (127, 120), (128, 114), (128, 115), (128, 119), (128, 121), (129, 105), (129, 108), (129, 115), (129, 120), (129, 121), (130, 101), (130, 103), (130, 104), (130, 109), (130, 120), (130, 121), (131, 101), (131, 105), (131, 106), (131, 10... |
with open('input.txt', 'r') as file:
start, stop = file.read().split('-')
start = int(start)
stop = int(stop)
result_1 = 0
result_2 = 0
for pword in range(start, stop):
isdouble = False
num = [int(i) for i in str(pword)]
if num == sorted(num):
counts = {str(pword).count(x) for x in str(pword)}... | with open('input.txt', 'r') as file:
(start, stop) = file.read().split('-')
start = int(start)
stop = int(stop)
result_1 = 0
result_2 = 0
for pword in range(start, stop):
isdouble = False
num = [int(i) for i in str(pword)]
if num == sorted(num):
counts = {str(pword).count(x) for x in str(pword)}... |
#print("Hello World")
#temperature = int(input("What is the temperature outside?"))
#if temperature > 80:
#print("Turn on the AC.")
#else:
#print("Open the Windows.")
score = int(input("What is your test score?"))
if score >= 90:
print('Your grade is an A.')
elif score>= 80:
print('Your grade is a B'... | score = int(input('What is your test score?'))
if score >= 90:
print('Your grade is an A.')
elif score >= 80:
print('Your grade is a B')
elif score >= 70:
print('Your grade is a C')
elif score >= 60:
print('Your grade is a D')
else:
print('You Suck,, Drop Out of School') |
class ZenviaTokenNotFound(Exception):
pass
class ZenviaUrlNotFound(Exception):
pass
class InvalidArgument(Exception):
pass
| class Zenviatokennotfound(Exception):
pass
class Zenviaurlnotfound(Exception):
pass
class Invalidargument(Exception):
pass |
def _check_box_size(size):
if int(size) <= 0:
raise ValueError(f"Invalid box size. Must be larger than 0")
def _check_border(size):
if int(size) <= 0:
raise ValueError(f"Invalid border value. Must be larger than 0")
class QRCode:
def __init__(self, box_size=10, border=2):
_check_... | def _check_box_size(size):
if int(size) <= 0:
raise value_error(f'Invalid box size. Must be larger than 0')
def _check_border(size):
if int(size) <= 0:
raise value_error(f'Invalid border value. Must be larger than 0')
class Qrcode:
def __init__(self, box_size=10, border=2):
_check... |
n = int(input())
cnt = 0
for i in range(2,11):
n2 = n
L = []
while(n2 > 0):
L.append(n2%i)
n2//=i
if L == L[::-1]:
print(i,end=" ")
for k in L:
print(k, end = "")
print()
cnt+=1
if cnt == 0:
print("NIE") | n = int(input())
cnt = 0
for i in range(2, 11):
n2 = n
l = []
while n2 > 0:
L.append(n2 % i)
n2 //= i
if L == L[::-1]:
print(i, end=' ')
for k in L:
print(k, end='')
print()
cnt += 1
if cnt == 0:
print('NIE') |
#
# PySNMP MIB module TIMETRA-BSX-NG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-BSX-NG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:17:06 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')
(single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
class Solution:
def scoreOfParentheses(self, S: str) -> int:
sLen = len(S)
if sLen == 0:
return 0
elif sLen == 1:
# throw out error message
pass
return 0
else:
sList = []
bgnIdx = 0
num = 0
... | class Solution:
def score_of_parentheses(self, S: str) -> int:
s_len = len(S)
if sLen == 0:
return 0
elif sLen == 1:
pass
return 0
else:
s_list = []
bgn_idx = 0
num = 0
while True:
if... |
class Solution:
def firstUniqChar(self, s: str) -> int:
dicti = {}
for char in s:
if char not in dicti:
dicti[char] = 0
dicti[char] += 1
for index, char in enumerate(s):
if dicti[char] == 1:
return index
return -... | class Solution:
def first_uniq_char(self, s: str) -> int:
dicti = {}
for char in s:
if char not in dicti:
dicti[char] = 0
dicti[char] += 1
for (index, char) in enumerate(s):
if dicti[char] == 1:
return index
return ... |
# noinspection PyUnusedLocal
# friend_name = unicode string
def hello(friend_name):
if not isinstance(friend_name, str):
raise ValueError("Invalid input")
return f"Hello, {friend_name}!"
| def hello(friend_name):
if not isinstance(friend_name, str):
raise value_error('Invalid input')
return f'Hello, {friend_name}!' |
# person = dict(first_name="Bob", last_name="Smith")
person = {
"first_name": "Bob",
"last_name": "Smith",
"age": 34,
"jobs": {
"programmer": "Sr. Developer",
"crochet": "Magazine Editor for Crocheting"
}
}
# person["jobs"]["programmer"]
# person = dict([
# ("first_name", "B... | person = {'first_name': 'Bob', 'last_name': 'Smith', 'age': 34, 'jobs': {'programmer': 'Sr. Developer', 'crochet': 'Magazine Editor for Crocheting'}}
for key in person:
print(key + ': ' + str(person[key])) |
k, q = map(int, input().split())
dp = [[0.0 for i in range(k + 1)] for j in range(10000)]
dp[0][0] = 1.0
for i in range(1, 10000):
for j in range(1, k + 1):
dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k
for t in range(q):
p = int(input())
for i in range(10000):
... | (k, q) = map(int, input().split())
dp = [[0.0 for i in range(k + 1)] for j in range(10000)]
dp[0][0] = 1.0
for i in range(1, 10000):
for j in range(1, k + 1):
dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k
for t in range(q):
p = int(input())
for i in range(10000):
if p ... |
def readlist(file="day_05/input.txt"):
with open(file, "r") as f:
return [int(char) for char in f.readline().split(",")]
def parse_instruction(instruction):
sint = str(instruction).zfill(5)
parm3 = bool(int(sint[0]))
parm2 = bool(int(sint[1]))
parm1 = bool(int(sint[2]))
op = int(sint[-... | def readlist(file='day_05/input.txt'):
with open(file, 'r') as f:
return [int(char) for char in f.readline().split(',')]
def parse_instruction(instruction):
sint = str(instruction).zfill(5)
parm3 = bool(int(sint[0]))
parm2 = bool(int(sint[1]))
parm1 = bool(int(sint[2]))
op = int(sint[-2... |
def cantApariciones(letra, cadena):
cant=0
for i in range(len(cadena)):
if (letra==cadena[i]):
cant+=1
return (cant)
def imprimeCantApariciones(cadena):
listaAparecidos=[]
for i in range(len(cadena)):
letra=cadena[i]
if (cantApariciones(letra,listaAp... | def cant_apariciones(letra, cadena):
cant = 0
for i in range(len(cadena)):
if letra == cadena[i]:
cant += 1
return cant
def imprime_cant_apariciones(cadena):
lista_aparecidos = []
for i in range(len(cadena)):
letra = cadena[i]
if cant_apariciones(letra, listaApar... |
# _*_ coding: utf-8 _*_
#
# Package: bookstore.src.core.repository.databases
__all__ = ["book_repository", "db_repository", "mysql_repository"]
| __all__ = ['book_repository', 'db_repository', 'mysql_repository'] |
mock_history_data = {
"coord": [50.0, 50.0],
"list": [
{
"main": {"aqi": 2},
"components": {
"co": 270.367,
"no": 5.867,
"no2": 43.184,
"o3": 4.783,
"so2": 14.544,
"pm2_5": 13.448,
... | mock_history_data = {'coord': [50.0, 50.0], 'list': [{'main': {'aqi': 2}, 'components': {'co': 270.367, 'no': 5.867, 'no2': 43.184, 'o3': 4.783, 'so2': 14.544, 'pm2_5': 13.448, 'pm10': 15.524, 'nh3': 0.289}, 'dt': 1606482000}, {'main': {'aqi': 2}, 'components': {'co': 280.38, 'no': 8.605, 'no2': 42.155, 'o3': 2.459, 's... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: ClimbingStairs.py
# @Author: olenji - lionhe0119@hotmail.com
# @Description:
# @Create: 2019-07-23 11:58
# @Last Modified: 2019-07-23 11:58
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
a = 1
... | class Solution:
def climb_stairs(self, n: int) -> int:
if n == 1:
return 1
a = 1
b = 2
for i in range(n):
(b, a) = (a + b, b)
return b
if __name__ == '__main__':
s = solution()
print(s.climbStairs(10)) |
word = 'banana'
count = 0
for letter in word:
if letter == 'n':
count = count + 1
print(count) | word = 'banana'
count = 0
for letter in word:
if letter == 'n':
count = count + 1
print(count) |
n = int(input())
left_dp = [1] * (n + 1)
right_dp = [1] * (n + 1)
arr = list(map(int, input().split()))
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i]:
left_dp[i] = max(left_dp[i], left_dp[j] + 1)
for i in range(n - 2, -1, -1):
for j in range(n - 1, i, -1):
if arr[j]... | n = int(input())
left_dp = [1] * (n + 1)
right_dp = [1] * (n + 1)
arr = list(map(int, input().split()))
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i]:
left_dp[i] = max(left_dp[i], left_dp[j] + 1)
for i in range(n - 2, -1, -1):
for j in range(n - 1, i, -1):
if arr[j] < a... |
#encoding:utf-8
subreddit = 'ani_bm'
t_channel = '@cahaf_avir'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'ani_bm'
t_channel = '@cahaf_avir'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
class Computer:
def __init__(self,name,size):
self.brand = name
self.size = size
class Laptop(Computer):
def __init__(self,name,size,model):
super().__init__(name,size)
self.model = model
if __name__ == "__main__":
abc = Laptop('MSI','15.6','GL Series')
print("... | class Computer:
def __init__(self, name, size):
self.brand = name
self.size = size
class Laptop(Computer):
def __init__(self, name, size, model):
super().__init__(name, size)
self.model = model
if __name__ == '__main__':
abc = laptop('MSI', '15.6', 'GL Series')
print('... |
def div_elem_list(list, divider):
try:
return [i /divider for i in list]
except ZeroDivisionError as e:
print(e, '- this is the error.')
return list
list = list(range(10))
divider = 0
print(div_elem_list(list, divider))
# que permiten que tu no vas a tener errores dentro
# ... | def div_elem_list(list, divider):
try:
return [i / divider for i in list]
except ZeroDivisionError as e:
print(e, '- this is the error.')
return list
list = list(range(10))
divider = 0
print(div_elem_list(list, divider)) |
# Object change log actions
OBJECT_CHANGE_ACTION_CREATE = 1
OBJECT_CHANGE_ACTION_UPDATE = 2
OBJECT_CHANGE_ACTION_DELETE = 3
OBJECT_CHANGE_ACTION_CHOICES = (
(OBJECT_CHANGE_ACTION_CREATE, "Created"),
(OBJECT_CHANGE_ACTION_UPDATE, "Updated"),
(OBJECT_CHANGE_ACTION_DELETE, "Deleted"),
)
# User Actions Constan... | object_change_action_create = 1
object_change_action_update = 2
object_change_action_delete = 3
object_change_action_choices = ((OBJECT_CHANGE_ACTION_CREATE, 'Created'), (OBJECT_CHANGE_ACTION_UPDATE, 'Updated'), (OBJECT_CHANGE_ACTION_DELETE, 'Deleted'))
user_action_create = 1
user_action_edit = 2
user_action_delete = 3... |
class FileStructureHelper:
def __init__(self, run_settings):
self.run_settings = run_settings
def get_project_directory(self):
return self.run_settings.app_directory + '/projects/' + self.run_settings.project
def get_config_file_path(self):
return self.get_project_directory() + "/... | class Filestructurehelper:
def __init__(self, run_settings):
self.run_settings = run_settings
def get_project_directory(self):
return self.run_settings.app_directory + '/projects/' + self.run_settings.project
def get_config_file_path(self):
return self.get_project_directory() + '/... |
# The usual way
numbers = [1, 2, 3, 4, 5, 6]
new_numbers = []
for f in numbers:
new_num = f + 1
new_numbers.append(new_num)
print(new_numbers)
# 6 lines!!
# With list comperhension
numbers = [1, 2, 3, 4, 5, 6]
new_numbers = [n + 1 for n in numbers]
print(new_numbers)
# 3 lines!!
# Using list comperhension wit... | numbers = [1, 2, 3, 4, 5, 6]
new_numbers = []
for f in numbers:
new_num = f + 1
new_numbers.append(new_num)
print(new_numbers)
numbers = [1, 2, 3, 4, 5, 6]
new_numbers = [n + 1 for n in numbers]
print(new_numbers)
range_list = [item * 2 for item in range(1, 5)]
names = ['Alex', 'Beth', 'Dave', 'Carolinnie', 'da... |
def sum_numbers(num1, num2):
return num1 + num2
def multiply_numbers(num1, num2):
return num1 * num2
def func_executor(*args):
results = []
for arg in args:
func, nums = arg
results.append(func(*nums))
return results
print(func_executor((sum_numbers, (1, 2)), (multiply_number... | def sum_numbers(num1, num2):
return num1 + num2
def multiply_numbers(num1, num2):
return num1 * num2
def func_executor(*args):
results = []
for arg in args:
(func, nums) = arg
results.append(func(*nums))
return results
print(func_executor((sum_numbers, (1, 2)), (multiply_numbers, (... |
class Solution:
def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
if not mat: return []
m = len(mat)
n = len(mat[0])
get = lambda i, j: mat[i][j] if 0 <= i < m and 0 <= j < n else 0
row = lambda i, j: sum([get(i, y) for y in range(j - K, j + K + 1)]... | class Solution:
def matrix_block_sum(self, mat: List[List[int]], K: int) -> List[List[int]]:
if not mat:
return []
m = len(mat)
n = len(mat[0])
get = lambda i, j: mat[i][j] if 0 <= i < m and 0 <= j < n else 0
row = lambda i, j: sum([get(i, y) for y in range(j - K... |
'''Starlark rule for packaging Python 3 Google Cloud Functions.'''
SRC_ZIP_EXTENSION = 'zip'
SRC_PY_EXTENSION = 'py'
MEMORY_VALUES = [
128, 256, 512, 1024, 2048, 4096,
]
MAX_TIMEOUT = 540
DEPLOY_SCRIPT_TEMPLATE = '''#!/usr/bin/env fish
set gcf_archive (status --current-filename | sed 's/\.fish$/\.zip/' | xargs real... | """Starlark rule for packaging Python 3 Google Cloud Functions."""
src_zip_extension = 'zip'
src_py_extension = 'py'
memory_values = [128, 256, 512, 1024, 2048, 4096]
max_timeout = 540
deploy_script_template = "#!/usr/bin/env fish\nset gcf_archive (status --current-filename | sed 's/\\.fish$/\\.zip/' | xargs realpath)\... |
#!/usr/bin/python3
#Every instance of this class, represents a single word found in a message.
class Word:
def __init__(self, word):
#The word itself.
self.word = word
#The number of times the word was found in a collection of ham messages.
self.inHam = 0
#The number of ... | class Word:
def __init__(self, word):
self.word = word
self.inHam = 0
self.inSpam = 0
self.hamProbability = 0
self.spamProbability = 0
def compute_ham_probability(self, number_of_keywords, my_sum):
self.hamProbability = float(1 + self.inHam) / float(number_of_ke... |
URL_LIST_ARTICLES = "../../../data/nytimes_news_articles.txt"
URL_BASE_ARTICLE = "../../../data/articles/nytimes"
URL_SPLIT_WORDS = "../../../data/split_words.json"
URL_SORT = "../../../data/sort.json"
URL_LIST_DICT = "../../../data/list_dict.json"
URL_LIST_DOCID = "../../../data/list_doc_id.json"
N_ARTICLE = 1000
| url_list_articles = '../../../data/nytimes_news_articles.txt'
url_base_article = '../../../data/articles/nytimes'
url_split_words = '../../../data/split_words.json'
url_sort = '../../../data/sort.json'
url_list_dict = '../../../data/list_dict.json'
url_list_docid = '../../../data/list_doc_id.json'
n_article = 1000 |
# 914000220
if not "cmd=o" in sm.getQRValue(21002):
sm.showFieldEffect("aran/tutorialGuide3")
sm.systemMessage("You can use a Command Attack by pressing both the arrow key and the attack key after a Consecutive Attack.")
sm.addQRValue(21002, "cmd=o") | if not 'cmd=o' in sm.getQRValue(21002):
sm.showFieldEffect('aran/tutorialGuide3')
sm.systemMessage('You can use a Command Attack by pressing both the arrow key and the attack key after a Consecutive Attack.')
sm.addQRValue(21002, 'cmd=o') |
class Curry:
def __init__(self, f, params=[], length=None):
self.f = f
self.len = f.__code__.co_argcount if length is None else length
self.params = params
def __call__(self, *a):
p = [*self.params, *a]
return self.f(*p) if len(p) >= self.len else Curry(self.f, p, self.... | class Curry:
def __init__(self, f, params=[], length=None):
self.f = f
self.len = f.__code__.co_argcount if length is None else length
self.params = params
def __call__(self, *a):
p = [*self.params, *a]
return self.f(*p) if len(p) >= self.len else curry(self.f, p, self.... |
'''
#basic data types
a = int(input())
b = float(input())
c = "I'm a boy"
print(c)
#casting------converting one datatype to another type
a = 1.22222
print(int(a))
#flowchartXXXX----conditionals----if/else
x = 'Ronaldo is better than Messi'
try:
print('Ronaldo' in s)
except:
print('sorry--not execute')
''... | """
#basic data types
a = int(input())
b = float(input())
c = "I'm a boy"
print(c)
#casting------converting one datatype to another type
a = 1.22222
print(int(a))
#flowchartXXXX----conditionals----if/else
x = 'Ronaldo is better than Messi'
try:
print('Ronaldo' in s)
except:
print('sorry--not execute')
""... |
class SubsystemA(object):
def operation_a1(self):
print("Operation a1")
def operation_a2(self):
print("Operation a2")
class SubsystemB(object):
def operation_b1(self):
print("Operation b1")
def operation_b2(self):
print("Operation b2")
class SubsystemC(object):
de... | class Subsystema(object):
def operation_a1(self):
print('Operation a1')
def operation_a2(self):
print('Operation a2')
class Subsystemb(object):
def operation_b1(self):
print('Operation b1')
def operation_b2(self):
print('Operation b2')
class Subsystemc(object):
... |
class Cashier:
def __init__(self, n, discount, products, prices):
self.n = n
self.now = n
self.dc = discount
self.pds = products
self.pcs = prices
def getBill(self, product, amount):
money = 0
for i in range(len(product)):
money += self.pcs[s... | class Cashier:
def __init__(self, n, discount, products, prices):
self.n = n
self.now = n
self.dc = discount
self.pds = products
self.pcs = prices
def get_bill(self, product, amount):
money = 0
for i in range(len(product)):
money += self.pcs[... |
s = b'abcdefgabc'
print(s)
print('c:', s.rindex(b'c'))
print('c:', s.index(b'c'))
#print('z:', s.rindex(b'z'))#ValueError: subsection not found
s = bytearray(b'abcdefgabc')
print(s)
print('c:', s.rindex(bytearray(b'c')))
print('c:', s.index(bytearray(b'c')))
#print('z:', s.rindex(bytearray(b'z')))#ValueError: subsecti... | s = b'abcdefgabc'
print(s)
print('c:', s.rindex(b'c'))
print('c:', s.index(b'c'))
s = bytearray(b'abcdefgabc')
print(s)
print('c:', s.rindex(bytearray(b'c')))
print('c:', s.index(bytearray(b'c'))) |
def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
vals[i], vals[i + 1] = vals[i + 1], vals[i]
# Yield gives the "state"
yield vals... | def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
(vals[i], vals[i + 1]) = (vals[i + 1], vals[i])
yield vals
vals = [int(x) for x in input().split... |
r = '\033[31m' # red
b = '\033[34m' # blue
g = '\033[32m' # green
y = '\033[33m' # yellow
f = '\33[m'
bb = '\033[44m' # backgournd blue
def tela(mensagem, colunatxt=5):
espaco = bb + ' ' + f
mensagem = bb + y + mensagem
for i in range(12):
print('')
if i == 5:
... | r = '\x1b[31m'
b = '\x1b[34m'
g = '\x1b[32m'
y = '\x1b[33m'
f = '\x1b[m'
bb = '\x1b[44m'
def tela(mensagem, colunatxt=5):
espaco = bb + ' ' + f
mensagem = bb + y + mensagem
for i in range(12):
print('')
if i == 5:
print(espaco * colunatxt + mensagem + espaco * (50 - (len(mensage... |
tst = int(input())
ids = [ int(w) for w in input().split(',') if w != 'x' ]
def wait_time(bus_id):
return (bus_id - tst % bus_id, bus_id)
min_id = min(map(wait_time, ids))
print(f"{min_id=}")
| tst = int(input())
ids = [int(w) for w in input().split(',') if w != 'x']
def wait_time(bus_id):
return (bus_id - tst % bus_id, bus_id)
min_id = min(map(wait_time, ids))
print(f'min_id={min_id!r}') |
# Aiden Baker
# 2/12/2021
# DoNow103
print(2*3*5)
print("abc")
print("abc"+"bde") | print(2 * 3 * 5)
print('abc')
print('abc' + 'bde') |
name = "ServerName"
user = "mongo"
japd = None
host = "hostname"
port = 27017
auth = False
auth_db = "admin"
use_arg = True
use_uri = False
repset = "ReplicaSet"
repset_hosts = ["host1:27017", "host2:27017"]
| name = 'ServerName'
user = 'mongo'
japd = None
host = 'hostname'
port = 27017
auth = False
auth_db = 'admin'
use_arg = True
use_uri = False
repset = 'ReplicaSet'
repset_hosts = ['host1:27017', 'host2:27017'] |
class GlobalConfig:
def __init__(self):
self.logger_name = "ecom"
self.log_level = "INFO"
self.vocab_filename = "products.vocab"
self.labels_filename = "labels.vocab"
self.model_filename = "classifier.mdl"
gconf = GlobalConfig()
| class Globalconfig:
def __init__(self):
self.logger_name = 'ecom'
self.log_level = 'INFO'
self.vocab_filename = 'products.vocab'
self.labels_filename = 'labels.vocab'
self.model_filename = 'classifier.mdl'
gconf = global_config() |
def fact(n):
if n > 0:
return (n*fact(n - 1))
else:
return 1
print(fact(5))
| def fact(n):
if n > 0:
return n * fact(n - 1)
else:
return 1
print(fact(5)) |
#!/usr/bin/env python3
class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self._... | class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self.__resource.metadata.name
... |
BOT_NAME = 'AmazonHeadSetScraping'
SPIDER_MODULES = ['AmazonHeadSetScraping.spiders']
NEWSPIDER_MODULE = 'AmazonHeadSetScraping.spiders'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
DOWNLOAD_DELAY = 3
DOWNLOAD_TIMEOUT = 30
RANDOMIZE_DOWNLOAD_DELAY = True
REACTOR_THRE... | bot_name = 'AmazonHeadSetScraping'
spider_modules = ['AmazonHeadSetScraping.spiders']
newspider_module = 'AmazonHeadSetScraping.spiders'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
download_delay = 3
download_timeout = 30
randomize_download_delay = True
reactor_threadpo... |
#!/usr/bin/python
DIR = "data_tmp/"
FILES = {}
FILES['20_avg'] = []
FILES['40_avg'] = []
FILES['50_avg'] = []
FILES['60_avg'] = []
FILES['80_avg'] = []
FILES['20_opt'] = []
FILES['40_opt'] = []
FILES['50_opt'] = []
FILES['60_opt'] = []
FILES['80_opt'] = []
FILES['20_avg'].append("04_attk2_avg20_20_test")
FILES['20_a... | dir = 'data_tmp/'
files = {}
FILES['20_avg'] = []
FILES['40_avg'] = []
FILES['50_avg'] = []
FILES['60_avg'] = []
FILES['80_avg'] = []
FILES['20_opt'] = []
FILES['40_opt'] = []
FILES['50_opt'] = []
FILES['60_opt'] = []
FILES['80_opt'] = []
FILES['20_avg'].append('04_attk2_avg20_20_test')
FILES['20_avg'].append('04_attk2... |
def list_of_lists(l, n):
q = len(l) // n
r = len(l) % n
if r == 0:
return [l[i * n:(i + 1) * n] for i in range(q)]
else:
return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)]
| def list_of_lists(l, n):
q = len(l) // n
r = len(l) % n
if r == 0:
return [l[i * n:(i + 1) * n] for i in range(q)]
else:
return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)] |
def find_common_number(*args):
result = args[0]
for arr in args:
result = insect_array(result, arr)
return result
def union_array(arr1, arr2):
return list(set.union(arr1, arr2))
def insect_array(arr1, arr2):
return list(set(arr1) & set(arr2))
arr1 = [1,5,10,20,40,80]
arr2 = [6,27,20,80,100]
arr3 = [... | def find_common_number(*args):
result = args[0]
for arr in args:
result = insect_array(result, arr)
return result
def union_array(arr1, arr2):
return list(set.union(arr1, arr2))
def insect_array(arr1, arr2):
return list(set(arr1) & set(arr2))
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 27, 20... |
# Question 2
# Convert all units of time into seconds.
day = float(input("Enter number of days: "))
hour = float(input("Enter number of hours: "))
minute = float(input("Enter number of minutes: "))
second = float(input("Enter number of seconds: "))
day = day * 3600 * 24
hour *= 3600
minute *= 60
second = day + hour + ... | day = float(input('Enter number of days: '))
hour = float(input('Enter number of hours: '))
minute = float(input('Enter number of minutes: '))
second = float(input('Enter number of seconds: '))
day = day * 3600 * 24
hour *= 3600
minute *= 60
second = day + hour + minute + second
print('Time: ' + str(round(second, 2)) +... |
class QueueMember:
def __init__(self, number):
self.number = number
self.next = self
self.prev = self
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def set_prev(self, prev):
self.prev = prev
def get_prev(self):
... | class Queuemember:
def __init__(self, number):
self.number = number
self.next = self
self.prev = self
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def set_prev(self, prev):
self.prev = prev
def get_prev(self):
... |
class AgedPeer:
def __init__(self, address, age=0):
self.address = address
self.age = age
def __eq__(self, other):
if isinstance(other, AgedPeer):
return self.address == other.address
return False
@staticmethod
def from_json(json_object):
return AgedPeer(json_object['address'], json_object['age']) | class Agedpeer:
def __init__(self, address, age=0):
self.address = address
self.age = age
def __eq__(self, other):
if isinstance(other, AgedPeer):
return self.address == other.address
return False
@staticmethod
def from_json(json_object):
return age... |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
EVENT_SOURCE = 'DatadogTest'
EVENT_ID = 9000
EVENT_CATEGORY = 42
INSTANCE = {
'legacy_mode': False,
'timeout': 2,
'path': 'Application',
'filters': {'source': [EVENT_SOURCE]},
}
| event_source = 'DatadogTest'
event_id = 9000
event_category = 42
instance = {'legacy_mode': False, 'timeout': 2, 'path': 'Application', 'filters': {'source': [EVENT_SOURCE]}} |
# 3/15
num_of_pages = int(input()) # < 10000
visited = set()
shortest_path = 0
instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)]
def choose_paths(page, history):
if page not in visited:
visited.add(page)
if not len(instructions[page - 1]): # if this page doesn't n... | num_of_pages = int(input())
visited = set()
shortest_path = 0
instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)]
def choose_paths(page, history):
if page not in visited:
visited.add(page)
if not len(instructions[page - 1]):
global shortest_path
if shortest... |
conn_info = {'host': 'vertica.server.ip.address',
'port': 5433,
'user': 'readonlyuser',
'password': 'XXXXXX',
'database': '',
# 10 minutes timeout on queries
'read_timeout': 600,
# default throw error on invalid UTF-8 results
... | conn_info = {'host': 'vertica.server.ip.address', 'port': 5433, 'user': 'readonlyuser', 'password': 'XXXXXX', 'database': '', 'read_timeout': 600, 'unicode_error': 'strict', 'ssl': False, 'connection_timeout': 5} |
# Created by MechAviv
# Quest ID :: 25562
# Fostering the Dark
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("Dark magic is so much easier than light...")
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay("But I do not fully understand it. With... | sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext('Dark magic is so much easier than light...')
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay('But I do not fully understand it. With every minor touch, I feel the lust for destruction well up within... |
# (n, k) represent nCk
# (N+M-1, N-1)-(N+M-1, N) = (N-M)/(N+M) * (N+M, N)
def solution():
T = int(input())
for i in range(T):
N, M = map(float, input().split(' '))
print('Case #%d: %f' % (i+1, (N-M)/(N+M)))
solution()
| def solution():
t = int(input())
for i in range(T):
(n, m) = map(float, input().split(' '))
print('Case #%d: %f' % (i + 1, (N - M) / (N + M)))
solution() |
# Find len of ll. k = k%l. Then mode l-k-1 steps and break the ll. Add the remaining part of the LL in the front.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListN... | class Solution:
def rotate_right(self, head: ListNode, k: int) -> ListNode:
(l, ptr) = (0, head)
while ptr:
l += 1
ptr = ptr.next
if l == 0 or k % l == 0:
return head
k = k % l
ptr = head
for _ in range(l - k - 1):
ptr ... |
MY_MAC = ""
MY_IP = ""
IFACE = ""
GATEWAY_MAC = ""
_SRC_DST = {}
PROTO = ""
CMD = ""
STOP_SNIFF = False | my_mac = ''
my_ip = ''
iface = ''
gateway_mac = ''
_src_dst = {}
proto = ''
cmd = ''
stop_sniff = False |
# Convert the temperature from Fahrenheit to Celsius in the
# function below. You can use this formula:
# C = (F - 32) * 5/9
# Round the returned result to 3 decimal places.
# You don't have to handle input, just implement the function
# below.
# Also, make sure your function returns the value. Please do NOT
# pr... | def fahrenheit_to_celsius(fahrenheit):
return round((fahrenheit - 32) * 5 / 9, 3) |
def zero(f=lambda a: a):
return f(0)
def one(f=lambda a: a):
return f(1)
def two(f=lambda a: a):
return f(2)
def three(f=lambda a: a):
return f(3)
def four(f=lambda a: a):
return f(4)
def five(f=lambda a: a):
return f(5)
def six(f=lambda a: a):
return f(6)
def seven(f=lambda a: a):
return f(7)
def eight(f=lambd... | def zero(f=lambda a: a):
return f(0)
def one(f=lambda a: a):
return f(1)
def two(f=lambda a: a):
return f(2)
def three(f=lambda a: a):
return f(3)
def four(f=lambda a: a):
return f(4)
def five(f=lambda a: a):
return f(5)
def six(f=lambda a: a):
return f(6)
def seven(f=lambda a: a):
... |
def ChangeText(s):
print('ChangeText() received:', s)
decoded = s.decode("utf-16-le")
print('Decoded:', decoded)
returned = None
if decoded == 'hello':
returned = 'world'
if returned is None:
return None
else:
b = returned.encode("utf-16-le")... | def change_text(s):
print('ChangeText() received:', s)
decoded = s.decode('utf-16-le')
print('Decoded:', decoded)
returned = None
if decoded == 'hello':
returned = 'world'
if returned is None:
return None
else:
b = returned.encode('utf-16-le') + b'\x00\x00'
re... |
#! /usr/bin/env python3
# coding:utf-8
def main():
#answer = [(a, b, c) for a in range(21) for b in range(34) for c in range(101-a-b)
# if a*5 + b*3 +c/3 == 100 and a+b+c == 100]
#print(answer)
for a in range(21):
for b in range(34):
c = 100-a-b
if a*5 + b*3 +c... | def main():
for a in range(21):
for b in range(34):
c = 100 - a - b
if a * 5 + b * 3 + c / 3 == 100:
print(a, b, c)
if __name__ == '__main__':
main() |
def getCommonLetters(word1, word2):
return ''.join(sorted(set(word1).intersection(set(word2))))
print(getCommonLetters('apple', 'strw'))
print(getCommonLetters('sing', 'song'))
| def get_common_letters(word1, word2):
return ''.join(sorted(set(word1).intersection(set(word2))))
print(get_common_letters('apple', 'strw'))
print(get_common_letters('sing', 'song')) |
class ParseFailure(Exception):
def __init__(self, message, offset=None, column=None, row=None, text=None):
self.message = message
self.offset = offset
self.column = column
self.row = row
self.text = text
super(ParseFailure, self).__init__(
self.message,
... | class Parsefailure(Exception):
def __init__(self, message, offset=None, column=None, row=None, text=None):
self.message = message
self.offset = offset
self.column = column
self.row = row
self.text = text
super(ParseFailure, self).__init__(self.message, self.offset, s... |
#
# @lc app=leetcode id=71 lang=python3
#
# [71] Simplify Path
#
# @lc code=start
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split('/'):
if token in ('', '.'):
pass
elif token == '..':
if stack:
... | class Solution:
def simplify_path(self, path: str) -> str:
stack = []
for token in path.split('/'):
if token in ('', '.'):
pass
elif token == '..':
if stack:
stack.pop()
else:
stack.append(token)... |
test_cases = int(input())
while test_cases > 0:
burles = int(input())
optimal = 0
while True:
# The main logic here is to divide the burles into small parts of burles, as, that would be optimal. If Mishka sell 10 burles, he'd get one back; if less, nothing, if higher than 10 and lower than 20 th... | test_cases = int(input())
while test_cases > 0:
burles = int(input())
optimal = 0
while True:
partition = int(burles / 10) * 10
optimal += partition
burles_left = burles - partition
burles = int(burles / 10) + burles_left
if burles < 10:
optimal += burles
... |
def MathOp():
classic_division=3/2
floor_division=3//2
modulus=3%2
power=3**2
return [classic_division, floor_division, modulus, power]
[classic_division, floor_division, modulus, power]=MathOp()
print(classic_division)
print(floor_division)
print(modulus)
print(power) | def math_op():
classic_division = 3 / 2
floor_division = 3 // 2
modulus = 3 % 2
power = 3 ** 2
return [classic_division, floor_division, modulus, power]
[classic_division, floor_division, modulus, power] = math_op()
print(classic_division)
print(floor_division)
print(modulus)
print(power) |
#
# PySNMP MIB module Juniper-Multicast-Router-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Multicast-Router-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:03:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) ... |
# Global Moderation
ACCOUNT_BAN = "ACB"
ACCOUNT_UNBAN = "UBN"
ACCOUNT_TIMEOUT = "TMO"
SERVER_KICK = "KIK"
PROMOTE_GLOBAL_OP = "AOP"
DEMOTE_GLOBAL_OP = "DOP"
LIST_ALTS = "AWC"
BROADCAST = "BRO"
REWARD = "RWD"
RELOAD_SERVER_CONFIG = "RLD"
# Channels
LIST_OFFICAL_CHANNELS = "CHA"
LIST_PRIVATE_CHANNELS = "ORS"
INITIAL_CHA... | account_ban = 'ACB'
account_unban = 'UBN'
account_timeout = 'TMO'
server_kick = 'KIK'
promote_global_op = 'AOP'
demote_global_op = 'DOP'
list_alts = 'AWC'
broadcast = 'BRO'
reward = 'RWD'
reload_server_config = 'RLD'
list_offical_channels = 'CHA'
list_private_channels = 'ORS'
initial_channel_data = 'ICH'
timeout = 'CTU... |
# Suppose you have a multiplication table that is N by N. That is, a 2D array
# where the value at the i-th row and j-th column is (i + 1) * (j + 1)
# (if 0-indexed) or i * j (if 1-indexed).
# Given integers N and X, write a function that returns the number of times X
# appears as a value in an N by N multiplica... | def count_appearance(n, x):
count = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
multip = i * j
if multip > x:
break
if multip == x:
count += 1
break
return count
if __name__ == '__main__':
print(count_a... |
def maxSubArray(X):
# Store sum, start, end
result = (X[0], 0, 0)
for i in range(0, len(X)):
for j in range(i, len(X)):
subSum = 0
for k in range(i, j + 1):
subSum += X[k]
if result[0] < subSum:
result = (subSum, i, j)
return result
| def max_sub_array(X):
result = (X[0], 0, 0)
for i in range(0, len(X)):
for j in range(i, len(X)):
sub_sum = 0
for k in range(i, j + 1):
sub_sum += X[k]
if result[0] < subSum:
result = (subSum, i, j)
return result |
# -*- coding: utf-8 -*-
a = []
b = a
c = []
print("id(a) = ", id(a))
print("id(b) = ", id(b))
print("id(c) = ", id(c))
a.append(1)
b.append(2)
c.append(3)
print("id(a) = ", id(a))
print("id(b) = ", id(b))
print("id(c) = ", id(c))
| a = []
b = a
c = []
print('id(a) = ', id(a))
print('id(b) = ', id(b))
print('id(c) = ', id(c))
a.append(1)
b.append(2)
c.append(3)
print('id(a) = ', id(a))
print('id(b) = ', id(b))
print('id(c) = ', id(c)) |
# read_stocks.py
# Read the current data of the stock market and show them if need be
def is_open(api):
#Check if market is closed
clock = api.get_clock()
print('The market is {}'.format('open.' if clock.is_open else 'closed.'))
### Please check again here
def read_market_data(api,input_stocks,intervals,ma_i... | def is_open(api):
clock = api.get_clock()
print('The market is {}'.format('open.' if clock.is_open else 'closed.'))
def read_market_data(api, input_stocks, intervals, ma_interval):
barset = api.get_barset(input_stocks, 'day', limit=intervals + ma_interval)
stock_bars = barset[input_stocks]
week_ope... |
with open('input.txt') as file:
sum = 0
group = None
for line in file:
if line.strip():
if group is None:
group = set(line.strip())
else:
group = group.intersection(line.strip())
else:
print("group:", ''.join(sorted(group))... | with open('input.txt') as file:
sum = 0
group = None
for line in file:
if line.strip():
if group is None:
group = set(line.strip())
else:
group = group.intersection(line.strip())
else:
print('group:', ''.join(sorted(group)))... |
#
# PySNMP MIB module CISCO-COMMON-MGMT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 11:53:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ... |
class Edge:
pass
class Loop(Edge):
pass
class ParallelEdge(Edge):
pass
| class Edge:
pass
class Loop(Edge):
pass
class Paralleledge(Edge):
pass |
# Division with int
# Prompt user for x
x = int(input("x: "))
# Prompt user for y
y = int(input("y: "))
# Perform division
print(x / y)
| x = int(input('x: '))
y = int(input('y: '))
print(x / y) |
# Python - 2.7.6
Test.describe('combine names')
Test.it('example tests')
Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens')
Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back')
Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent')
| Test.describe('combine names')
Test.it('example tests')
Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens')
Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back')
Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent') |
a,b = [int(i) for i in input().split()]
def gcd(a,b):
if b==0:
print(a)
quit()
c = a%b
gcd(b,c)
if a>b:
gcd(a,b)
else:
gcd(b,a) | (a, b) = [int(i) for i in input().split()]
def gcd(a, b):
if b == 0:
print(a)
quit()
c = a % b
gcd(b, c)
if a > b:
gcd(a, b)
else:
gcd(b, a) |
DEFAULT_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
},
'handlers': {
... | default_logging_config = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'console': {'()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter... |
# Write an algorithm to determine if a number n is "happy".
# A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cy... | class Solution:
def is_happy(self, n: int, s=set()) -> bool:
if n == 1:
return True
if n in s:
return False
total = 0
s.add(n)
for i in str(n):
total += int(i) ** 2
return self.isHappy(total)
s = 19
s = 11
s = 10
print(solution().i... |
def Mean_of_All_Digits(num):
arr = []
n = num
while n > 0:
r = n % 10
n = n // 10
arr.append(r)
return sum(arr)//len(arr)
print(Mean_of_All_Digits(42))
print(Mean_of_All_Digits(12345))
print(Mean_of_All_Digits(666)) | def mean_of__all__digits(num):
arr = []
n = num
while n > 0:
r = n % 10
n = n // 10
arr.append(r)
return sum(arr) // len(arr)
print(mean_of__all__digits(42))
print(mean_of__all__digits(12345))
print(mean_of__all__digits(666)) |
#make a way to quickly make a new dictionary with the right properties
def tool_dict(line):
return {"name":line[0],"2015":line[1],"2016":line[2],"2017":line[3],"2018":line[4],"2019":line[5],"total":sum(line[1:])}
#open file
file=open("tools_dh_proceedings.csv")
print("Opened tools_dh_proceedings.csv")
#throw ... | def tool_dict(line):
return {'name': line[0], '2015': line[1], '2016': line[2], '2017': line[3], '2018': line[4], '2019': line[5], 'total': sum(line[1:])}
file = open('tools_dh_proceedings.csv')
print('Opened tools_dh_proceedings.csv')
file.readline()
lines = file.readlines()
file.close()
print('File has been read.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.