content stringlengths 7 1.05M |
|---|
def setup():
#this is your canvas size
size(1000,1000)
#fill(34,45,56,23)
#background(192, 64, 0)
stroke(255)
colorMode(RGB)
strokeWeight(1)
#rect(150,150,150,150)
def draw():
x=mouseX
y=mouseY
ix=width-x
iy=height-y
px=pmouseX
py=pmouseY
... |
def binary_search(coll, elem):
low = 0
high = len(coll) - 1
while low <= high:
middle = (low + high) // 2
guess = coll[middle]
if guess == elem:
return middle
if guess > elem:
high = middle - 1
else:
low = middle + 1
return N... |
# Time Complexity => O(n^2 + log n) ; log n for sorting
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
output = []
nums.sort()
for i in range(len(nums)-2):
if i>0 and nums[i]==nums[i-1]:
continue
j = i+1
k = len(nu... |
# input 3 number and calculate middle number
def Middle_3Num_Calc(a, b, c):
if a >= b:
if b >= c:
return b
elif a <= c:
return a
else:
return c
elif a > c:
return a
elif b > c:
return c
else:
return b
def Middle_3Num_C... |
# -*- coding: utf-8 -*-
class Null(object):
def __init__(self, *args, **kwargs):
return None
def __call__(self, *args, **kwargs):
return self
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
return self
def __delattr__(self, name):
... |
batch_size = 32
epochs = 200
lr = 0.01
momentum = 0.9
no_cuda =False
cuda_id = '0'
seed = 1
log_interval = 10
l2_decay = 5e-4
class_num = 31
param = 0.3
bottle_neck = True
root_path = "/data/zhuyc/OFFICE31/"
source_name = "dslr"
target_name = "amazon"
|
def solution(record):
Change = "Change"
entry = {"Enter": " entered .",
"Leave": " left." }
recs = []
for r in record:
r = r.split(" ")
recs.append(r)
# Change user id for all record first.
for r in recs:
uid = ""
nickname = ""
if (Chang... |
with open("input4.txt") as f:
raw = f.read()
pp = raw.split("\n\n")
ppd = list()
for p in pp:
p = p.replace("\n", " ")
p = p.strip()
if not p:
continue
pairs = p.split(" ")
ppd.append({s.split(":")[0]: s.split(":")[1] for s in pairs})
def isvalid(p):
if not {"byr", "iyr", "eyr", ... |
class Block(object):
def __init__(self, block):
self.block = block
def get_block(self):
return self.block
def set_block(self, new_block):
self.block = new_block
|
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... |
# encoding: utf-8
# Copyright 2012 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
'''EDRN RDF — Errors and other exceptional conditions'''
class RDFUpdateError(Exception):
'''An abstract exception indicating a problem during RDF updates.'''
def __init__(s... |
'''
Problem 48
@author: Kevin Ji
'''
def self_power_with_mod(number, mod):
product = 1
for _ in range(number):
product *= number
product %= mod
return product
MOD = 10000000000
number = 0
for power in range(1, 1000 + 1):
number += self_power_with_mod(power, MOD)
number %= MOD
... |
# Code for demo_03
def captureInfoCam():
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True)
#Azure
face_uri = "https://raspberr... |
wagons = int(input())
wagons_list = [0 for _ in range(wagons)]
command = input().split()
while "End" not in command:
if "add" in command:
wagons_list[-1] += int(command[1])
elif "insert" in command:
wagons_list[int(command[1])] += int(command[2])
elif "leave" in command:
wagons_list... |
# Copyright (C) 2019-2020 Petr Pavlu <setup@dagobah.cz>
# SPDX-License-Identifier: MIT
"""StorePass exceptions."""
class StorePassException(Exception):
"""Base StorePass exception."""
class ModelException(StorePassException):
"""Exception when working with a model."""
class StorageException(StorePassExce... |
#Exercício Python 48: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
soma = 0
cont = 0
for n in range(1, 501, 2):
if n % 3 == 0:
soma = soma + n
cont = cont + 1
print('A soma de todos os {} valores ímpares divíveis ... |
class Solution(object):
def average(self, salary):
"""
:type salary: List[int]
:rtype: float
"""
# Runtime: 24 ms
# Memory: 13.4 MB
# In Python 2, you need to convert the divisor/dividend into float in order to get a float answer
return (sum(salary) -... |
# --------------
##File path for the file
file_path
def read_file(path):
file = open(file_path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
# --------------
#Code starts here
#Function to fuse message
def fuse_msg(message_a,me... |
class Solution:
def partitionLabels(self, string):
"""O(N) time | O(1) space"""
chars = {}
for i, char in enumerate(string):
if char in chars:
chars[char][1] = i
else:
chars[char] = [i, i]
partitions = []
i = prev = 0
... |
# 3.uzdevums
my_name = str(input('Enter sentence '))
words = my_name.split()
rev_list = [word[::-1] for word in words]
rev_string=" ".join(rev_list)
result=rev_string.capitalize()
print(result)
print(" ".join([w[::-1] for w in my_name.split()]).capitalize()) |
# def math(num1, num2, operation='add'):
# if(operation == "mult"):
# return num1 * num2
# if(operation == "div"):
# return num1 / num2
# if(operation == "sub"):
# return num1 - num2
# if(operation == "add"):
# return num1 + num2
# else:
# print("not a valid o... |
"""
Control Flow II - SOLUTION
"""
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. Note : Use 'continue' statement.
for i in range(6):
if (i == 3 or i ==6):
continue
print(i,end=' ')
print("\n") |
""" Euclidean algorithm (greatest common divisor (GCD)) """
def euclidean(a, b):
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
gcd = a or b
return gcd
def test_euclidean():
""" Tests """
assert(euclidean(30, 18) == 6)
assert(euclidean(1... |
tamanho = int(input('Informe o tamanho do arquivo em MB '))
velocidade = int(input('informe a velocidade em Mbps '))
tempo = tamanho/velocidade
tempo = tempo/60
if tempo < 1:
print('Levará menos de 1 minuto ')
else:
print('Levará aproximadamente %d minutos' %(int(tempo)))
|
"""
Classe:
Classes devem comecar com a Letra Maiuscula (camel case : ExemploPessoa)
É a base da OO.
É a fôrma (fôrma de gelo) que define como nossos objetos se comportam. As vezes é utilizado
como sinonimo de "tipo".
Funcao:
Funcoes devem comecar com a letra minuscula (snake_case : exemplo_pessoa)
def: (Metodo)
... |
def binary_search(arr, target):
low, high = 0, len(arr)-1
while low < high:
mid = (low + high)/2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
try:
if arr[high] == target:
return high
else:
return -1
except Ind... |
MOD_ID = 'id'
MOD_RGB = 'rgb'
MOD_SS_DENSE = 'semseg_dense'
MOD_SS_CLICKS = 'semseg_clicks'
MOD_SS_SCRIBBLES = 'semseg_scribbles'
MOD_VALIDITY = 'validity_mask'
SPLIT_TRAIN = 'train'
SPLIT_VALID = 'val'
MODE_INTERP = {
MOD_ID: None,
MOD_RGB: 'bilinear',
MOD_SS_DENSE: 'nearest',
MOD_SS_CLICKS: 'sparse... |
nmbr = 3
if nmbr % 2 == 0:
print("%d is even" % nmbr)
elif nmbr == 0:
print("%d is zero" % nmbr)
else:
print("%d is odd" % nmbr)
free = "free";
print("I am free") if free == "free" else print("I am not free")
# Nested Conditions
nmbr = 4
if nmbr % 2 == 0:
if nmbr % 4 == 0:
print("I can pas... |
class Book:
""" Model for Book object """
def __init__(self, title, author):
self.title = title
self.author = author
self.bookmark = None
self.read = False
def setBookmark(self, page):
""" Sets bookmark attribute of a book to given page """
self.bookmark = page
def read(self):
""" Changes read... |
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right,... |
#!/usr/bin/python3
"""
Part of speech tagging in python using Hidden Markov Model.
POS tagging using Hidden Markov model (Viterbi algorithm)
"""
__author__ = "Sunil"
__copyright__ = "Copyright (c) 2017 Sunil"
__license__ = "MIT License"
__email__ = "suba5417@colorado.edu"
__version__ = "0.1"
class PennTreebank(obje... |
DEBUG = True
SECRET_KEY = 'topsecret'
#SQLALCHEMY_DATABASE_URI = 'postgresql://yazhu:root@localhost/matcha'
# SQLALCHEMY_DATABASE_URI = 'postgresql://jchung:@localhost/matcha'
SQLALCHEMY_DATABASE_URI = 'postgresql://root:1234@localhost/matcha'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ACCOUNT_ACTIVATION = False
ROOT_URL ... |
"""Defines a node for link-based data structures"""
class Node:
"""A node in the linked list"""
def __init__(self, next=None, data=None):
self.next = next
self.data = data
def __eq__(self, other):
return self.data == other.data
def __repr__(self):
return repr(self.data... |
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
map_squares_trees = mensaje.split('\n')
# print(map_squares_trees)
# cantidad de elementos (square or tree) por cada fila
lenght_of_one_line = len(map_squares_trees[0])
pos_columna = 3
pos_linea = 0
iteraciones = 0
tree = ... |
PURCHASE_NO_CLIENT_STATE = 0
PURCHASE_WAITING_STATE = 1
PURCHASE_PLAYAGAIN_STATE = 2
PURCHASE_EXIT_STATE = 3
PURCHASE_DISCONNECTED_STATE = 4
PURCHASE_UNREPORTED_STATE = 10
PURCHASE_REPORTED_STATE = 11
PURCHASE_CANTREPORT_STATE = 12
PURCHASE_COUNTDOWN_TIME = 120
|
# 14. Write a program in Python to calculate the volume of a sphere
rad=int(input("Enter radius of the sphere: "))
vol=(4/3)*3.14*(rad**3)
print("Volume of the sphere= ",vol)
|
'''
Created on Aug 10, 2017
@author: Itai Agmon
'''
class ReportElementType():
REGULAR = "regular"
LINK = "lnk"
IMAGE = "img"
HTML = "html"
STEP = "step"
START_LEVEL = "startLevel"
STOP_LEVEL = "stopLevel"
class ReportElementStatus():
SUCCESS = "success"
WARNING = "warning"
FA... |
{
"targets": [
{
"target_name": "strings",
"sources": ["main.cpp"],
"cflags": ["-Wall", "-Wextra", "-ansi", "-O3"],
"include_dirs" : ["<!(node -e \"require('nan')\")"]
}
]
}
|
# @Title: 图片平滑器 (Image Smoother)
# @Author: KivenC
# @Date: 2018-07-14 14:09:11
# @Runtime: 600 ms
# @Memory: N/A
class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
R, C = len(M), len(M[0])
res = [[0 for _ in... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = {}
for str in strs:
key = ''.join(sorted(str))
if key not in anagrams:
anagrams[key] = []
anagrams[key].append(str)
return list(anagrams.values())
|
class Car:
# Class-level
wheels = 4
def __init__(self, manufacturer: str, model: str, color: str, mileage: int):
# Instance-level
self.manufacturer = manufacturer
self.model = model
self.color = color
self.mileage = mileage
# Method
def add_mileage(self, mil... |
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm(a, b, g):
return a * b // g
A, B = (int(term) for term in input().split())
g = gcd(A, B)
print(g)
print(lcm(A, B, g))
|
def solution(a, b):
answer = 0
for x,y in zip(a,b):
answer+=x*y
return answer
|
AVAILABLE_OPTIONS = [('doc_m2m_prob_threshold', 'Probability threshold for showing document to mass2motif links'),
('doc_m2m_overlap_threshold', 'Threshold on overlap score for showing document to mass2motif links'),
('log_peakset_intensities', 'Whether or not to log the peakset intensities (... |
phi, d, t, coll = input().split()
phi = float(phi)
phi_1 = phi - 0.01
phi_2 = phi + 0.01
print(str(phi) + " " + "0.00001" + " " + "0.1 " + str(t) + " 10 20")
|
n = int(input())
len_n = len(str(n)) # n의 자릿수 파악( ex 123 : 3자릿수)
sum = 0
for i in range(len_n-1):
sum += 9 * (10 ** i) * (i+1) # ex)3자릿수라면(123) 두자릿수까지의 경우의수 계산
nums = n - (10 ** (len_n-1)) + 1 # ex) 3자리수라면 n - 100 +1 을 통해 100~n 사이의 개수 구하기
sum += nums * len_n # ex) 3자릿수 개수 * 3 -> 세자릿수 숫자들의 길이
print(... |
class usuario(object):
def __init__(self, nombre, apellido, edad, genero):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
self.genero = genero
def descripcion_usuario(self):
print("Nombre: " + self.nombre.title() + "\nApellido: " + self.apellido.title() +... |
# Ley d'Hondt
def hondt(votes, n):
""" Ley d'Hondt; coefficient: c_i = V_i / (s_i + 1)
V_i = total number of votes obtained by party i
s_i = number of seats assigned to party i (initially 0)
"""
s = [0] * len(votes)
for i in range(n):
c = [v[j] / (s[j] + 1) for j in range(len(s... |
class Class1(object):
def __init__(self):
pass
def test1(self):
return 5
class Class2(object):
def test1(self):
return 6
class Class3(object):
def test1(self, x):
return self.test2(x)-1
def test2(self, x):
return 2*x
a = Class1()
print(a.test1())
a = ... |
n = str(input('Digite seu nome completo:')).strip()
nome = n.split()
print ('É um prezer te conhecer!')
print ('seu primeiro nome é {}'.format(nome[0]))
print ('Seu último nome é {}'.format(nome[len(nome)-1])) |
# -*- coding: utf-8 -*-
"""
sphinxpapyrus
~~~~~~~~~~~~~
Sphinx extensions.
:copyright: Copyright 2018 by nakandev.
:license: MIT, see LICENSE for details.
"""
__import__('pkg_resources').declare_namespace(__name__)
|
class Tee:
def __init__(self, f, f_tee):
self.f = f
self.f_tee = f_tee
def read(self, nbytes):
buf = self.f.read(nbytes)
self.f_tee.write(buf)
return buf
def write(self, buf):
self.f_tee.write(buf)
self.f.write(buf)
def flush(self):
self... |
'''
This is all the calculation for the main window
'''
|
__title__ = 'lottus'
__description__ = 'An ussd library that will save you time'
__version__ = '0.0.4'
__author__ = 'Benjamim Chambule'
__author_email__ = 'benchambule@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Benjamim Chambule'
|
extra_annotations = \
{
'ai': [ 'artificial intelligence', 'machine learning', 'statistical learning', 'statistical model', 'supervised model',
'unsupervised model', 'computer vision', 'image analysis', 'object recognistion', 'object detection',
'image segmentation', 'deep learni... |
num = int(input())
numdict = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine'
}
print(numdict.get(num, 'number too big'))
|
# -*- coding: utf-8 -*-
class FormFactory(type):
"""This is the factory required to gather every Form components"""
def __init__(cls, name, bases, dct):
cls.datas={}
for k,v in dct.items():
if k[0]!="_":
cls.datas[k]=v
return type.__init__(cls, name, ... |
class Rational:
def __init__(self, p, q):
self.numerator = p
self.denominator = q
def __mul__(self, other):
return Rational(
self.numerator * other.numerator,
self.denominator * other.denominator
)
def __str__(self):
return f"{self.numera... |
# -*- coding: utf-8 -*-
db.define_table('Device',
Field('device_id', 'string'),
Field('device_name', 'string'),
Field('model', 'string'),
Field('location', 'string')
)
db.Device.device_id.requires = [IS_NOT_EMPTY(),IS_NOT_IN_DB(db, 'Device... |
#
i = 0
lista = [i]*6
while i < len(lista):
lista[i] = int(input('Digite a nota {}: '.format(i+1)))
i += 1
print('Notas digitadas')
i = 0
while i < len(lista):
print(lista[i])
i += 1
i = 0
s = 0
while i < len(lista):
s += lista[i]
i += 1
media = s/(i)
print('Média: {:... |
lista = [1753,
1858,
1860,
1978,
1758,
1847,
2010,
1679,
1222,
1723,
1592,
1992,
1865,
1635,
1692,
1653,
1485,
848,
1301,
1818,
1872,
1883,
1464,
2002,
1736,
1821,
1851,
1299,
1627,
1698,
1713,
1676,
1673,
1448,
1939,
1506,
1896,
1710,
1677,
1894,
1645,
1454,
1972,
1687,
265,
1923,
1666,
1761,
1386,
2006,
1463,
1759,
1... |
class helloworld:
def hello(self):
print("This is my first task !")
def run():
helloworld().hello()
|
# dp
class Solution:
def lengthOfLIS(self, nums: 'List[int]') -> 'int':
if len(nums) < 2: return len(nums)
dp = [1] * (len(nums) + 1)
for i in range(1, len(nums)):
for j in range(0, i):
if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
|
class Configuration:
"""
Configuration file for Twitter Sentiment
"""
def __init__(self):
self.color = "#00A8E0"
self.total_gauge_color = "#FF0102"
self.image_path = "static/icon.jpeg"
self.default_model = "twitter_sentiment_model"
self.title = "Twitter Sentime... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 17:48:06 2020
@author: Fernando
"""
# A = [14,13,12,11,10,9,8,7,6,5,4,3,2,1]
A = [3,2,1]
B = []
C = []
count = 0
def towers_of_hanoi(A,B,C,n):
global count
if n == 1:
disk = A.pop()
C.append(disk)
count +=1
else:
... |
def test_udp_header_with_counter(api, b2b_raw_config, utils):
"""
Configure a raw udp flow with,
- Non-default Counter Pattern values of src and
dst Port address, length, checksum
- 100 frames of 74B size each
- 10% line rate
Validate,
- tx/rx frame count is as expected
- all capt... |
'''
Dict with attr access to keys.
Usage:
pip install adict
from adict import adict
d = adict(a=1)
assert d.a == d['a'] == 1
See all features, including ajson() in adict.py:test().
adict version 0.1.7
Copyright (C) 2013-2015 by Denis Ryzhkov <denisr@denisr.com>
MIT License, see http://opensource.or... |
soma = 0
sMMenos20 = 0
idadevelho = 0
for i in range(1, 5):
nome = input('Escreva o nome da {}° pessoa: '.format(i))
idade = int(input('Escreva a sua idade: '))
gen = input('Escreva seu gênero: [F/M/NB] ').upper()
print('='*30)
soma = soma + idade
if gen == 'F' and idade < 20:
sMMenos20 ... |
while True:
n = int(input())
if n == 0: break
x, y = [int(g) for g in str(input()).split()]
for j in range(n):
a, b = [int(g) for g in str(input()).split()]
if a == x or b == y: print('divisa')
else:
if x < a:
if y < b: print('NE')
else... |
str(print('\033[0;34mBem-vindo ao site de empréstimo bancário!\033[m'))
valor = float(input('Qual será o valor da casa desejada?R$'))
sal = float(input('Qual é a sua remenuração mensal?R$'))
ano = int(input('Em quantos anos você pretende pagar o imóvel?'))
a = ano * 12 #1 ano = 12 meses
pres = valor/a #prestação é o va... |
"""
TW3: Sliced to Order
Mohammed Elhaj
Sohrab Rajabi
Andrew Nalundasan
Teamwork exercise 3 code
"""
# user inputs
user_text = input('Enter some text, please: ')
start_position = int(input('Slice starting position (zero for beginning): '))
end_position = int(input('Slice ending position (can be negative t... |
'''
По данному натуральному n вычислите сумму 1**3+2**3+3**3+...+n**3.
'''
n = int(input())
sum1 = 0
for i in range(1, n + 1):
sum1 += i ** 3
print(sum1)
|
# Módulo criptomat
# Dominio público
def mcd(a, b):
# Devuelve el MCD de dos números a y b mediante
# el algoritmo de Euclides
while a != 0:
a, b = b % a, a
return b
def invMod(a, m):
# Devuelve el inverso modular de a mod m, que es el
# número x tal que a * x mod m = 1
... |
def normalizable_feature(mean, std):
"""Decorator for features to specify default normalization.
Args:
mean: The mean value for the feature.
std: The standard deviation for the feature.
"""
def _normalizable_feature(func):
func.normal_mean = mean
func.normal_std = std
... |
'''
- Leetcode problem: 98
- Difficulty: Medium
- Brief problem description:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nod... |
"""
Write a program to accept a character from
the user and display whether it is a special character,
digit or an alphabet. The program should continue
as long as the juser wishes to.
"""
x = "Y"
while x == "y":
check = input("Enter a character: ")
if check >= 'a' and check <= 'z' or check >= 'A' and che... |
class TapeEnvWrapper:
def __init__(self, env):
self.__env = env
self.__factors = self.__get_factors()
def reset(self):
return self.__env.reset()
def step(self, action):
action = self.__undiscretise(action)
next_state, reward, done, info = self.__env.step(action)
... |
class Solution:
def solve(self, n):
if n == 0:
return '0'
remainders = []
while n:
n, r = divmod(n, 3)
remainders.append(str(r))
return ''.join(reversed(remainders))
|
#
# PySNMP MIB module CISCO-ITP-GSP2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-GSP2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:03:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
{
'targets': [
{
'target_name': 'discount',
'dependencies': [ 'libmarkdown' ],
'sources': [
'src/discount.cc'
],
'include_dirs': [
'deps/discount'
],
'libraries': [
'deps/disco... |
class BTNode:
def __init__(self, data = -1, left = None, right = None):
self.data = data
self.left = left
self.right = right
class BTree:
def __init__(self):
self.root = None
self.is_comp = True
self.num = 0
def is_empty(self):
return self.root is Non... |
load("//dev-infra/bazel/browsers:browser_archive_repo.bzl", "browser_archive")
"""
Defines repositories for Firefox that can be used inside Karma unit tests
and Protractor e2e tests with Bazel.
"""
def define_firefox_repositories():
# Instructions on updating the Firefox version can be found in the `README.md... |
class DockablePane(object,IDisposable):
"""
A user interface pane that participates in Revit's docking window system.
DockablePane(other: DockablePane)
DockablePane(id: DockablePaneId)
"""
def Dispose(self):
""" Dispose(self: DockablePane) """
pass
def GetTitle(self):
"""
GetTitle(sel... |
# Calculating Page rank.
class Graph():
def __init__(self):
self.linked_node_map = {}
self.PR_map = {}
def add_node(self, node_id):
if node_id not in self.linked_node_map:
self.linked_node_map[node_id] = []
self.PR_map[node_id] = 0
def add_link(self, node1, ... |
class NavigationValues:
navigation_distance = None
navigation_time = None
speed_limit = None
class Movement:
value = None
kph = None
mph = None
def calculate_speed(self):
self.kph = self.value * 3.6
self.mph = self.value * 2.25
def __init__(... |
def generate_board():
# Generate full, randomized sudoku board
pass
def generate_section():
# generate a randomized, 3x3 seciont of the board
pass
class SudokuBoard(object):
"""
"""
def __init__(self, difficulty):
super().__init__()
self._base_size = 3
self.... |
"""
Author: Omkar Pandit Bankar
Date: 10/10/2019
Email: omkarpbankar@gmail.com
""" |
#066_Varios_numeros_com_flag.py
j = soma = 0
while True:
num = int(input("Entre com um número: "))
if num == 999:
break
j += 1
soma += num
print(f"A soma dos {j} valores é {soma} e a média é {(soma/j):.2f}") |
def is_phone_valid(phone: str) -> bool:
if (
phone.isnumeric()
and phone.startswith(("6", "7", "8", "9"))
and len(phone) == 10
):
return True
return False
|
# !/usr/bin/python3
# 集合类型
# 包含的元素不可重复
# 可以进行集合运算
# 集合为无序
varTypeSet = {"0", "1", "2", "3"}
varTypeSet1 = {"2", "3", "4", "5"}
print(varTypeSet, varTypeSet1)
# 差集
print("差集", end=" ")
print(varTypeSet - varTypeSet1, end=" ")
print(varTypeSet1 - varTypeSet)
# 并集
# 错误示例,不能使用+
# print(varTypeSet + varTypeSet1)
print("... |
"""
An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d), the entire current tape is repeated... |
panjang = int(raw_input("masukan panjang: "))
lebar = int(raw_input("masukan lebar: "))
tinggi = int(raw_input("masukan tinggi: "))
volume = panjang * lebar * tinggi
print(volume)
|
class Node:
def __init__(self,data):
self.data = data
self.left = self.right = None
def findPreSuc(root, key):
# Base Case
if root is None:
return
# If key is present at root
if root.data == key:
# the maximum value in left subtree is predecessor
if ro... |
""""
This file stores details of the rsvp.
"""
RVSPS=[]
class Rsvp():
class_count = 1
def __init__(self):
self.meetup_id = None
self.topic = None
self.status = None
self.rsvp_id = Rsvp.class_count
self.user_id = None
Rsvp.class_count +=1
def __repr__(self):... |
STUDENT_NUMBER_STOP = 999
def parse_correct_answers(record):
return record.split(" ")
def parse_student_answers(record):
parsed = record.split(" ")
student = int(parsed[0])
if len(parsed) == 1:
return (student, None)
else:
return (student, parsed[1:])
def calculate_marks(correct,... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=29):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá, meu nome é {self.nome}'
@staticmethod
def metodo_estatico():
return 42
@clas... |
# Copyright 2021 The Fraud Detection Framework 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 requ... |
def czynniki_pierwsze(num: int) -> []:
factors = []
k = 2
while num > 1:
while num % k == 0:
factors.append(k)
num = num // k
k = k + 1
return factors
|
tmp=input('请输入你要转换的分钟数:')
mins=int(tmp)*60
print('%s分钟等于%s秒'%(tmp,mins))
|
versions = {}
def get_by_vid(vid):
return versions[vid]
def get_by_package(package, version_mode, vid):
if not in_cache(package, version_mode, vid):
return None
return versions[vid][package + version_mode]
def in_cache(package, version_mode, vid):
package_str = package + version_mode
return vid in ve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.