content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# tlseabra@github
def left_in_bag(input):
all_tiles = {'A':9, 'B':2, 'C':2, 'D':4, 'E':12, 'F':2, 'G':3, 'H':2, '_':2,
'I':9, 'J':1, 'K':1, 'L':4, 'M':2, 'N':6, 'O':8, 'P':2, 'Q':1,
'R':6, 'S':4, 'T':6, 'U':4, 'V':2, 'W':2, 'X':1, 'Y':2, 'Z':1}
for char in input:
a... | def left_in_bag(input):
all_tiles = {'A': 9, 'B': 2, 'C': 2, 'D': 4, 'E': 12, 'F': 2, 'G': 3, 'H': 2, '_': 2, 'I': 9, 'J': 1, 'K': 1, 'L': 4, 'M': 2, 'N': 6, 'O': 8, 'P': 2, 'Q': 1, 'R': 6, 'S': 4, 'T': 6, 'U': 4, 'V': 2, 'W': 2, 'X': 1, 'Y': 2, 'Z': 1}
for char in input:
all_tiles[char] -= 1
if... |
def getclass(yClass):
classes = []
for clas in yClass:
if clas not in classes:
classes.append(clas)
return classes
| def getclass(yClass):
classes = []
for clas in yClass:
if clas not in classes:
classes.append(clas)
return classes |
# a bunch of error messages that can be called by various other functions throughout this network
not_enough_args = "Please enter your picks in the format of: (Round number), (Pokemon), (Tier)"
bad_rd = "Your round number is not an integer. Please try again."
bad_rd2 = "Your round number does not fall within the range... | not_enough_args = 'Please enter your picks in the format of: (Round number), (Pokemon), (Tier)'
bad_rd = 'Your round number is not an integer. Please try again.'
bad_rd2 = 'Your round number does not fall within the range of 1 - 11. Please try again.'
bad_pkmn = "I could not find your Pokemon. Maybe it's misspelled or ... |
#
# PySNMP MIB module NEOTERIS-IVE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NEOTERIS-IVE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:18:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def _clang_config_file_content(module_maps):
"""Returns the contents of a Clang configuration file given a depset of module maps."""
content = ""
for map in module_maps.to_list():
path = map.path
# Ignore module maps from the prebuilt frameworks. These are redundant
# because those... | def _clang_config_file_content(module_maps):
"""Returns the contents of a Clang configuration file given a depset of module maps."""
content = ''
for map in module_maps.to_list():
path = map.path
if '.framework' in path:
continue
if '.pch' in path:
continue
... |
#Martina O'Brien 10/3/2019
#divisors
#Print all numbers between 1,000 and 10,000 that are divisble by 6 but not 12
#Input integer needed for calculation between the range of 1,000 and 10,000
#Firstly, need to be able to print range between 1,000 and 10,000. Lower level is set with code =int(input ('Enter Number i... | lower = int(input('Enter Number in lower range: '))
upper = int(input('Enter Number in upper range: '))
for i in range(lower, upper):
if i % 6 == 0 and i % 12 != 0:
print(i) |
slownik={'a':'b','b':'c','c':'d'}
ch='a'
try:
while True:
ch=slownik[ch]
print(ch)
except KeyError:
print('Nie ma takiego klucza',ch) | slownik = {'a': 'b', 'b': 'c', 'c': 'd'}
ch = 'a'
try:
while True:
ch = slownik[ch]
print(ch)
except KeyError:
print('Nie ma takiego klucza', ch) |
def raw_file(filename: str) -> str:
with open(filename) as f:
x = f.read()
return x
# end raw_file
# cfg['cat_file'] = raw_file | def raw_file(filename: str) -> str:
with open(filename) as f:
x = f.read()
return x |
#
# PySNMP MIB module SCTE-HMS-MPEG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCTE-HMS-MPEG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:47:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("c inside add():", c)
add()
print("c in main:", c)
def foo():
x = 20
def bar():
global x
x = 25
print("Before calling bar: ", x)
print("Calling bar now")
bar()
print("After calling bar:... | c = 0
def add():
global c
c = c + 2
print('c inside add():', c)
add()
print('c in main:', c)
def foo():
x = 20
def bar():
global x
x = 25
print('Before calling bar: ', x)
print('Calling bar now')
bar()
print('After calling bar: ', x)
foo()
print('x in main:', x) |
# 8 TeV
electron_qcd_samples = [ 'QCD_Pt_20_30_BCtoE',
'QCD_Pt_30_80_BCtoE',
'QCD_Pt_80_170_BCtoE',
'QCD_Pt_170_250_BCtoE',
'QCD_Pt_250_350_BCtoE',
'QCD_Pt_350_BCtoE',
'... | electron_qcd_samples = ['QCD_Pt_20_30_BCtoE', 'QCD_Pt_30_80_BCtoE', 'QCD_Pt_80_170_BCtoE', 'QCD_Pt_170_250_BCtoE', 'QCD_Pt_250_350_BCtoE', 'QCD_Pt_350_BCtoE', 'QCD_Pt_20_30_EMEnriched', 'QCD_Pt_30_80_EMEnriched', 'QCD_Pt_80_170_EMEnriched', 'QCD_Pt_170_250_EMEnriched', 'QCD_Pt_250_350_EMEnriched', 'QCD_Pt_350_EMEnriche... |
def div(num, den):
return num / den
def div(num=0, den=0):
return num / den
def sum(*args):
res = 0
for x in args:
res += x
return res
def print_reverse(cdn):
r = cdn[::-1]
print(r)
def quotient_modulo(a, b):
return a // b, a % b
a = quotient_modulo(13, 6)
print(a)
prin... | def div(num, den):
return num / den
def div(num=0, den=0):
return num / den
def sum(*args):
res = 0
for x in args:
res += x
return res
def print_reverse(cdn):
r = cdn[::-1]
print(r)
def quotient_modulo(a, b):
return (a // b, a % b)
a = quotient_modulo(13, 6)
print(a)
print('V... |
#
# PySNMP MIB module CIENA-CES-RSVPTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CIENA-CES-RSVPTE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:31:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
class Turma:
def __init__(self, turma_id, criterio, coordenador):
self._lista_alunos = []
self._criterio = criterio
self._coordenador = coordenador
self._turma_id = turma_id
def get_turma_id(self): # getter / expoe um atributo privado
return self._turma_id
def inse... | class Turma:
def __init__(self, turma_id, criterio, coordenador):
self._lista_alunos = []
self._criterio = criterio
self._coordenador = coordenador
self._turma_id = turma_id
def get_turma_id(self):
return self._turma_id
def insere_aluno(self, aluno):
self._... |
def checkList(l, nb):
li = list(range(1, len(l)+1))
for i in reversed(list(range(len(l)))):
e = l[i]
# i is index
# e is element
diff_i = i - li.index(e)
# print(diff_i)
if l == li:
print(nb)
break
if diff_i > 0:
cont... | def check_list(l, nb):
li = list(range(1, len(l) + 1))
for i in reversed(list(range(len(l)))):
e = l[i]
diff_i = i - li.index(e)
if l == li:
print(nb)
break
if diff_i > 0:
continue
if diff_i < 0 and abs(diff_i) < 3:
nb += ab... |
class MinHeap:
def __init__(self, lst):
self.lst = lst
self.n = len(lst)
def min_heapify(self, i):
li, ri, imin = 2*i + 1, 2*(i+1), i
if li < self.n and self.lst[li] < self.lst[imin]:
imin = li
if ri < self.n and self.lst[ri] < self.lst[imin]:
... | class Minheap:
def __init__(self, lst):
self.lst = lst
self.n = len(lst)
def min_heapify(self, i):
(li, ri, imin) = (2 * i + 1, 2 * (i + 1), i)
if li < self.n and self.lst[li] < self.lst[imin]:
imin = li
if ri < self.n and self.lst[ri] < self.lst[imin]:
... |
OLD_CLASSIFIER = {
"brandName": "test",
"custom": True,
"defaultIncidentType": "",
"id": "test classifier",
"keyTypeMap": {
"test": "test1"
},
"mapping": {
"Logz.io Alert": {
"dontMapEventToLabels": False,
"internalMapping": {
"test Ale... | old_classifier = {'brandName': 'test', 'custom': True, 'defaultIncidentType': '', 'id': 'test classifier', 'keyTypeMap': {'test': 'test1'}, 'mapping': {'Logz.io Alert': {'dontMapEventToLabels': False, 'internalMapping': {'test Alert ID': {'complex': None, 'simple': 'alertId'}, 'details': {'complex': None, 'simple': 'de... |
def b1():
pass
def b2(a):
pass
def b3(a, b, c, d):
pass
def b4(a, b, c, *fun):
pass
def b5(*fun):
pass
def b6(a, b, c, **kwargs):
pass
def b7(**kwargs):
pass
def b8(*args, **kwargs):
pass
def b9(a, b, c, *args, **kwargs):
pass
def b10(a, b, c=3, d=4, *args, **kwargs):
''... | def b1():
pass
def b2(a):
pass
def b3(a, b, c, d):
pass
def b4(a, b, c, *fun):
pass
def b5(*fun):
pass
def b6(a, b, c, **kwargs):
pass
def b7(**kwargs):
pass
def b8(*args, **kwargs):
pass
def b9(a, b, c, *args, **kwargs):
pass
def b10(a, b, c=3, d=4, *args, **kwargs):
""... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, data):
self.root = Node(data)
def add_left(self, current, data):
new_node = Node(data)
if current.left == None:
cur... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Binarytree:
def __init__(self, data):
self.root = node(data)
def add_left(self, current, data):
new_node = node(data)
if current.left == None:
curre... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """
Defines a repository rule for configuring the node executable.
"""
def _impl(repository_ctx):
if repository_ctx.attr.target_tool and repository_ctx.attr.target_tool_path:
fail('Can only set one of target_tool or target_tool_path but both where set.')
if repository_ctx.attr.target_tool:
subs... |
# coding: utf-8
def calculateKnightMoves(unit, player, game):
position = game.getPositionOfUnit(unit)
global x
global y
x = position[0]
y = position[1]
if y < game.upperLimit - 1:
calculateUpperMoves(unit, player, game)
if y > game.lowerLimit:
calculateLowerMoves(unit, playe... | def calculate_knight_moves(unit, player, game):
position = game.getPositionOfUnit(unit)
global x
global y
x = position[0]
y = position[1]
if y < game.upperLimit - 1:
calculate_upper_moves(unit, player, game)
if y > game.lowerLimit:
calculate_lower_moves(unit, player, game)
d... |
# https://www.hackerrank.com/challenges/count-luck/problem
# Count the number of intersections in the correct path of a maze
def countLuck(matrix, k):
# Get the start and the end coordinates
for y, row in enumerate(matrix):
if row.__contains__('M'):
start = (row.index('M'), y)
if r... | def count_luck(matrix, k):
for (y, row) in enumerate(matrix):
if row.__contains__('M'):
start = (row.index('M'), y)
if row.__contains__('*'):
end = (row.index('*'), y)
max_x = len(matrix[0])
max_y = len(matrix)
look_for = [start]
been_to = []
paths = [[sta... |
'''
@author: l4zyc0d3r
People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt
'''
class Solution:
def search(self, N: List[int], target: int) -> int:
idx = -1
lo, hi =0, len(N)-1
while lo<=hi:
md = lo+(hi-lo)//2
if N[md]==target:
... | """
@author: l4zyc0d3r
People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt
"""
class Solution:
def search(self, N: List[int], target: int) -> int:
idx = -1
(lo, hi) = (0, len(N) - 1)
while lo <= hi:
md = lo + (hi - lo) // 2
if N[m... |
class CodeBeautifierError(Exception):
pass
class AsirSyntaxError(CodeBeautifierError):
def __init__(self, message):
self.message = message
| class Codebeautifiererror(Exception):
pass
class Asirsyntaxerror(CodeBeautifierError):
def __init__(self, message):
self.message = message |
class ChainEvent:
def __init__(self, events):
self._events = events
def initialize(self):
for event in self._events:
event.initialize()
def run(self, stop_time):
for event in self._events:
event.run(stop_time)
def update(self, stop_time):
for ev... | class Chainevent:
def __init__(self, events):
self._events = events
def initialize(self):
for event in self._events:
event.initialize()
def run(self, stop_time):
for event in self._events:
event.run(stop_time)
def update(self, stop_time):
for e... |
class Tree(object):
def __init__(self, data, depth, parent):
self.data = data
self.depth = depth
self.parent = parent
self.children = []
def add_child(self, obj):
self.children.append(obj)
def search_and_remove(lines, tree: Tree, depth):
new_lines = []
for line... | class Tree(object):
def __init__(self, data, depth, parent):
self.data = data
self.depth = depth
self.parent = parent
self.children = []
def add_child(self, obj):
self.children.append(obj)
def search_and_remove(lines, tree: Tree, depth):
new_lines = []
for line... |
#
# PySNMP MIB module SYNOLOGY-DISK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYNOLOGY-DISK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:14:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ... |
__author__ = 'kra869'
class ArmoryException(BaseException):
def __init__(self, msg):
self.msg = msg
def print_message(self):
print(type(self).__name__ + ": " + self.msg)
| __author__ = 'kra869'
class Armoryexception(BaseException):
def __init__(self, msg):
self.msg = msg
def print_message(self):
print(type(self).__name__ + ': ' + self.msg) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
... | class Solution:
def min_depth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and (not root.right):
return 1
queue = []
queue.append(root)
depth = 1
while queue:
for i in range(len(queue)):
node... |
#! /usr/bin/env python3
def read_input():
with open('../inputs/input09.txt') as fp:
lines = fp.readlines()
return [int(line) for line in lines]
chain = [35,20,15,25,47,40,62,55,65,95,102,117,150,182,127,219,299,277,309,576]
preamble = 5
chain = read_input()
preamble = 25
# Find number in chain w... | def read_input():
with open('../inputs/input09.txt') as fp:
lines = fp.readlines()
return [int(line) for line in lines]
chain = [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576]
preamble = 5
chain = read_input()
preamble = 25
for n in range(len(chain) - pream... |
"""Constants for UI Lovelace Minimalist."""
# Base component constants
NAME = "UI Lovelace Minimalist"
DOMAIN = "ui_lovelace_minimalist"
DOMAIN_DATA = f"{DOMAIN}_data"
VERSION = "0.0.1"
ATTRIBUTION = "Data provided by http://jsonplaceholder.typicode.com/"
ISSUE_URL = "https://github.com/stokkie90/ui-lovelace-minimalis... | """Constants for UI Lovelace Minimalist."""
name = 'UI Lovelace Minimalist'
domain = 'ui_lovelace_minimalist'
domain_data = f'{DOMAIN}_data'
version = '0.0.1'
attribution = 'Data provided by http://jsonplaceholder.typicode.com/'
issue_url = 'https://github.com/stokkie90/ui-lovelace-minimalist/issues'
conf_language = 'l... |
def cmd8500(cmd , ser):
print("Command: ", hex(cmd[2]))
printbuff(cmd)
ser.write(cmd)
resp = ser.read(26)
#print("Resp: ")
printbuff(resp)
def printbuff(b):
r=""
for s in range(len(b)):
r+=" "
#r+=str(s)
#r+="-"
r+=hex(b[s]).replace('0x','')
prin... | def cmd8500(cmd, ser):
print('Command: ', hex(cmd[2]))
printbuff(cmd)
ser.write(cmd)
resp = ser.read(26)
printbuff(resp)
def printbuff(b):
r = ''
for s in range(len(b)):
r += ' '
r += hex(b[s]).replace('0x', '')
print(r)
def csum(thing):
sum = 0
for i in range(l... |
class GovtEmployee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def displayEmp(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
elist=[]
for i in range(3):
n=input("Enter name of an employee: ")
s=int(input("Enter salary of... | class Govtemployee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display_emp(self):
print('Name : ', self.name, ', Salary: ', self.salary)
elist = []
for i in range(3):
n = input('Enter name of an employee: ')
s = int(input('Enter salary of an emp... |
class BaseEngine(object):
r"""Base class for all engines.
It defines the training and evaluation process.
The subclass should implement at least the following:
- :meth:`train`
- :meth:`log_train`
- :meth:`eval`
- :meth:`log_eval`
"""
def __init__(self, agent, ru... | class Baseengine(object):
"""Base class for all engines.
It defines the training and evaluation process.
The subclass should implement at least the following:
- :meth:`train`
- :meth:`log_train`
- :meth:`eval`
- :meth:`log_eval`
"""
def __init__(self, agent, ru... |
#
# PySNMP MIB module TPT-MULTIDV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-MULTIDV-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:18:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
def make_strings()->List(String):
xs = []
for i in range(3):
if i == 0:
xs.append(i)
elif i == 1:
xs.append(True)
else:
xs.append(make_strings)
return xs
make_strings()
| def make_strings() -> list(String):
xs = []
for i in range(3):
if i == 0:
xs.append(i)
elif i == 1:
xs.append(True)
else:
xs.append(make_strings)
return xs
make_strings() |
def fib(n):
"""Calculates the nth Fibonacci number"""
if n >= 0:
return fibiter(1, 0, 0, 1, n)
if n < 0:
a, b = 0, 1
for _ in xrange(0, n, -1):
a, b = b - a, a
return a
def fibiter(a, b, p, q, count):
if count == 0:
return b
if coun... | def fib(n):
"""Calculates the nth Fibonacci number"""
if n >= 0:
return fibiter(1, 0, 0, 1, n)
if n < 0:
(a, b) = (0, 1)
for _ in xrange(0, n, -1):
(a, b) = (b - a, a)
return a
def fibiter(a, b, p, q, count):
if count == 0:
return b
if count % 2 =... |
class Submission:
def valid_pairs(self, n: int):
pass
| class Submission:
def valid_pairs(self, n: int):
pass |
# @desc The **+** operator combines two strings into a new string
def concat1(s1, s2):
result = s1 + s2
return result
def main():
print(concat1('Car', 'wash'))
print(concat1('Hello', ' world'))
print(concat1('5', '8'))
print(concat1('Snow', 'ball'))
print(concat1('Rain', 'boots'))
pri... | def concat1(s1, s2):
result = s1 + s2
return result
def main():
print(concat1('Car', 'wash'))
print(concat1('Hello', ' world'))
print(concat1('5', '8'))
print(concat1('Snow', 'ball'))
print(concat1('Rain', 'boots'))
print(concat1('Reading', 'bat'))
print(concat1('', 'Hi'))
print... |
pinyins = []
pinyin_combinations = []
pinyin_tables = []
def read_pinyins(f):
while line := f.readline()[:-1]:
lst = line.split(',')
pinyins.append(tuple(lst[i] for i in (0,2,3)))
def read_pinyin_combinations(f):
while line := f.readline()[:-1]:
pinyin_combinations.append(line)
def re... | pinyins = []
pinyin_combinations = []
pinyin_tables = []
def read_pinyins(f):
while (line := f.readline()[:-1]):
lst = line.split(',')
pinyins.append(tuple((lst[i] for i in (0, 2, 3))))
def read_pinyin_combinations(f):
while (line := f.readline()[:-1]):
pinyin_combinations.append(line)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
RRFAnalyser version Web
Learn more about RRF on https://f5nlg.wordpress.com
Check video about RRFTracker on https://www.youtube.com/watch?v=rVW8xczVpEo
73 & 88 de F4HWN Armel
'''
# Ansi color
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '... | """
RRFAnalyser version Web
Learn more about RRF on https://f5nlg.wordpress.com
Check video about RRFTracker on https://www.youtube.com/watch?v=rVW8xczVpEo
73 & 88 de F4HWN Armel
"""
class Color:
purple = '\x1b[95m'
cyan = '\x1b[96m'
darkcyan = '\x1b[36m'
blue = '\x1b[94m'
green = '\x1b[92m'
ye... |
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cur = root
... | class Solution:
def kth_smallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cur = root
node = None
while k > 0:
while cur:
stack.append(cur)
cur = cur.left
node = stack.pop()
k -= 1
cur =... |
# Python > Sets > Set .symmetric_difference() Operation
# Making symmetric difference of sets.
#
# https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem
#
n = int(input())
english = set(map(int, input().split()))
n = int(input())
french = set(map(int, input().split()))
print(len(englis... | n = int(input())
english = set(map(int, input().split()))
n = int(input())
french = set(map(int, input().split()))
print(len(english ^ french)) |
############################
#####code challenge 27######
############################
# making insertion sort function takes an array and return the array sorted
# def merge_sort(array):
# """merge sort"""
# n = len(array)
# if n > 1:
# mid = n // 2
# left = array[:mid]
# right = ... | def merge_sort_sol(array):
if len(array) <= 1:
return array
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
merge_sort_sol(left)
merge_sort_sol(right)
merge_two_sorted_array(left, right, array)
return array
def merge_two_sorted_array(a, b, array):
"""merge two s... |
class script_error(Exception):
def __init__(self,value): self.value = value
def __str__(self): return self.value
__repr__ = __str__
class art_error(Exception):
def __init__(self,value): self.value = value
def __str__(self): return self.value
__repr__ = __str__
class markup_error(Exceptio... | class Script_Error(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
__repr__ = __str__
class Art_Error(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
__repr__ = __st... |
"""
The media module provides some facilities for handling music. Individual pieces of music can be
- started
- stopped
`PlayLists` can be
- constructed
- played sequentially
- played randomly.
There are also some control and dialog classes available for setting music-related options.
""" | """
The media module provides some facilities for handling music. Individual pieces of music can be
- started
- stopped
`PlayLists` can be
- constructed
- played sequentially
- played randomly.
There are also some control and dialog classes available for setting music-related options.
""" |
'''
This module contains some constants that are used by the Bluetooth stack.
'''
# === General constants ===
TYPE_ACL_DATA = 0x2
TYPE_HCI_EVENT = 0x4
# === Ubertooth constants ===
# USB Dev FS Reset Constant
USBDEVFS_RESET = ord('U') << (4 * 2) | 20
# Modulations
MOD_BT_BASIC_RATE = 0
MOD_BT_LOW_ENERGY = 1
MOD_802... | """
This module contains some constants that are used by the Bluetooth stack.
"""
type_acl_data = 2
type_hci_event = 4
usbdevfs_reset = ord('U') << 4 * 2 | 20
mod_bt_basic_rate = 0
mod_bt_low_energy = 1
mod_80211_fhss = 2
ubertooth_ping = 0
ubertooth_rx_symbols = 1
ubertooth_tx_symbols = 2
ubertooth_get_usrled = 3
uber... |
"""File tree package.
This package allow to go through sources and handle supported files.
"""
| """File tree package.
This package allow to go through sources and handle supported files.
""" |
_log = ''
def log(text):
print(text)
global _log
_log += '{}\n'.format(text)
def flush():
with open('log.txt', 'wb') as log_file:
log_file.write(_log.encode('utf-8')) | _log = ''
def log(text):
print(text)
global _log
_log += '{}\n'.format(text)
def flush():
with open('log.txt', 'wb') as log_file:
log_file.write(_log.encode('utf-8')) |
a = 0
b = 1
n = int(input("Please press 2, 4 or 6"))
print("You pressed:", n)
h = float((b - a) / n)
def func(x):
return x * x
if n == 2:
def twoPanels(f, a, b, h):
return (h / 3) * (f(a) + (4 * f((a + b) / 2)) + f(b))
print(twoPanels(func, a, b, h))
if n == 4:
def fourPanels(f... | a = 0
b = 1
n = int(input('Please press 2, 4 or 6'))
print('You pressed:', n)
h = float((b - a) / n)
def func(x):
return x * x
if n == 2:
def two_panels(f, a, b, h):
return h / 3 * (f(a) + 4 * f((a + b) / 2) + f(b))
print(two_panels(func, a, b, h))
if n == 4:
def four_panels(f, a, b, h):
... |
expected_output = {
"main": {
"chassis": "ISR4331/K9"
},
"slot": {
"0": {
"lc": {
"ISR4331/K9": {
"cpld_ver": "17100927",
"fw_ver": "16.7(3r)",
"insert_time": "3w5d",
"name": "ISR4331/... | expected_output = {'main': {'chassis': 'ISR4331/K9'}, 'slot': {'0': {'lc': {'ISR4331/K9': {'cpld_ver': '17100927', 'fw_ver': '16.7(3r)', 'insert_time': '3w5d', 'name': 'ISR4331/K9', 'slot': '0', 'state': 'ok', 'subslot': {'0': {'ISR4331-3x1GE': {'insert_time': '3w5d', 'name': 'ISR4331-3x1GE', 'state': 'ok', 'subslot': ... |
# -*- coding: utf-8 -*-
def remove_dc(data, axis=0, method='mean'):
pass
| def remove_dc(data, axis=0, method='mean'):
pass |
'''
Tr3ccani Scraper:
welcome!
version 0.1
cc fcagnola
''' | """
Tr3ccani Scraper:
welcome!
version 0.1
cc fcagnola
""" |
""" CS206 Spring 2017 ludobots -- Project Phototaxis
https://www.reddit.com/r/ludobots/wiki/pyrosim/phototaxis
"""
# Robot design parameters
L = 0.4 # leg length
R = L/5 # leg radius
D = 30*L # light sensor distance
G = 1.0 # light sensor gain
Tau = 1.0 # motor neuron time constant
# Evolution simulati... | """ CS206 Spring 2017 ludobots -- Project Phototaxis
https://www.reddit.com/r/ludobots/wiki/pyrosim/phototaxis
"""
l = 0.4
r = L / 5
d = 30 * L
g = 1.0
tau = 1.0
eval_time = 2000
pop_size = 10
num_gens = 200
num_envs = 4 |
class TestClass(object):
def __init__(self, arg1: int, arg2: str, arg3: float = None):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.arg4 = self._get_arg4()
def _get_arg4(self):
return 4
| class Testclass(object):
def __init__(self, arg1: int, arg2: str, arg3: float=None):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.arg4 = self._get_arg4()
def _get_arg4(self):
return 4 |
almaweb = {
"user": "<username for almaweb>",
"password": "<password for almaweb>"
}
email = {
"From": "<Sender Mail>",
"FromName": "<Sender Name>",
"FromPassword": "<Sender Password>",
"FromSMTP": "<Sender SMPT server adress>",
"To": "<mail the news should be delivered to>"
}
refreshTime = ... | almaweb = {'user': '<username for almaweb>', 'password': '<password for almaweb>'}
email = {'From': '<Sender Mail>', 'FromName': '<Sender Name>', 'FromPassword': '<Sender Password>', 'FromSMTP': '<Sender SMPT server adress>', 'To': '<mail the news should be delivered to>'}
refresh_time = {'upper': 1800, 'lower': 2700} |
"""WikiArt Retriever.
Author: Lucas David -- <ld492@drexel.edu>
License: MIT License (c) 2016
"""
| """WikiArt Retriever.
Author: Lucas David -- <ld492@drexel.edu>
License: MIT License (c) 2016
""" |
# Function definition is here
def printinfo(arg1, *vartuple):
print("Output is: ")
print('first:',arg1)
for var in vartuple:
print(var)
print()
return
# Now you can call printinfo function
printinfo(10)
printinfo(70, 60, 50)
| def printinfo(arg1, *vartuple):
print('Output is: ')
print('first:', arg1)
for var in vartuple:
print(var)
print()
return
printinfo(10)
printinfo(70, 60, 50) |
# Do not edit. bazel-deps autogenerates this file from dependencies.yaml.
def declare_maven(hash):
native.maven_jar(
name = hash["name"],
artifact = hash["artifact"],
sha1 = hash["sha1"],
repository = hash["repository"]
)
native.bind(
name = hash["bind"],
act... | def declare_maven(hash):
native.maven_jar(name=hash['name'], artifact=hash['artifact'], sha1=hash['sha1'], repository=hash['repository'])
native.bind(name=hash['bind'], actual=hash['actual'])
def list_dependencies():
return [{'artifact': 'com.fasterxml.jackson.core:jackson-core:2.1.3', 'lang': 'java', 'sha... |
class Warband:
def __init__(self, army_list):
self.army_list = army_list
self.hero = None
self.warriors = []
def add_warrior(self, w):
self.warriors.append(w)
def set_hero(self, h):
self.hero = h
def remove_warrior(self, warrior):
try:
self.... | class Warband:
def __init__(self, army_list):
self.army_list = army_list
self.hero = None
self.warriors = []
def add_warrior(self, w):
self.warriors.append(w)
def set_hero(self, h):
self.hero = h
def remove_warrior(self, warrior):
try:
self... |
class Node:
def __init__(self, dup, val):
self.dup = dup
self.val = val
self.left = None
self.right = None
self.sum = 0
def inDup(self):
self.dup += 1
def getDup(self):
return self.dup
class Solution:
def countSmaller(self, nums: [int]) -> [int]:... | class Node:
def __init__(self, dup, val):
self.dup = dup
self.val = val
self.left = None
self.right = None
self.sum = 0
def in_dup(self):
self.dup += 1
def get_dup(self):
return self.dup
class Solution:
def count_smaller(self, nums: [int]) -> ... |
__name__ = "revscoring"
__version__ = "2.11.4"
__author__ = "Aaron Halfaker"
__author_email__ = "ahalfaker@wikimedia.org"
__description__ = ("A set of utilities for generating quality scores for " +
"MediaWiki revisions")
__url__ = "https://github.com/wikimedia/revscoring"
__license__ = "MIT"
| __name__ = 'revscoring'
__version__ = '2.11.4'
__author__ = 'Aaron Halfaker'
__author_email__ = 'ahalfaker@wikimedia.org'
__description__ = 'A set of utilities for generating quality scores for ' + 'MediaWiki revisions'
__url__ = 'https://github.com/wikimedia/revscoring'
__license__ = 'MIT' |
set_5={1,2,3,4,5}
set_6={0,1,2,3,4,5}
print(set_5)
print(set_6)
print(set_5.issubset(set_6))
print(set_6.issubset(set_5)) | set_5 = {1, 2, 3, 4, 5}
set_6 = {0, 1, 2, 3, 4, 5}
print(set_5)
print(set_6)
print(set_5.issubset(set_6))
print(set_6.issubset(set_5)) |
# Imagine you've got all your friends in a list, and you want to print it out.
friends = ["Rolf", "Anne", "Charlie"]
print(f"My friends are {friends}.")
# Not the prettiest, so instead you can join your friends using a ",":
friends = ["Rolf", "Anne", "Charlie"]
comma_separated = ", ".join(friends)
print(f"My friends a... | friends = ['Rolf', 'Anne', 'Charlie']
print(f'My friends are {friends}.')
friends = ['Rolf', 'Anne', 'Charlie']
comma_separated = ', '.join(friends)
print(f'My friends are {comma_separated}.') |
coordinates_00EBFF = ((105, 193),
(105, 194), (105, 195), (105, 196), (105, 197), (105, 198), (105, 199), (106, 190), (106, 192), (106, 201), (107, 188), (107, 193), (107, 194), (107, 195), (107, 196), (107, 197), (107, 198), (107, 199), (107, 203), (108, 187), (108, 190), (108, 191), (108, 192), (108, 193), (108, 19... | coordinates_00_ebff = ((105, 193), (105, 194), (105, 195), (105, 196), (105, 197), (105, 198), (105, 199), (106, 190), (106, 192), (106, 201), (107, 188), (107, 193), (107, 194), (107, 195), (107, 196), (107, 197), (107, 198), (107, 199), (107, 203), (108, 187), (108, 190), (108, 191), (108, 192), (108, 193), (108, 194... |
# File Handle as a Sequence
file = open('test.txt')
for line in file:
print(line)
fhand = open('test.txt')
inp = fhand.read() # Reads the whole file into a var that can be iterated over etc.
print(len(inp))
for char in inp:
print(char)
# print(inp[:20])
# Searching through a file w/ continue
file = open(... | file = open('test.txt')
for line in file:
print(line)
fhand = open('test.txt')
inp = fhand.read()
print(len(inp))
for char in inp:
print(char)
file = open('test.txt')
for line in file:
line = line.rstrip()
if not line.startswith('line'):
continue
print(line) |
chance = 0
minutos = 0
while chance < 6:
tiempo_min = int(input("Ingrese el tiempo en minutos: "))
chance +=1
if tiempo_min / 60:
minutos = 60 - tiempo_min % 60
dias = 24 - tiempo_min % 24
horas = 8 - tiempo_min % 8
| chance = 0
minutos = 0
while chance < 6:
tiempo_min = int(input('Ingrese el tiempo en minutos: '))
chance += 1
if tiempo_min / 60:
minutos = 60 - tiempo_min % 60
dias = 24 - tiempo_min % 24
horas = 8 - tiempo_min % 8 |
"""
Integer Replacement
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1... | """
Integer Replacement
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1... |
# This program displays the sum of all the
# single digit numbers in a string.
def main():
string = input('Enter a series of numbers without spaces and I will add them.\n')
total = 0
for num in string:
total += int(num)
print('The sum of the digits in', strin... | def main():
string = input('Enter a series of numbers without spaces and I will add them.\n')
total = 0
for num in string:
total += int(num)
print('The sum of the digits in', string, 'is', str(total) + '.')
main() |
class Solution(object):
def maxIceCream(self, costs, coins):
"""
:type costs: List[int]
:type coins: int
:rtype: int
"""
costs.sort()
out = 0
for i in range(len(costs)):
if(costs[i]<=coins):
coins -= costs[i]
... | class Solution(object):
def max_ice_cream(self, costs, coins):
"""
:type costs: List[int]
:type coins: int
:rtype: int
"""
costs.sort()
out = 0
for i in range(len(costs)):
if costs[i] <= coins:
coins -= costs[i]
... |
def column_align(texts):
ret = list()
for i, line in enumerate(texts):
line = line[:-1]
line = line.split('\t')
if len(line) != 10:
print(f'{i+1} ({len(line)}): {line}')
ret.append('\t'.join(line))
return ret
if __name__ == '__main__':
file = './datasets/ra... | def column_align(texts):
ret = list()
for (i, line) in enumerate(texts):
line = line[:-1]
line = line.split('\t')
if len(line) != 10:
print(f'{i + 1} ({len(line)}): {line}')
ret.append('\t'.join(line))
return ret
if __name__ == '__main__':
file = './datasets/r... |
class MessagesController:
def index(self, view, request):
return view("messages/index.html")
def show(self, view, request, id):
return f"message {id}"
def new(self, view, request):
return "form"
def create(self, view, request):
return "message created", 201
def ed... | class Messagescontroller:
def index(self, view, request):
return view('messages/index.html')
def show(self, view, request, id):
return f'message {id}'
def new(self, view, request):
return 'form'
def create(self, view, request):
return ('message created', 201)
def... |
BOARD_SCORES = {
"PAWN": 1,
"BISHOP": 4,
"KING": 0,
"QUEEN": 10,
"KNIGHT": 5,
"ROOK": 3
}
# max board score for player == 42 < WIN
END_SCORES = {
"WIN": 100,
"LOSE": -100,
"TIE": 0,
}
PIECES = {
1: "PAWN",
2: "KNIGHT",
3: "BISHOP",
4: "ROOK",
5: "QUEEN",
6... | board_scores = {'PAWN': 1, 'BISHOP': 4, 'KING': 0, 'QUEEN': 10, 'KNIGHT': 5, 'ROOK': 3}
end_scores = {'WIN': 100, 'LOSE': -100, 'TIE': 0}
pieces = {1: 'PAWN', 2: 'KNIGHT', 3: 'BISHOP', 4: 'ROOK', 5: 'QUEEN', 6: 'KING'} |
# -*- coding: utf-8 -*-
#
# AWS Sphinx configuration file.
#
# For more information about how to configure this file, see:
#
# https://w.amazon.com/index.php/AWSDevDocs/Sphinx
#
#
# General information about the project.
#
# Optional service/SDK name, typically the three letter acronym (TLA) that
# represents the ser... | service_name = u'Mobile SDK'
service_name_long = u'AWS ' + service_name
service_docs_home = u'http://aws.amazon.com/documentation/mobile-sdk/'
project = u'iOS Developer Guide'
project_desc = u'%s %s' % (service_name_long, project)
project_basename = 'mobile/sdkforios/developerguide'
man_name = 'aws-ios-dg'
language = u... |
small_sizes = [200, 100, 50, 10, 1]
# Root of tudocomp provided mirrors of datasets
TDC_URL = "dolomit.cs.uni-dortmund.de/tudocomp"
# TODO: This server went offline
# Only he-graph has an existing 200mb prefix on loebels system
# TODO: Need to upload to our server
# HashTag Datasets, see http://acube.di.unipi.it/data... | small_sizes = [200, 100, 50, 10, 1]
tdc_url = 'dolomit.cs.uni-dortmund.de/tudocomp'
download_and_extract('cc', small_sizes, [TDC_URL + '/commoncrawl.ascii.xz'])
download_and_extract('chr19', small_sizes, [TDC_URL + '/chr19.10.fa.xz'])
pc_url = 'http://pizzachili.dcc.uchile.cl'
download_and_extract('pc', small_sizes, [T... |
class Response:
"""A simple HTTP Response, with status code, status message, headers, and
body."""
def __init__(self, code, message, headers, body):
self.code = code
self.message = message
self.headers = dict(headers)
self.body = body
def __repr__(self):
return... | class Response:
"""A simple HTTP Response, with status code, status message, headers, and
body."""
def __init__(self, code, message, headers, body):
self.code = code
self.message = message
self.headers = dict(headers)
self.body = body
def __repr__(self):
return ... |
woerter = {"Germany" : "Deutschland",
"Spain" : "Spanien",
"Greece" : "Griechenland"}
fobj = open("ausgabe.txt", "w")
for engl in woerter:
fobj.write("{} {}\n".format(engl, woerter[engl]))
fobj.close()
| woerter = {'Germany': 'Deutschland', 'Spain': 'Spanien', 'Greece': 'Griechenland'}
fobj = open('ausgabe.txt', 'w')
for engl in woerter:
fobj.write('{} {}\n'.format(engl, woerter[engl]))
fobj.close() |
pen = float(input())
price_Pen = pen*5.8
marker = float(input())
price_Marker = marker*7.2
preparat = float(input())
price_Preparat = preparat*1.2
percent = float(input())
all = (price_Pen+price_Marker+price_Preparat) * ((100-percent)/100)
print(f'{all:.3f}') | pen = float(input())
price__pen = pen * 5.8
marker = float(input())
price__marker = marker * 7.2
preparat = float(input())
price__preparat = preparat * 1.2
percent = float(input())
all = (price_Pen + price_Marker + price_Preparat) * ((100 - percent) / 100)
print(f'{all:.3f}') |
submission = """
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"challenge_phase": 7,
"created_by": 4,
"execution_time": "None",
"id": 9,
"input_file": "http://testserver/media/submission_files/submission_9/2224fb89-6828-4... | submission = '\n{\n "count": 4,\n "next": null,\n "previous": null,\n "results": [\n {\n "challenge_phase": 7,\n "created_by": 4,\n "execution_time": "None",\n "id": 9,\n "input_file": "http://testserver/media/submission_files/submission_9/2224fb... |
class ArithmeticSkill:
def __init__(self, tts_service=None):
""" Initialisation.
:param db: the json database.
:param tts_service: A TTS service, i.e. an object which has a
`speak(text)` method for speaking the result.
"""
sel... | class Arithmeticskill:
def __init__(self, tts_service=None):
""" Initialisation.
:param db: the json database.
:param tts_service: A TTS service, i.e. an object which has a
`speak(text)` method for speaking the result.
"""
self... |
"""
[2015-11-23] Challenge # 242 [easy] Funny plant
https://www.reddit.com/r/dailyprogrammer/comments/3twuwf/20151123_challenge_242_easy_funny_plant/
**Description**
Scientist have discovered a new plant. The fruit of the plant can feed 1 person for a whole week and best of all, the
plant never dies.
Fruits needs 1 w... | """
[2015-11-23] Challenge # 242 [easy] Funny plant
https://www.reddit.com/r/dailyprogrammer/comments/3twuwf/20151123_challenge_242_easy_funny_plant/
**Description**
Scientist have discovered a new plant. The fruit of the plant can feed 1 person for a whole week and best of all, the
plant never dies.
Fruits needs 1 w... |
ReLU
[[0.0540062, -2.61092, -0.180027, 0.242194, 0.141407], [-1.12374, 0.0263619, -0.00917929, 0.055623, -0.327635], [0.196019, 0.242159, 0.638452, -0.478265, 0.142577], [-1.63015, -0.0344447, -0.00605492, 0.0112076, -0.0104997], [-0.355133, 0.565969, 0.228267, 0.177342, -0.208078], [-0.0341918, 1.4957, -1.53371, 0.040... | ReLU
[[0.0540062, -2.61092, -0.180027, 0.242194, 0.141407], [-1.12374, 0.0263619, -0.00917929, 0.055623, -0.327635], [0.196019, 0.242159, 0.638452, -0.478265, 0.142577], [-1.63015, -0.0344447, -0.00605492, 0.0112076, -0.0104997], [-0.355133, 0.565969, 0.228267, 0.177342, -0.208078], [-0.0341918, 1.4957, -1.53371, 0.040... |
{
"targets": [{
"target_name": "alienfx",
"sources": [
"sources/binding/alienfx.cc",
"sources/binding/sync/alienfxSync.cc",
"sources/binding/async/alienfxAsync.cc",
"sources/binding/objects/alienfxObjects.cc",
"sources/binding/contracts.cc"... | {'targets': [{'target_name': 'alienfx', 'sources': ['sources/binding/alienfx.cc', 'sources/binding/sync/alienfxSync.cc', 'sources/binding/async/alienfxAsync.cc', 'sources/binding/objects/alienfxObjects.cc', 'sources/binding/contracts.cc'], 'include_dirs': ['dependencies/alienfxsdk/include'], 'conditions': [["OS=='win'"... |
class Sequence:
"""
A class for performing sequence manipulations
"""
def __init__(self, seq):
self.seq = seq
self.comp_seq = ''
self.alphabet = []
self.mapping = {}
def __repr__(self):
return f'{type(self).__name__}(seq="{self.seq[0:10]}...")'
def coun... | class Sequence:
"""
A class for performing sequence manipulations
"""
def __init__(self, seq):
self.seq = seq
self.comp_seq = ''
self.alphabet = []
self.mapping = {}
def __repr__(self):
return f'{type(self).__name__}(seq="{self.seq[0:10]}...")'
def coun... |
"""{{ cookiecutter.package_name }} - {{ cookiecutter.package_description }}"""
# __version__ = "0.0.1"
# __author__ = "Tianyi Shi"
# __all__ = []
| """{{ cookiecutter.package_name }} - {{ cookiecutter.package_description }}""" |
#method 'strip' deletes all empty spaces in string
address = " 18 Main Street "
print(address.strip())
#method 'rstrip' deletes empty spaces just from right
#method 'lstrip' deletes empty spaces just from left
address = "18 Main Street "
print(address.rstrip())
address = " 18 Main Street"
print(add... | address = ' 18 Main Street '
print(address.strip())
address = '18 Main Street '
print(address.rstrip())
address = ' 18 Main Street'
print(address.lstrip()) |
"""Webarchive-related exceptions."""
__all__ = ["WebArchiveError"]
class WebArchiveError(Exception):
"""Class representing an error in an operation on a WebArchive."""
pass
| """Webarchive-related exceptions."""
__all__ = ['WebArchiveError']
class Webarchiveerror(Exception):
"""Class representing an error in an operation on a WebArchive."""
pass |
# Challenge 1
# vowels -> g
# ------------
# dog -> dgg
# cat -> cgt
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation... | def translate(phrase):
translation = ''
for letter in phrase:
if letter.lower() in 'aeiou':
if letter.isupper():
translation = translation + 'G'
else:
translation = translation + 'g'
else:
translation = translation + letter
... |
def solve(n: int) -> int:
digisum = 0
while n > 0:
digi = n % 10
if digi < 9 and digi+10 <= n:
digi += 10
n = (n-digi)/10
digisum += digi
return digisum | def solve(n: int) -> int:
digisum = 0
while n > 0:
digi = n % 10
if digi < 9 and digi + 10 <= n:
digi += 10
n = (n - digi) / 10
digisum += digi
return digisum |
hero_classes = {
'Warrior': {
'max hp': 12,
'attack': 3,
'defense': 2,
'speed': 0,
'hp per level': 2,
'attack per level': 3,
'defense per level': 2,
'speed per level': 1
},
'Archer': {
'max hp': 8,
'attack': 5,
'defense'... | hero_classes = {'Warrior': {'max hp': 12, 'attack': 3, 'defense': 2, 'speed': 0, 'hp per level': 2, 'attack per level': 3, 'defense per level': 2, 'speed per level': 1}, 'Archer': {'max hp': 8, 'attack': 5, 'defense': 1, 'speed': 2, 'hp per level': 2, 'attack per level': 4, 'defense per level': 1, 'speed per level': 1}... |
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'auto_bisect',
'bisect_tester',
'chromium',
'chromium_tests',
'depot_tools/gclient',
'recipe_engine/json',
'recipe_e... | deps = ['auto_bisect', 'bisect_tester', 'chromium', 'chromium_tests', 'depot_tools/gclient', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/raw_io', 'recipe_engine/step']
def run_steps(api):
mastername = api.properties.get('mastername')
buildern... |
class PlaceAction:
def __init__(self, piece, new_pos):
self.piece = piece
self.new_pos = new_pos
class MoveAction:
def __init__(self, piece, old_pos, new_pos):
self.piece = piece.at(new_pos)
self.old_pos = old_pos
self.new_pos = new_pos
class RemoveAction:
de... | class Placeaction:
def __init__(self, piece, new_pos):
self.piece = piece
self.new_pos = new_pos
class Moveaction:
def __init__(self, piece, old_pos, new_pos):
self.piece = piece.at(new_pos)
self.old_pos = old_pos
self.new_pos = new_pos
class Removeaction:
def __... |
# not used
# Pong-v0 action mapping
# action_dict = {0: 0, 1: 2, 2: 3}
num_actions = 2
ob_shape = (400, 400) | num_actions = 2
ob_shape = (400, 400) |
a = 3
b = "true"
c = 1,2,3
print(a) # a+2 and print(a) both use different forms of a, namely int and str
print(b)
print(c)
| a = 3
b = 'true'
c = (1, 2, 3)
print(a)
print(b)
print(c) |
class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
row_max = grid[0] # first row
col_max = [grid[i][0] for i in range(len(grid))] # first col
bottom = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 0: botto... | class Solution:
def projection_area(self, grid: List[List[int]]) -> int:
row_max = grid[0]
col_max = [grid[i][0] for i in range(len(grid))]
bottom = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] != 0:
bottom ... |
class Test:
def __init__(self):
self.a = 1
def func1():
pass
test = Test()
print(hasattr(test, 'a'))
print(hasattr(test, 'b'))
print(hasattr(test, 'func1')) | class Test:
def __init__(self):
self.a = 1
def func1():
pass
test = test()
print(hasattr(test, 'a'))
print(hasattr(test, 'b'))
print(hasattr(test, 'func1')) |
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
maxFreq = 0
count = defaultdict(int)
for row in wall:
prefix = 0
for i in range(len(row) - 1):
prefix += row[i]
count[prefix] += 1
maxFreq = max(maxFreq, count[prefix])
return len(wall) - maxFreq... | class Solution:
def least_bricks(self, wall: List[List[int]]) -> int:
max_freq = 0
count = defaultdict(int)
for row in wall:
prefix = 0
for i in range(len(row) - 1):
prefix += row[i]
count[prefix] += 1
max_freq = max(ma... |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def coverPoints(self, A, B):
stepcount = 0
acount = A[0]
bcount = B[0]
for i in range(len(A)-1):
cx = A[i]
cy = B[i]
nx = A[i+1]
... | class Solution:
def cover_points(self, A, B):
stepcount = 0
acount = A[0]
bcount = B[0]
for i in range(len(A) - 1):
cx = A[i]
cy = B[i]
nx = A[i + 1]
ny = B[i + 1]
xdis = abs(cx - nx)
ydis = abs(cy - ny)
... |
# Camiseta: Escreva uma funcao chamada make_shirt() que aceite um tamanho e o texto de uma mensagem que devera' ser estampada na camiseta. A funcao deve exibir uma frase que mostre o tamanho da camiseta e a mensagem estampada.
# ARGUMENTOS POSICIONAIS
def make_shirt(size, msg):
cont = len(msg)
print("=="*20)
... | def make_shirt(size, msg):
cont = len(msg)
print('==' * 20)
print(f"The requested shirt has '{size}' size and '{msg}' as a mensage whit {cont} caracters.".strip())
print('==' * 20)
make_shirt('M', 'Love Python')
make_shirt(size='M', msg='Love Python') |
"""
Given an array arr[] and an integer K where K is smaller than size of array,
the task is to find the Kth smallest element in the given array.
It is given that all array elements are distinct.
Input: arr[] = 7 10 4 3 20 15; K = 3
Output: 7
Explanation: 3rd smallest element in the given array is 7.
Solution: We are... | """
Given an array arr[] and an integer K where K is smaller than size of array,
the task is to find the Kth smallest element in the given array.
It is given that all array elements are distinct.
Input: arr[] = 7 10 4 3 20 15; K = 3
Output: 7
Explanation: 3rd smallest element in the given array is 7.
Solution: We are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.