content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
sequence, base, result = '123456789', 10, []
for length in range(len(str(low)), len(str(high)) + 1):
for start in range(base - length):
number = int(sequence[start : start + length])
... | class Solution:
def sequential_digits(self, low: int, high: int) -> List[int]:
(sequence, base, result) = ('123456789', 10, [])
for length in range(len(str(low)), len(str(high)) + 1):
for start in range(base - length):
number = int(sequence[start:start + length])
... |
while True:
try:
comprimento, eventos = [int(x) for x in input().split()]
except EOFError:
break
lucro, utilizado, estacionamento = 0, 0, {} # 'veic' : tamanho
for aux in range(0, eventos):
evento = input().split(' ')
if len(evento) == 3: # entrada veic
if c... | while True:
try:
(comprimento, eventos) = [int(x) for x in input().split()]
except EOFError:
break
(lucro, utilizado, estacionamento) = (0, 0, {})
for aux in range(0, eventos):
evento = input().split(' ')
if len(evento) == 3:
if comprimento >= utilizado + int(... |
class EmbeddedDocumentMixin:
_fields = {}
_db_name_map = {}
_dirty_fields = {}
def __init__(self, **kwargs):
self._values = {}
for name, value in kwargs.items():
if name in self._fields:
setattr(self, name, value)
self._make_clean()
def to_mongo(... | class Embeddeddocumentmixin:
_fields = {}
_db_name_map = {}
_dirty_fields = {}
def __init__(self, **kwargs):
self._values = {}
for (name, value) in kwargs.items():
if name in self._fields:
setattr(self, name, value)
self._make_clean()
def to_mong... |
with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
total = 0
group_answers = {}
for line in input:
if not line:
total += len(group_answers)
group_answers = {}
for char in line:
group_answers[char] = 1
total += len(group_answers)
print(total)
| with open('input.txt', 'r') as input_file:
input = input_file.read().split('\n')
total = 0
group_answers = {}
for line in input:
if not line:
total += len(group_answers)
group_answers = {}
for char in line:
group_answers[char] = 1
total += len(group_answers)
print(total) |
# This file is implements of 'The elements of computer systesm'
# chap 6.Assembler
# author:gongqingkui AT 126.com
# date:2021-09-18
jumpTable = {
'null': '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '111'}
compTable = {
# a = 0 ... | jump_table = {'null': '000', 'JGT': '001', 'JEQ': '010', 'JGE': '011', 'JLT': '100', 'JNE': '101', 'JLE': '110', 'JMP': '111'}
comp_table = {'0': '0101010', '1': '0111111', '-1': '0111010', 'D': '0001100', 'A': '0110000', '!D': '0001101', '!A': '0110001', '-D': '0001111', '-A': '0110011', 'D+1': '0011111', 'A+1': '0110... |
# -*- encoding: utf-8 -*-
'''
__author__ = "Larry_Pavanery
'''
class User(object):
def __init__(self, id, url_keys=[]):
self.id = id
self.url_keys = url_keys
| """
__author__ = "Larry_Pavanery
"""
class User(object):
def __init__(self, id, url_keys=[]):
self.id = id
self.url_keys = url_keys |
def vmax(lista):
n = 0
for c in range(len(lista)):
for i in range(len(lista)):
if lista[i] > lista[c]:
n = i
return n
freq = []
num = int(input())
lista = list(range(2, num + 1))
n = num
n_1 = 0
c = 0
while True:
print(n_1)
if n_1 <= len(lista) - 1:
if n... | def vmax(lista):
n = 0
for c in range(len(lista)):
for i in range(len(lista)):
if lista[i] > lista[c]:
n = i
return n
freq = []
num = int(input())
lista = list(range(2, num + 1))
n = num
n_1 = 0
c = 0
while True:
print(n_1)
if n_1 <= len(lista) - 1:
if n %... |
mp = 'Today is a Great DAY'
print(mp.lower())
print(mp.upper())
print(mp.strip())
print(mp.startswith('w'))
print(mp.find('a'))
| mp = 'Today is a Great DAY'
print(mp.lower())
print(mp.upper())
print(mp.strip())
print(mp.startswith('w'))
print(mp.find('a')) |
# Programa que le a altura de uma parede em metros
# e calcule a sua area e a quantidade de tinta necessaria
# para pinta-la, sabendo que cada litro de tinta, pinta uma area
# de 2m^2
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = larg * alt
tinta = area / ... | larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = larg * alt
tinta = area / 2
print('A parede tem {}{}{} metros quadrados e para pintar essa parede precisaremos de {} litros de tintas'.format('\x1b[1;107m', area, '\x1b[m', tinta)) |
#----------* CHALLENGE 37 *----------
#Ask the user to enter their name and display each letter in their name on a separate line.
name = input("Enter your name: ")
for i in name:
print(i)
| name = input('Enter your name: ')
for i in name:
print(i) |
class Camera(object):
def __init__(self, macaddress, lastsnap='snaps/default.jpg'):
self.macaddress = macaddress
self.lastsnap = lastsnap | class Camera(object):
def __init__(self, macaddress, lastsnap='snaps/default.jpg'):
self.macaddress = macaddress
self.lastsnap = lastsnap |
# coding: utf-8
strings = ['KjgWZC', 'arf12', '']
for s in strings:
if s.isalpha():
print("The string " + s + " consists of all letters.")
else:
print("The string " + s + " does not consist of all letters.")
| strings = ['KjgWZC', 'arf12', '']
for s in strings:
if s.isalpha():
print('The string ' + s + ' consists of all letters.')
else:
print('The string ' + s + ' does not consist of all letters.') |
'''
In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com.
They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app... | """
In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com.
They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app... |
class CardError(Exception):
pass
class IssuerNotRecognised(CardError):
pass
class InvalidCardNumber(CardError):
pass
| class Carderror(Exception):
pass
class Issuernotrecognised(CardError):
pass
class Invalidcardnumber(CardError):
pass |
def Wspak(dane):
for i in range(len(dane)-1, -1, -1):
yield dane[i]
tablica = Wspak([1, 2, 3])
print('tablica [1, 2, 3]', end=' ')
print('[', end='')
print(next(tablica), end=', ')
print(next(tablica), end=', ')
print(next(tablica), end=']')
print() | def wspak(dane):
for i in range(len(dane) - 1, -1, -1):
yield dane[i]
tablica = wspak([1, 2, 3])
print('tablica [1, 2, 3]', end=' ')
print('[', end='')
print(next(tablica), end=', ')
print(next(tablica), end=', ')
print(next(tablica), end=']')
print() |
class Solution:
def getHint(self, secret, guess):
ss, gs = {str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)}
A = 0
for s, g in zip(secret, guess):
if s == g: A += 1
ss[s] += 1
gs[g] += 1
ans = 0
for k, v in ss.items():
... | class Solution:
def get_hint(self, secret, guess):
(ss, gs) = ({str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)})
a = 0
for (s, g) in zip(secret, guess):
if s == g:
a += 1
ss[s] += 1
gs[g] += 1
ans = 0
for (k, ... |
class Sample:
def __init__(self, source=None, data=None, history=None, uid=None):
if history is not None:
self.history = history
elif source is not None:
self.history = [("init", "", source)]
else:
self.history = []
if data is not None:
... | class Sample:
def __init__(self, source=None, data=None, history=None, uid=None):
if history is not None:
self.history = history
elif source is not None:
self.history = [('init', '', source)]
else:
self.history = []
if data is not None:
... |
# class Solution:
# # @param A : integer
# # @return a strings
def findDigitsInBinary(self, A):
res = ""
while(A != 0):
temp = A%2
res += str(temp)
A = A//2
res = res[::-1]
return res
print(findDigitsInBinary(6))
| def find_digits_in_binary(self, A):
res = ''
while A != 0:
temp = A % 2
res += str(temp)
a = A // 2
res = res[::-1]
return res
print(find_digits_in_binary(6)) |
pygame, random, sys
pygame.init()
screen_width, screen_height = 400, 600
SCORE_FONT = pygame.font.SysFont('comicsans', 40)
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Stack towers")
BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
YELLOW = (255,212,... | (pygame, random, sys)
pygame.init()
(screen_width, screen_height) = (400, 600)
score_font = pygame.font.SysFont('comicsans', 40)
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Stack towers')
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
yellow = ... |
def main():
pins = {}
subconnectors = ["A", "B", "C", "D"]
curr_connector = None
with open("pins.txt", "r") as f:
for line in f:
l = line.split("#")[0].strip()
if len(l) == 0:
continue
if l[0] == '.':
curr_connector = l[1:]
... | def main():
pins = {}
subconnectors = ['A', 'B', 'C', 'D']
curr_connector = None
with open('pins.txt', 'r') as f:
for line in f:
l = line.split('#')[0].strip()
if len(l) == 0:
continue
if l[0] == '.':
curr_connector = l[1:]
... |
stations = [
'12th St. Oakland City Center',
'16th St. Mission (SF)',
'19th St. Oakland',
'24th St. Mission (SF)',
'Ashby (Berkeley)',
'Balboa Park (SF)',
'Bay Fair (San Leandro)',
'Castro Valley',
'Civic Center (SF)',
'Coliseum/Oakland Airport',
'Colma',
'Concord',
'... | stations = ['12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', 'Daly City', 'Downtown Berkeley', 'Dublin/Pleasanton',... |
def palindrome(word, index):
second_index = len(word) - 1 - index
if index == len(word) // 2:
return f"{word} is a palindrome"
if word[index] == word[second_index]:
return palindrome(word, index + 1)
else:
return f"{word} is not a palindrome"
print(palindrome("abcba",... | def palindrome(word, index):
second_index = len(word) - 1 - index
if index == len(word) // 2:
return f'{word} is a palindrome'
if word[index] == word[second_index]:
return palindrome(word, index + 1)
else:
return f'{word} is not a palindrome'
print(palindrome('abcba', 0))
print(p... |
# Configuration file for the Sphinx documentation builder.
# -- Project information
project = 'PDFsak'
copyright = '2021, Raffaele Mancuso'
author = 'Raffaele Mancuso'
release = '1.1'
version = '1.1.1'
# -- General configuration
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.au... | project = 'PDFsak'
copyright = '2021, Raffaele Mancuso'
author = 'Raffaele Mancuso'
release = '1.1'
version = '1.1.1'
extensions = ['sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('https://docs.python.org/3/', None)... |
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")'
s2 = '+'.join(['\'{}\''.format(x) for x in s])
print('(lambda:sandboxed_eval({}))()'.format(s2))
| s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")'
s2 = '+'.join(["'{}'".format(x) for x in s])
print('(lambda:sandboxed_eval({}))()'.format(s2)) |
def isMAC48Address(inputString):
letters = ['A','B', 'C','D','E','F']
string = inputString.split('-')
input = len(string)
if input != 6:
return False
for i in range(input):
subInput = string[i]
subString = len(subInput)
if subString != 2:
return False
... | def is_mac48_address(inputString):
letters = ['A', 'B', 'C', 'D', 'E', 'F']
string = inputString.split('-')
input = len(string)
if input != 6:
return False
for i in range(input):
sub_input = string[i]
sub_string = len(subInput)
if subString != 2:
return Fa... |
#!/usr/bin/env python
## Global macros
SNIFF_TIMEOUT = 5
AGGREGATION_TIMEOUT = 5
ACTIVE_TIMEOUT = 20 ## If a flow doesn't have a packet traversing a router during ACTIVE_TIMEOUT, it will be removed from monitored flows
BATCH_SIZE = 1000
MAX_BG_TRAFFIC_TO_READ = 5000
MIN_REPORT_SIZE = 600 ## Only send summary report if... | sniff_timeout = 5
aggregation_timeout = 5
active_timeout = 20
batch_size = 1000
max_bg_traffic_to_read = 5000
min_report_size = 600
bg_traffic_size = 900
svd_matrix_rank = 12
kmean_num_clusters = 200
max_summary_id = 100
g_background_traffic = {} |
class AirTable:
# AirTable configuration variables
API_KEY = ''
BASE = ''
PROJECT_TABLE_NAME = ''
PROJECT_PHASE_OWNERS_TABLE = ''
PROJECT_PHASE_FIELD = ''
ASSIGNEE_FIELD = '' | class Airtable:
api_key = ''
base = ''
project_table_name = ''
project_phase_owners_table = ''
project_phase_field = ''
assignee_field = '' |
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
| n = int(input('Enter a number:'))
tot = 0
while n > 0:
dig = n % 10
tot = tot + dig
n = n // 10
print('The total sum of digits is:', tot) |
class Node:
'''This class is just for creating a Node with some data, thats why we set the refrence field to Null'''
def __init__(self, data):
self.data = data
self.nref = None
self.pref = None
class Doubly_LL:
'''This class is for performing the operations to the node which w... | class Node:
"""This class is just for creating a Node with some data, thats why we set the refrence field to Null"""
def __init__(self, data):
self.data = data
self.nref = None
self.pref = None
class Doubly_Ll:
"""This class is for performing the operations to the node which we cre... |
#
# PySNMP MIB module ZYXEL-IF-LOOPBACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-IF-LOOPBACK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:44:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
expansion_dates = [
["2017-09-06", "D2 Vanilla"],
["2018-09-04", "Forsaken"],
["2019-10-01", "Shadowkeep"],
["2020-11-10", "Beyond Light"],
["2022-22-02", "Witch Queen"],
]
season_dates = [
["2017-12-05", "Curse of Osiris"],
["2018-05-08", "Warmind"],
["2018-12-04", "Season of the Forge... | expansion_dates = [['2017-09-06', 'D2 Vanilla'], ['2018-09-04', 'Forsaken'], ['2019-10-01', 'Shadowkeep'], ['2020-11-10', 'Beyond Light'], ['2022-22-02', 'Witch Queen']]
season_dates = [['2017-12-05', 'Curse of Osiris'], ['2018-05-08', 'Warmind'], ['2018-12-04', 'Season of the Forge'], ['2019-03-05', 'Season of the Dri... |
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
maxProfitSoFar = 0
buy = prices[0]
for i in range(1, len(prices)):
cur ... | class Solution:
def max_profit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
max_profit_so_far = 0
buy = prices[0]
for i in range(1, len(prices)):
cur = prices[i]
cur_profit = cur - buy
if curProfit < 0:
... |
# Variables to be overriden by template_vars.mk via jinja
# watch the string quoting.
RUNAS = "{{MLDB_USER}}"
HTTP_LISTEN_PORT = {{MLDB_LOGGER_HTTP_PORT}}
| runas = '{{MLDB_USER}}'
http_listen_port = {{MLDB_LOGGER_HTTP_PORT}} |
class IIDError:
INTERNAL_ERROR = 'internal-error'
UNKNOWN_ERROR = 'unknown-error'
INVALID_ARGUMENT = 'invalid-argument'
AUTHENTICATION_ERROR = 'authentication-error'
SERVER_UNAVAILABLE = 'server-unavailable'
ERROR_CODES = {
400: INVALID_ARGUMENT,
401: AUTHENTICATION_ERROR,
... | class Iiderror:
internal_error = 'internal-error'
unknown_error = 'unknown-error'
invalid_argument = 'invalid-argument'
authentication_error = 'authentication-error'
server_unavailable = 'server-unavailable'
error_codes = {400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, 403: AUTHENTICATION_ERR... |
PATH_TO_DATASET = "houseprice.csv"
TARGET = 'SalePrice'
CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure',
'FireplaceQu', 'GarageType', 'GarageFinish']
NUMERICAL_TO_IMPUTE = ['LotFrontage']
YEAR_VARIABLE = 'YearRemodAdd'
NUMERICAL_LOG = ['LotFrontage', ... | path_to_dataset = 'houseprice.csv'
target = 'SalePrice'
categorical_to_impute = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish']
numerical_to_impute = ['LotFrontage']
year_variable = 'YearRemodAdd'
numerical_log = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']
categorical_e... |
def get_questions_and_media_attributes(json):
questions=[]
media_attributes=[]
def parse_repeat(r_object):
r_question = r_object['name']
for first_children in r_object['children']:
question = r_question+"/"+first_children['name']
if first_child... | def get_questions_and_media_attributes(json):
questions = []
media_attributes = []
def parse_repeat(r_object):
r_question = r_object['name']
for first_children in r_object['children']:
question = r_question + '/' + first_children['name']
if first_children['type'] in ... |
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
... | auth_password_validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.Num... |
#
# "Client-ID" and "Client-Secret" from https://www.strava.com/settings/api
#
CLIENT_ID = '19661'
CLIENT_SECRET = '673409cdf6d02b8bc47b0e88cd03015283dddba2'
AUTH_URL = 'http://127.0.0.1:7123/auth' | client_id = '19661'
client_secret = '673409cdf6d02b8bc47b0e88cd03015283dddba2'
auth_url = 'http://127.0.0.1:7123/auth' |
WHITE_ON_BLACK = 0
WHITE_ON_BLUE = 1
BLUE_ON_BLACK = 2
RED_ON_BLACK = 3
GREEN_ON_BLACK = 4
YELLOW_ON_BLACK = 5
CYAN_ON_BLACK = 6
MAGENTA_ON_BLACK = 7
WHITE_ON_CYAN = 8
MAGENTA_ON_CYAN = 9
PROTOCOL_NUMBERS = {
0: "HOPOPT",
1: "ICMP",
2: "IGMP",
3: "GGP",
4: "IPv4",
5: "ST",
6: "TCP",
7: ... | white_on_black = 0
white_on_blue = 1
blue_on_black = 2
red_on_black = 3
green_on_black = 4
yellow_on_black = 5
cyan_on_black = 6
magenta_on_black = 7
white_on_cyan = 8
magenta_on_cyan = 9
protocol_numbers = {0: 'HOPOPT', 1: 'ICMP', 2: 'IGMP', 3: 'GGP', 4: 'IPv4', 5: 'ST', 6: 'TCP', 7: 'CBT', 8: 'EGP', 9: 'IGP', 10: 'BB... |
type_ = "postgresql"
username = ""
password = ""
address = ""
database = ""
sort_keys = True
secret_key = ""
debug = True
app_host = "0.0.0.0"
| type_ = 'postgresql'
username = ''
password = ''
address = ''
database = ''
sort_keys = True
secret_key = ''
debug = True
app_host = '0.0.0.0' |
# -*- coding: utf-8 -*-
qntMedidaVelocidadeMotor = int(input())
listMedidaVelocidade = list(map(int, input().split()))
indiceMedidaMenor = 0
for indiceMedida in range(1, qntMedidaVelocidadeMotor):
if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]:
indiceMedidaMenor = indiceMed... | qnt_medida_velocidade_motor = int(input())
list_medida_velocidade = list(map(int, input().split()))
indice_medida_menor = 0
for indice_medida in range(1, qntMedidaVelocidadeMotor):
if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]:
indice_medida_menor = indiceMedida + 1
... |
'''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
'''
class Solution:
def findDuplicate(self, nu... | """
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
"""
class Solution:
def find_duplicate(self, n... |
#!python
class Person:
def __init__(self, initialAge):
self.age = initialAge if initialAge >= 0 else 0
if initialAge < 0:
print("Age is not valid, setting age to 0.")
def amIOld(self):
if self.age < 13:
print("You are young.")
elif self.age < 18:
... | class Person:
def __init__(self, initialAge):
self.age = initialAge if initialAge >= 0 else 0
if initialAge < 0:
print('Age is not valid, setting age to 0.')
def am_i_old(self):
if self.age < 13:
print('You are young.')
elif self.age < 18:
pr... |
MotorDriverDirection = [
'forward',
'backward',
]
class MotorDriver():
def __init__(self):
self.PWMA = 0
self.AIN1 = 1
self.AIN2 = 2
self.PWMB = 5
self.BIN1 = 3
self.BIN2 = 4
def MotorRun(self, pwm, motor, index, speed):
if speed > 100:
... | motor_driver_direction = ['forward', 'backward']
class Motordriver:
def __init__(self):
self.PWMA = 0
self.AIN1 = 1
self.AIN2 = 2
self.PWMB = 5
self.BIN1 = 3
self.BIN2 = 4
def motor_run(self, pwm, motor, index, speed):
if speed > 100:
return... |
#counting sort
l = []
n = int(input("Enter number of elements in the list: "))
highest = 0
for i in range(n):
temp = int(input("Enter element"+str(i+1)+': '))
if temp > highest:
highest = temp
l += [temp]
def counting_sort(l,h):
bookkeeping = [0 for i in range(h+1)]
for i in l:... | l = []
n = int(input('Enter number of elements in the list: '))
highest = 0
for i in range(n):
temp = int(input('Enter element' + str(i + 1) + ': '))
if temp > highest:
highest = temp
l += [temp]
def counting_sort(l, h):
bookkeeping = [0 for i in range(h + 1)]
for i in l:
bookkeepin... |
class Source:
'''
Source class to define Source Objects
'''
def __init__(self,id,name,description,url,category,language,country):
self.id =id
self.name = name
self.description= description
self.url = url
self.category = category
self.language = language
... | class Source:
"""
Source class to define Source Objects
"""
def __init__(self, id, name, description, url, category, language, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.language = l... |
class Solution:
def toGoatLatin(self, S: str) -> str:
ans = ''
for i, word in enumerate(S.split()):
if('aiueoAIUEO'.find(word[0]) != -1):
word += 'ma'
else:
word = word[1:] + word[0] + 'ma'
word += 'a' * (i + 1)
ans += w... | class Solution:
def to_goat_latin(self, S: str) -> str:
ans = ''
for (i, word) in enumerate(S.split()):
if 'aiueoAIUEO'.find(word[0]) != -1:
word += 'ma'
else:
word = word[1:] + word[0] + 'ma'
word += 'a' * (i + 1)
ans ... |
def make_bold(func):
def wrapper(*args, **kwargs):
return f'<b>{func(*args, **kwargs)}</b>'
return wrapper
def make_italic(func):
def wrapper(*args, **kwargs):
return f'<i>{func(*args, **kwargs)}</i>'
return wrapper
def make_underline(func):
def wrapper(*args, **kwargs):
... | def make_bold(func):
def wrapper(*args, **kwargs):
return f'<b>{func(*args, **kwargs)}</b>'
return wrapper
def make_italic(func):
def wrapper(*args, **kwargs):
return f'<i>{func(*args, **kwargs)}</i>'
return wrapper
def make_underline(func):
def wrapper(*args, **kwargs):
... |
#Naive vowel removal.
removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem"
charToRemove = ['a', 'e', 'i', 'o', 'u']
... | remove_vowels = 'EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem'
char_to_remove = ['a', 'e', 'i', 'o', 'u']
print(removeVowels)
f... |
class SwanTag:
__tag = None
__link = None
__desc = None
__parent = []
__child = []
__attrs = []
def __init__(self):
pass
| class Swantag:
__tag = None
__link = None
__desc = None
__parent = []
__child = []
__attrs = []
def __init__(self):
pass |
N = int(input())
def explosion_3(n):
n_pos_B = [0 for i in range(n)]
n_pos_A = [0 for i in range(n)]
n_pos_C = [0 for i in range(n)]
n_pos_B[0] = 1
n_pos_A[0] = 1
n_pos_C[0] = 1
for i in range(1, n):
n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_B[i] ... | n = int(input())
def explosion_3(n):
n_pos_b = [0 for i in range(n)]
n_pos_a = [0 for i in range(n)]
n_pos_c = [0 for i in range(n)]
n_pos_B[0] = 1
n_pos_A[0] = 1
n_pos_C[0] = 1
for i in range(1, n):
n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1]
n_pos_B[i] = ... |
class InstanceStack(object):
def __init__(self, max_stack):
self._max_stack = max_stack
self._stack = []
def __contains__(self, name):
return name in map(lambda instance: instance.get_arch_name(), self._stack)
def __getitem__(self, name):
for instance in self._stack:
... | class Instancestack(object):
def __init__(self, max_stack):
self._max_stack = max_stack
self._stack = []
def __contains__(self, name):
return name in map(lambda instance: instance.get_arch_name(), self._stack)
def __getitem__(self, name):
for instance in self._stack:
... |
# URI Online Judge 2756
diamond = [
' A',
' B B',
' C C',
' D D',
' E E',
' D D',
' C C',
' B B',
' A',
]
for line in diamond:
print(line)
| diamond = [' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A']
for line in diamond:
print(line) |
# Write and test a function threshold(vals, goal)
# where vals is a sequence of numbers and goal is a positive number.
# The function returns the smallest integer n such that the sum of
# the first n numbers in vals is >= goal. If the goal is
# unachievable, the function returns 0
def func(data, goal):
n = int... | def func(data, goal):
n = int()
pos = int()
for (i, v) in enumerate(data):
if n < goal:
n += v
pos = i
elif n >= goal:
pos = i
break
if n < goal:
return 0
return i
dd = [1, 1, 2, 3, 4, 5]
gg = 10
a = func(dd, gg)
print(a) |
def main() -> None:
# binary search
n = int(input())
a = list(map(int, input().split()))
def binary_search_average() -> float:
def possible_more_than(average: float) -> bool:
b = [x - average for x in a]
dp = [[0.0, 0.0] for _ in range(n + 1)]
# not-... | def main() -> None:
n = int(input())
a = list(map(int, input().split()))
def binary_search_average() -> float:
def possible_more_than(average: float) -> bool:
b = [x - average for x in a]
dp = [[0.0, 0.0] for _ in range(n + 1)]
for i in range(n):
... |
# /home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser_tables.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '4\xa4a\x00\xea\xcdZp5\xc6@\xa5\xfa\x1dCA'
_lr_action_items = {'NONE_TOK':([8,12,24,26,],[11,11,11,11,]),'LP_TOK':(... | _tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = '4¤a\x00êÍZp5Æ@¥ú\x1dCA'
_lr_action_items = {'NONE_TOK': ([8, 12, 24, 26], [11, 11, 11, 11]), 'LP_TOK': ([5, 8, 12, 24, 26], [8, 12, 12, 12, 12]), 'STRING_TOK': ([8, 12, 24, 26], [13, 13, 13, 13]), 'RP_TOK': ([8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 26, 27,... |
def funny_division(anumber):
try:
return 100 / anumber
except ZeroDivisionError:
return "Silly wabbit, you can't divide by zero!"
print(funny_division(0))
print(funny_division(50.0))
print(funny_division("hello"))
| def funny_division(anumber):
try:
return 100 / anumber
except ZeroDivisionError:
return "Silly wabbit, you can't divide by zero!"
print(funny_division(0))
print(funny_division(50.0))
print(funny_division('hello')) |
with sqlite3.connect(DATABASE) as db:
db.execute(SQL_CREATE_TABLE)
db.executemany(SQL_INSERT, DATA)
result = list(db.execute(SQL_SELECT))
| with sqlite3.connect(DATABASE) as db:
db.execute(SQL_CREATE_TABLE)
db.executemany(SQL_INSERT, DATA)
result = list(db.execute(SQL_SELECT)) |
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
... | class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
... |
src =Split('''
uData_sample.c
''')
component =aos_component('uDataapp', src)
dependencis =Split('''
tools/cli
framework/netmgr
framework/common
device/sensor
framework/uData
''')
for i in dependencis:
component.add_comp_deps(i)
global_includes =Split('''
.
''')
for i in global_inclu... | src = split(' \n uData_sample.c\n')
component = aos_component('uDataapp', src)
dependencis = split(' \n tools/cli\n framework/netmgr\n framework/common\n device/sensor\n framework/uData\n')
for i in dependencis:
component.add_comp_deps(i)
global_includes = split(' \n .\n')
for i in global_inclu... |
{
'name': 'Chapter 05, Recipe 1 code',
'summary': 'Report errors to the user',
'depends': ['base'],
}
| {'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base']} |
config = {
"interfaces": {
"google.pubsub.v1.Subscriber": {
"retry_codes": {
"idempotent": ["ABORTED", "UNAVAILABLE", "UNKNOWN"],
"non_idempotent": ["UNAVAILABLE"],
"none": [],
},
"retry_params": {
"default":... | config = {'interfaces': {'google.pubsub.v1.Subscriber': {'retry_codes': {'idempotent': ['ABORTED', 'UNAVAILABLE', 'UNKNOWN'], 'non_idempotent': ['UNAVAILABLE'], 'none': []}, 'retry_params': {'default': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_timeo... |
class EntrySupport(object):
mixin = 'Entry'
class Reporter(object):
def __init__(self, model, subject=None):
if subject:
subject = subject.strip(':')
self.model = model
self.subject = subject
def __call__(self, tag, subject=None, entry=None,... | class Entrysupport(object):
mixin = 'Entry'
class Reporter(object):
def __init__(self, model, subject=None):
if subject:
subject = subject.strip(':')
self.model = model
self.subject = subject
def __call__(self, tag, subject=None, entry=None,... |
class BouncingBall(object):
def __init__(self, x, y, dia, col):
self.location = PVector(x, y)
self.velocity = PVector(0, 0)
self.d = dia
self.col = col
self.gravity = 0.1
self.dx = 2
def move(self):
# self.location.x += self.dx
s... | class Bouncingball(object):
def __init__(self, x, y, dia, col):
self.location = p_vector(x, y)
self.velocity = p_vector(0, 0)
self.d = dia
self.col = col
self.gravity = 0.1
self.dx = 2
def move(self):
self.velocity.y += self.gravity
self.location... |
class errors():
# ***********************************************************************
#
# SpcErr.h = (c) Spectrum GmbH, 2006
#
# ***********************************************************************
#
# error codes of the Spectrum drivers. Until may 2004 this file was
# errors.h. N... | class Errors:
err_ok = 0
err_init = 1
err_nr = 2
err_typ = 3
err_fncnotsupported = 4
err_brdremap = 5
err_kernelversion = 6
err_hwdrvversion = 7
err_adrrange = 8
err_invalidhandle = 9
err_boardnotfound = 10
err_boardinuse = 11
err_lasterr = 16
err_abort = 32
e... |
def get_data_odor_num_val():
# get data
odor = ''
data = []
with open('mushrooms_data.txt') as f:
lines = f.readlines()
for line in lines:
odor = line[10]
if odor == 'a': # almond
data.append(1)
elif odor == 'l': # anise
data.append(2)
... | def get_data_odor_num_val():
odor = ''
data = []
with open('mushrooms_data.txt') as f:
lines = f.readlines()
for line in lines:
odor = line[10]
if odor == 'a':
data.append(1)
elif odor == 'l':
data.append(2)
elif odor == 'c':
da... |
# This problem can be solved analytically, but we can just as well use
# a for loop. For a given shell of side n, the value at the top right
# vertex is given by the area, n^2. Moving anticlockwise, the values at
# the other vertex is always (n - 1) less than the previous vertex.
n_max = 1001
ans = 1 + sum(4*n... | n_max = 1001
ans = 1 + sum((4 * n ** 2 - 6 * (n - 1) for n in range(3, n_max + 1, 2)))
print(ans) |
#Create a converter that changes binary numbers to decimals and vice versa
def b_to_d(number):
var = str(number)[::-1]
counter = 0
decimal = 0
while counter < len(var):
if int(var[counter]) == 1:
decimal += 2**counter
counter += 1
return decimal
def d_to_b(number):
binary = ''
while num... | def b_to_d(number):
var = str(number)[::-1]
counter = 0
decimal = 0
while counter < len(var):
if int(var[counter]) == 1:
decimal += 2 ** counter
counter += 1
return decimal
def d_to_b(number):
binary = ''
while number > 0:
binary += str(number % 2)
... |
#file operations
with open('test.txt', 'r') as f:
#print('file contents using f.read()', f.read())
#print('file contencts using f.readlines()', f.readlines())
#print('file read 1 line using f.readline', f.readline())
print('read line by line, so that there is no memeory issue')
for line in f:
print(line, end = ... | with open('test.txt', 'r') as f:
print('read line by line, so that there is no memeory issue')
for line in f:
print(line, end='')
print()
with open('test.txt', 'r') as f:
print('printing using specific size')
size_to_read = 10
f_contents = f.read(size_to_read)
while len(f_contents) > 0:
... |
_base_ = [
'../../../_base_/datasets/fine_tune_based/few_shot_voc.py',
'../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py',
'../../../_base_/default_runtime.py'
]
# classes splits are predefined in FewShotVOCDataset
# FewShotVOCDefaultDataset predefine ann_cfg for model reproducibility.
data = ... | _base_ = ['../../../_base_/datasets/fine_tune_based/few_shot_voc.py', '../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py', '../../../_base_/default_runtime.py']
data = dict(train=dict(type='FewShotVOCDefaultDataset', ann_cfg=[dict(method='TFA', setting='SPLIT2_10SHOT')], num_novel_shots=10, num_base_shots=... |
class LibraryException(Exception):
pass
class BookException(Exception):
pass
| class Libraryexception(Exception):
pass
class Bookexception(Exception):
pass |
a,b=map(int,input().split())
if b==0 and a>0:
print("Gold")
elif a==0 and b>0:
print("Silver")
elif a>0 and b>0:
print("Alloy")
| (a, b) = map(int, input().split())
if b == 0 and a > 0:
print('Gold')
elif a == 0 and b > 0:
print('Silver')
elif a > 0 and b > 0:
print('Alloy') |
n = int(input())
h = int(input())
w = int(input())
print((n-h+1) * (n-w+1)) | n = int(input())
h = int(input())
w = int(input())
print((n - h + 1) * (n - w + 1)) |
class custom_range:
def __init__(self, start: int, end: int) -> None:
self.start = start
self.end = end
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start <= self.end:
i = self.start
self.start += 1
... | class Custom_Range:
def __init__(self, start: int, end: int) -> None:
self.start = start
self.end = end
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start <= self.end:
i = self.start
self.start += 1
return i... |
ADD_USER_CONTEXT = {
"CyberArkPAS.Users(val.id == obj.id)": {
"authenticationMethod": [
"AuthTypePass"
],
"businessAddress": {
"workCity": "",
"workCountry": "",
"workState": "",
"workStreet": "",
"workZip": ""
},
"changePassOnNextLogon": True,
"componentUse... | add_user_context = {'CyberArkPAS.Users(val.id == obj.id)': {'authenticationMethod': ['AuthTypePass'], 'businessAddress': {'workCity': '', 'workCountry': '', 'workState': '', 'workStreet': '', 'workZip': ''}, 'changePassOnNextLogon': True, 'componentUser': False, 'description': 'new user for test', 'distinguishedName': ... |
# Common training-related configs that are designed for "tools/lazyconfig_train_net.py"
# You can use your own instead, together with your own train_net.py
train = dict(
output_dir="./output",
init_checkpoint="detectron2://ImageNetPretrained/MSRA/R-50.pkl",
max_iter=90000,
amp=dict(enabled=False), # op... | train = dict(output_dir='./output', init_checkpoint='detectron2://ImageNetPretrained/MSRA/R-50.pkl', max_iter=90000, amp=dict(enabled=False), ddp=dict(broadcast_buffers=False, find_unused_parameters=False, fp16_compression=False), checkpointer=dict(period=5000, max_to_keep=100), eval_period=5000, log_period=20, device=... |
s1 = "fairy tales"
s2 = "rail safety"
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
# Requires n log n time (since any comparison
# based sorting algorithm requires at least
# nlogn time to sort).
print(sorted(s1) == sorted(s2))
# The Preferred Solution
# This solution is of linear time complexi... | s1 = 'fairy tales'
s2 = 'rail safety'
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
print(sorted(s1) == sorted(s2))
def is_anagram(s1, s2):
ht = dict()
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
print(s1, ' ', s2)
if len(s1) != len(s2):
return Fal... |
model = Model()
i1 = Input("input", "TENSOR_QUANT8_ASYMM", "{4, 3, 2}, 0.8, 5")
axis = Parameter("axis", "TENSOR_INT32", "{4}", [1, 0, -3, -3])
keepDims = False
output = Output("output", "TENSOR_QUANT8_ASYMM", "{2}, 0.8, 5")
model = model.Operation("REDUCE_MAX", i1, axis, keepDims).To(output)
# Example 1. Input in op... | model = model()
i1 = input('input', 'TENSOR_QUANT8_ASYMM', '{4, 3, 2}, 0.8, 5')
axis = parameter('axis', 'TENSOR_INT32', '{4}', [1, 0, -3, -3])
keep_dims = False
output = output('output', 'TENSOR_QUANT8_ASYMM', '{2}, 0.8, 5')
model = model.Operation('REDUCE_MAX', i1, axis, keepDims).To(output)
input0 = {i1: [1, 2, 3, 4... |
#Your secret information. Make sure you don't tell anyone
secret_key = ''
public_key = ''
url='https://api.paystack.co/transaction'
| secret_key = ''
public_key = ''
url = 'https://api.paystack.co/transaction' |
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
second_num = -math.inf
stck = []
# Try to find nums[i] < second_num < stck[-1]
for i in range(len(nums) - 1, -1, -1):
if nums[i] < second_num:
... | class Solution:
def find132pattern(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
second_num = -math.inf
stck = []
for i in range(len(nums) - 1, -1, -1):
if nums[i] < second_num:
return True
while stck and stck[-1] ... |
class Logger:
# Logger channel.
channel: str
def __init__(self, channel: str):
self.channel = channel
def log(self, message):
print(f'\033[92m[{self.channel}] {message}\033[0m')
def info(self, message):
print(f'\033[94m[{self.channel}] {message}\033[0m')
def warning(s... | class Logger:
channel: str
def __init__(self, channel: str):
self.channel = channel
def log(self, message):
print(f'\x1b[92m[{self.channel}] {message}\x1b[0m')
def info(self, message):
print(f'\x1b[94m[{self.channel}] {message}\x1b[0m')
def warning(self, message):
... |
r=' '
lista=list()
while True:
n=(int(input('digite um numero')))
if n in lista:
print('numero duplicado nao adicionado...')
r = str(input('quer continuar'))
else:
lista.append(n)
print('numero adicionado com sucesso.')
r=str(input('quer continuar'))
if r == 'n... | r = ' '
lista = list()
while True:
n = int(input('digite um numero'))
if n in lista:
print('numero duplicado nao adicionado...')
r = str(input('quer continuar'))
else:
lista.append(n)
print('numero adicionado com sucesso.')
r = str(input('quer continuar'))
if r ==... |
# Almost any value is evaluated to True if it has some sort of content.
#
# Any string is True, except empty strings.
#
# Any number is True, except 0.
#
# Any list, tuple, set, and dictionary are True, except empty ones.
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
| bool('abc')
bool(123)
bool(['apple', 'cherry', 'banana']) |
# Distributed under the MIT software license, see the accompanying
# file LICENSE or https://www.opensource.org/licenses/MIT.
# List of words which are recognized in commands. The display_name method
# also recognizes strings between these words as own words so not all words
# appearing in command names have to be lis... | word_list = ['abort', 'account', 'address', 'balance', 'block', 'by', 'chain', 'change', 'clear', 'connection', 'convert', 'decode', 'fee', 'generate', 'get', 'hash', 'header', 'import', 'info', 'key', 'label', 'message', 'multi', 'network', 'node', 'out', 'psbt', 'pool', 'priv', 'pruned', 'list', 'raw', 'save', 'send'... |
data = {
"red": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)),
"green": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)),
"blue": ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
}
| data = {'red': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))} |
# create template
class DtlTemplateCreateModel:
def __init__(self, name, subject, html_body): # required fields
self.name = name
self.subject = subject
self.html_body = html_body
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object... | class Dtltemplatecreatemodel:
def __init__(self, name, subject, html_body):
self.name = name
self.subject = subject
self.html_body = html_body
self.template_setting_id = None
self.unsubscribe_option = None
def get_json_object(self):
return {'name': self.name, 's... |
ABSOLUTE_URL_OVERRIDES = {}
ADMINS = ()
ADMIN_FOR = ()
ADMIN_MEDIA_PREFIX = '/static/admin/'
ALLOWED_INCLUDE_ROOTS = ()
APPEND_SLASH = True
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
BANNED_IPS = ()
CACHES = {}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDL... | absolute_url_overrides = {}
admins = ()
admin_for = ()
admin_media_prefix = '/static/admin/'
allowed_include_roots = ()
append_slash = True
authentication_backends = ('django.contrib.auth.backends.ModelBackend',)
banned_ips = ()
caches = {}
cache_middleware_alias = 'default'
cache_middleware_key_prefix = ''
cache_middl... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'},
{'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'},
{'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'},
{'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'}... | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'}, {'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'}, {'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'}, {'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'}, {'abbr': 4, 'code': 4, 'title': 'V... |
IMAGE_PATH = "H:\Asu\mwdb\project-phase-0\CSE 515 Fall19 - Smaller Dataset\Phase-1\CSE 515 Fall19 - Smaller Dataset\Hand_0008110.jpg"
IMAGE_FOLDER = "H:\Asu\mwdb\project-phase-0\CSE 515 Fall19 - Smaller Dataset\images"
DATABASE_FOLDER = "H:\Asu\mwdb\project-phase-0\CSE 515 Fall19 - Smaller Dataset\Database\\"
METADA... | image_path = 'H:\\Asu\\mwdb\\project-phase-0\\CSE 515 Fall19 - Smaller Dataset\\Phase-1\\CSE 515 Fall19 - Smaller Dataset\\Hand_0008110.jpg'
image_folder = 'H:\\Asu\\mwdb\\project-phase-0\\CSE 515 Fall19 - Smaller Dataset\\images'
database_folder = 'H:\\Asu\\mwdb\\project-phase-0\\CSE 515 Fall19 - Smaller Dataset\\Data... |
def remove_duplicates(some_list):
return list(set(some_list))
def run():
random_list = [1,1,2,2,4]
print(remove_duplicates(random_list))
if __name__ == '__main__':
run() | def remove_duplicates(some_list):
return list(set(some_list))
def run():
random_list = [1, 1, 2, 2, 4]
print(remove_duplicates(random_list))
if __name__ == '__main__':
run() |
# -*- coding: utf-8 -*-
# Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved.
# Please refer to our terms for more information:
#
# https://www.sqreen.io/terms.html
#
__author__ = "Sqreen"
__copyright__ = "Copyright 2016, 2017, 2018, 2019, Sqreen"
__email__ = "contact@sqreen.io"
__license__ = "propri... | __author__ = 'Sqreen'
__copyright__ = 'Copyright 2016, 2017, 2018, 2019, Sqreen'
__email__ = 'contact@sqreen.io'
__license__ = 'proprietary'
__version__ = '0.4.1' |
# Copyright 2017 Michael Blondin, Alain Finkel, Christoph Haase, Serge Haddad
# 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 requir... | class Configuration:
def __init__(self):
pass
def __eq__(self, other):
raise not_implemented_error()
def __ne__(self, other):
raise not_implemented_error()
def __gt__(self, other):
raise not_implemented_error()
def __ge__(self, other):
raise not_implement... |
class Report(object):
def __init__(self):
self._packets_in_buffer = []
self._packet_wait_time = []
self._server_load = []
def update_state(self, packets_in_buffer, packet_wait_time, server_load):
self._packets_in_buffer.append(packets_in_buffer)
self._packet_wait_time.ap... | class Report(object):
def __init__(self):
self._packets_in_buffer = []
self._packet_wait_time = []
self._server_load = []
def update_state(self, packets_in_buffer, packet_wait_time, server_load):
self._packets_in_buffer.append(packets_in_buffer)
self._packet_wait_time.a... |
# coding=utf-8
if __name__ == "__main__":
print("developing...") | if __name__ == '__main__':
print('developing...') |
ITALY_CITIES = ['Roma', 'Milano']
GERMAN_CITIES = ['Berlin', 'Frankfurt']
US_CITIES = ['Boston', 'Los Angeles']
# Our restaurant is named differently in different
# in different parts of the world
def get_restaurant_name(city: str) -> str:
if city in ITALY_CITIES:
return "Trattoria Viafore"
if city i... | italy_cities = ['Roma', 'Milano']
german_cities = ['Berlin', 'Frankfurt']
us_cities = ['Boston', 'Los Angeles']
def get_restaurant_name(city: str) -> str:
if city in ITALY_CITIES:
return 'Trattoria Viafore'
if city in GERMAN_CITIES:
return "Pat's Kantine"
if city in US_CITIES:
retur... |
training_data_hparams = {
'shuffle': False,
'num_epochs': 1,
'batch_size': 5,
'allow_smaller_final_batch': False,
'source_dataset': {
"files": ['data/iwslt14/train.de'],
'vocab_file': 'data/iwslt14/vocab.de',
'max_seq_length': 50
},
'target_dataset': {
'files'... | training_data_hparams = {'shuffle': False, 'num_epochs': 1, 'batch_size': 5, 'allow_smaller_final_batch': False, 'source_dataset': {'files': ['data/iwslt14/train.de'], 'vocab_file': 'data/iwslt14/vocab.de', 'max_seq_length': 50}, 'target_dataset': {'files': ['data/iwslt14/train.en'], 'vocab_file': 'data/iwslt14/vocab.e... |
def foo(x):
return x**2
def decorator(func):
def wrapper(*args, **kwargs):
print(func, args, kwargs)
return func(*args, **kwargs)
return wrapper
_decorated_funcs = defaultdict(lambda: [])
_applied_decorators = defaultdict(lambda: [])
def apply_decorator(func, decorator):
_decorated_fu... | def foo(x):
return x ** 2
def decorator(func):
def wrapper(*args, **kwargs):
print(func, args, kwargs)
return func(*args, **kwargs)
return wrapper
_decorated_funcs = defaultdict(lambda : [])
_applied_decorators = defaultdict(lambda : [])
def apply_decorator(func, decorator):
_decorate... |
# Created by MechAviv
# ID :: [910150001]
# Frozen Fairy Forest : Elluel
sm.showEffect("Effect/Direction5.img/effect/mercedesInIce/merBalloon/8", 2000, 0, -100, 0, -2, False, 0)
sm.sendDelay(2000)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
sm.progressMessageFont(3, 20, 20, 0, "Pr... | sm.showEffect('Effect/Direction5.img/effect/mercedesInIce/merBalloon/8', 2000, 0, -100, 0, -2, False, 0)
sm.sendDelay(2000)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
sm.progressMessageFont(3, 20, 20, 0, 'Press the Alt key to jump.') |
#!/usr/bin/env python3
input = int(input())
def scores_after_n_receipes(n):
scores = [3, 7]
elfs_positions = [0, 1]
target_scores = n + 10
while len(scores) < target_scores:
new_receipe_score = 0
for i, pos in enumerate(elfs_positions):
new_receipe_score += scores[pos]
... | input = int(input())
def scores_after_n_receipes(n):
scores = [3, 7]
elfs_positions = [0, 1]
target_scores = n + 10
while len(scores) < target_scores:
new_receipe_score = 0
for (i, pos) in enumerate(elfs_positions):
new_receipe_score += scores[pos]
scores.extend(map(... |
# try:
# total = 1/0
# # this will not execute
# except Exception:
# total = 0
# print(total) # 0
# try:
# total = 1/0
# print("This will not show up.")
# except Exception:
# print("Exception was caught") # Exception was caught
# total = 0
# print(total) # 0
# num = input("What is a... | num = input('What is a number? ')
num = int(num)
print(num) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.