content stringlengths 7 1.05M |
|---|
class ParamSet:
"""A class for holding and validating the GET params
It validates the most of params with their restrictions. And also validate the required values for each mode
"""
AVAILABLE_MODES = (
'thumbnail', 'resize', 'flip', 'rotate',
)
AVAILABLE_FORMATS = (
'jpg', 'jpe... |
#
# PySNMP MIB module RIVERSTONE-SYSTEM-RESOURCES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-SYSTEM-RESOURCES-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:49:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
'''
Em Matemática, o número harmônico designado por H(n) define-se como sendo a soma da série Harmónica:
H(n) = 1 + 1/2 + 1/3 + 1/4 + ... +1/n
Faça um programa que leia um valor n inteiro e positivo e apresente o valor de H(n).
'''
n1 = int(input('Digite um número inteiro e positivo: '))
n2 = 1
somatorio =... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 16:55:30 2020
@author: Mario Palazuelos - Aliado Analítico, Morelos, México
"""
class TextParser:
def __init__(self, DATAFRAME, INDEX, COLUMN, TAG):
#Creating the Objects that will build the Class Skeleton.
self.DATAFRAME = DATAFRAME
... |
# Write a method that takes an array of consecutive (increasing) letters
# as input and that returns the missing letter in the array.
def find_missing_letter(chars):
"""
chars: string of characters
return: missing letter between chars or after
"""
letters = [char for char in chars][0]
chars = [char.lower()... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
比特位计数
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
示例 1:
输入: 2
输出: [0,1,1]
示例 2:
输入: 5
输出: [0,1,1,2,1,2]
进阶:
给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
要求算法的空间复杂度为O(n)。
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)... |
string = 'INDIA123DELHI'
#list = list(filter(lambda x: x!= '1' and x!='2' and x!='3',string))
list = list(filter(lambda x: x not in [str(n) for n in range(10)] ,string))
print((''.join(list)))
|
"""
行
"""
# 3个物理行3个逻辑行(建议)
a = 5
b = 2
c = a + b
# 1个物理行3个逻辑行(不建议)
a = 5;b = 2;c = a + b
# 3个物理行1个逻辑行(不建议)
# 折行符
data = 1 + 2 + 3 \
+ 4 + 5 + \
6 + 7 + 8 + 9
# 括号是天然的换行符
data = (1 + 2 + 3
+ 4 + 5 +
6 + 7 + 8 + 9)
print(
int(input("请输入年龄:")) > 25 and
int(input("请输入身高:")) < 17... |
def transform(df, index):
df['Latitude'].fillna('0', inplace=True)
df['Longitude'].fillna('0', inplace=True)
return df
|
class Node(object):
def __init__(self, value):
self.__value = value
self.attr = {}
def __str__(self):
return "Node value --> " + self.__value
def __hash__(self):
return hash(self.__value)
"""def __cmp__(self, other):
return cmp(self.attr['h'], other.attr['h'])"... |
# GENERATED VERSION FILE
# TIME: Thu Mar 7 20:30:16 2019
__version__ = '0.5.4+a6ee053'
short_version = '0.5.4'
|
timezone_info = {
"A": "UTC +1",
"ACDT": "UTC +10:30",
"ACST": "UTC +9:30",
"ACT": "UTC -5",
"ACWST": "UTC +8:45",
"ADT": "UTC +4",
"AEDT": "UTC +11",
"AEST": "UTC +10",
"AET": "UTC +10:00 / +11:00",
"AFT": "UTC +4:30",
"AKDT": "UTC -8",
"AKST": "UTC -9",
"ALMT": "UTC... |
# open file
func=open("func.txt","r")
# split it with \n
func_list=func.read().split("\n")
new_list=[]
# remove len 0 to 31 and store it in new list
for a in range(len(func_list)):
b=func_list[a][36:]
if len(b)>0:
new_list.append(b)
# short it with sorting algorithm
new_list=sorted(new_list)
# sorting t... |
'''
ler o primeiro termo e a razão da pa, e mostrar os 10 primeiros termos
'''
def main():
print('|********PROGRESSÃO ARITMÉTICA********|')
termo = int(input('-> Primeiro termo da PA: '))
razao = int(input('-> Razão da PA: '))
total = 0
cont = 10
while cont > 0:
print(f'{termo}', end='... |
"""
0356. Line Reflection
Medium
Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points symmetrically, in other words, answer whether or not if there exists a line that after reflecting all points over the given line the set of the original points is the same that t... |
#
# PySNMP MIB module CPM-NORTEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPM-NORTEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
#! /usr/bin/python3
input = open("input/01.txt").read()
floor = input.count("(") - input.count(")")
print(floor)
floor = 0
for i, a in enumerate(input):
floor = floor + (1 if a == '(' else - 1)
if floor == -1:
print(i + 1)
break
|
def generateClassId(classIds, firstName, lastName, subjectId):
initials = (firstName[0] + lastName[0: 2]).upper()
classId = f"{subjectId}-{initials}-A"
suffix = ord("B")
while classId in classIds:
classId = classId[0: -1] + chr(suffix)
suffix += 1
return classId
|
# These dictionaries are applied to the generated enums dictionary at build time
# Any changes to the API should be made here. attributes.py is code generated
# We are not code genning enums that have been marked as obsolete prior to the initial
# Python API bindings release
# We also do not codegen enums associated w... |
class Bird:
def __init__(self, name, color):
self.name = name
self.color = color
def fly(self):
print("飞行")
|
def product(factor1, factor2):
resultaat = factor1 * factor2
return resultaat
print("Unittest van 'product'")
assert product(9, 3) == 27, "Berekening van 'product' bevat een fout"
assert product(0, 0) == 0, "Fout bij berekenen 0 waarde"
assert product(1000, 1000) == 100000, "Fout bij berekenen grote waarde"
|
def pallindrome(z):
mid = (len(z)-1)//2
start = 0
last = len(z) - 1
flag = 0
while(start < mid):
if(z[start]== z[last]):
start += 1
last -= 1
else:
flag = 1
break;
if flag == 0:
print("The... |
class Student1:
def __init__(self,a=10,b=20):
self.add=a+b
self.sub=a-b
def result(self):
print("Sum is: ",self.add)
print("Sub is: ",self.sub)
|
FACTOR_RULES = "rules_factor"
TOPIC_RULES = "rules_topic"
TOPIC_RULE = "topic_rule"
FACTOR_RULE = "factor_rule"
MONITOR_RULES = "monitor_rules"
|
var = 0
def foo():
var = 2
print(var)
def fua():
var = 1
def fup():
global var
var = 42
print(foo())
print()
fua()
print(var)
fup()
print(var)
|
#Q9: Cual es la complejidad de
def cuadrado(n):
# Eleva al cuadrado los n primero números mientras el resultado sea menor que n
p = 0
for i in range(n):
p = i * i
if p >= n:
break
print(p)
cuadrado(10)
# i = 1 | p = 1 * 1
# i = 2 | p = 2 * 2
# i = 3 | p = 3 *... |
class PaginationKeys(object):
PAGE = 'page'
COUNT = 'count'
TOTAL = 'total'
SHOW = 'show'
DATA = 'data'
ITEMS_PER_PAGE = 25
|
# 2번째 workshop
num1 = int(input('첫번째 숫자를 입력하세요'));
num2 = int(input('두번째 숫자를 입력하세요'));
op = input('연산자를 입력하세요');
result1 = (num1+num2);
result2 = (num1-num2);
result3 = (num1*num2);
result4 = (num1/num2);
if op == '+':
print(result1);
elif op == '-':
print(result2);
elif op == '*':
print(re... |
"""
@author nghiatc
@since 06/01/2021
"""
|
s = float(0)
for i in range(1, 101):
s = float(s + float(1) / float(i))
print(f"{s:.2f}")
|
# Calculo factorial
def factorial(n):
prod = 1
i = 1
while i <= n:
prod *= i
i += 1
return prod
# Función para calcular la aproximación
def aproximacion(N, x):
n = 0
exp = 0
while n <= N:
exp += (x ** n) / factorial(n)
n += 1
return exp
# Entrada de dato... |
class MyList(list):
pass
def main():
my_list = MyList()
my_list.append('a')
my_list.append('b')
print(my_list[0])
print(my_list[1])
if __name__ == "__main__":
main() |
def for_D():
"""printing capital 'D' using for loop"""
for row in range(4):
for col in range(4):
if col==0 or row==0 and col!=3 or row==3 and col!=3 or col==3 and row in(1,2):
print("*",end=" ")
else:
print(" ",end=" ")
print()
... |
def heapify(tree, n, i):
"""
递归的方式实现。
:param tree: 完全二叉树/列表
:param n: 完全二叉树的结点数
:param i: 当前结点,
:return: None
"""
# 设一个最大值
largest = i
left = 2 * i + 1 # 左子结点:left = 2*i + 1
right = 2 * i + 2 # 右子结点:right = 2*i + 2
# 如果左子结点存在且比父结点大,修改最大值
if left < n and tree[larges... |
class AbstractRegulator:
"""Models the genetic regulation of cells. This class exists only
to document the required interface. (There is no need to inherit
from it.)
"""
def __init__(self, simulator):
"""Reference to Simulator required.
simulator -- The Simulator object containi... |
#!python2.7
# -*- coding: utf-8 -*-
"""
Created by kun on 2016/7/29.
"""
__author__ = 'kun'
class RecommenderEvaluator(object):
"""
Basic Interface which is responsible to evaluate the quality of Recommender
recommendations. The range of values that may be returned depends on the
implemen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Zheng <me@BoardCAM.org>
# Desc: 根据身高、体重、滑行方式生成滑雪板参考参数
# TODO 增加该程序估算完成后 直接生成配置文件, 通过配置文件直接生成对应的导出文件
# TODO 该计算方法较为粗糙简陋,需要进一步与骑手和厂商进行改进
def find(weight, height):
"""
:param weight: 体重(单位: kg)
:param height: 身高(单位: cm)
:return:
"""
print... |
class Solution:
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
if sx == tx and sy == ty:
return True
elif tx == ty or sx > tx or sy > ty:
return Fal... |
n = int(input())
for i in range(n + 1, 2 * n):
j = 2
while j * j <= i:
if i % j == 0:
break
j += 1
else:
print('YES')
print(i)
exit()
print('NO')
|
place = 'caf\u00e9'
# café
print( place )
# <class 'str'>
print( type(place) )
place_bytes = place.encode('utf-8')
# b'caf\xc3\xa9'
print( place_bytes )
# <class 'bytes'>
print( type(place_bytes) )
place2 = place_bytes.decode('utf-8')
# café
print( place2 ) |
def is_prime(a):
for j in range(2, a):
if a % j == 0:
return False
return True
answer = []
for i in range(2, 101):
if is_prime(i):
answer.append(str(i))
print(" ".join(answer))
# is_first = True
# for i in range(2, 101):
# if is_prime(i):
# if is_first:
# ... |
"""
Class for computing heat duty
This class performs simple thermodynamic calculations
to allow for heat duty and temperature change calculations.
Perfect heaters:
* You can specify a heat duty, and see what the final temperature is
* You can specify a final temperatue, and see what the heat duty required is
Heat l... |
"""A module defining the third party dependency gn"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def gn_repositories():
maybe(
new_git_repository,
name = "gn",
build_file = Label("//gn:BUILD.gn.ba... |
class Parser:
def __init__(self, file_name):
self.file_name = file_name
self.tokens = self.load_tokens()
def load_tokens(self):
with open(self.file_name) as f:
lines = map(lambda line: self.remove_comments(line).split(), f.readlines())
... |
def denominations(array):
den_list = []
for i in range(len(array)):
# since there is no coin with value 0
if i == 0:
continue
if array[i] > 0:
if not den_list:
den_list.append(i)
continue
if len(den_list) > 0:
... |
print("Interview by computer")
name = input("your name : ")
print(f"hello {name}")
age = input("your age : ")
favorite_color = input("your fav color : ")
second_person_name_etc = input()
# above is no an efficient way
# Below is an efficient way (using Tuples)
questions = (
"Your name: ",
"Your age: ",
... |
class x:
counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
def f1(self, x, y):
return min(x, x + y)
|
class Solution:
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
pushed.reverse()
popped.reverse()
ps = []
pp = []
i, j = 0, 0
while pushed or popped:
... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
bar('0')
main()
print('runing is ok!')
|
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
A = list(A)
diff = []
for i in range(len(A)):
if A[i] != B[i]:
diff.a... |
##
foto_2 = ruleGMLString("""rule [
ruleID "foto O2 " # H-O-H + Hf -> H-O. + H.
left [
node [ id 2 label "O" ]
node [ id 3 label "H" ]
edge [source 2 target 3 label "-"]
node [ id 4 label "Hf" ]
]
context [
node [ id 1 label "H" ]
edge [source 1 target 2 label "-"]
]
right [
... |
lista = [12, 13, 14, 15, 16, 17, 21, 22, 34, 54, 67]
print('''
A lista é composta dos seguintes Números:
= 12, 13, 14, 15, 16, 17, 21, 22, 34, 54, 67
''')
numero = int(input('Informe o número que saber a posição: '))
primeiro = 0
ultimo = len(lista)-1
while primeiro <= ultimo:
#faço a divisão da lista ... |
resnext_101_32_path = './pretrained/resnext_101_32x4d.pth'
pretrained_res_best = './pretrained/res_best.pth'
pretrained_vgg_best = './pretrained/vgg_best.pth'
DUTDefocus = './datasets/DUTDefocus'
CUHKDefocus = './datasets/CUHKDefocus' |
class Solution:
def possiblyEquals(self, s1: str, s2: str) -> bool:
def getNums(s: str) -> Set[int]:
nums = {int(s)}
for i in range(1, len(s)):
nums |= {x + y for x in getNums(s[:i]) for y in getNums(s[i:])}
return nums
def getNextLetterIndex(s: str, i: int) -> int:
j = i
... |
# Create veggies list
veggies = ['tomato', 'spinach', 'pepper', 'pea']
print(veggies)
# Remove first occurence of 'tomato'
veggies.remove('tomato')
print(veggies)
# Append 'corn'
veggies.append('corn')
print(veggies)
# Create meats list
meats = ['chicken', 'beef', 'pork', 'fish']
print(meats)
# Concatenate meats an... |
def test_something():
# (i'm going to delete this later, i just wanna make sure gh actions/etc.
# is set up ok)
assert 2 + 2 == 4
|
# Write a function that receives 3 characters. Concatenate all the characters into one string and print it on the console.
chr_1 = str(input())
chr_2 = str(input())
chr_3 = str(input())
print(chr_1+chr_2+chr_3) |
# This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
DEBUG = True
# Make these unique, and don't share it with anybody.
SECRET_KEY = "t6e%#%(w!lg1@1bk1$lhh%q_d4h&z*s3utakds-bzu-3b(bebe"
NEVERCACHE_KEY = "dit-cgsc$(w%xx)z*=l1-1vtz%a6v1hwhv9jtlsm0_kcg(md0z"
DAT... |
lista = []
consoantes = 0
for i in range(10):
lista.append(input("Digite uma letra: ").lower())
char = lista[i]
if char not in ('a','e','i','o','u'):
consoantes += 1
print(consoantes)
|
"""
Crie um programa que leia vários números inteiros pelo teclado.
No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos.
O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores.
"""
lst = []
n = sm = cont = s = 0
while s != "N":
n = in... |
# Copyright 2015 Ufora Inc.
#
# 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 law or agreed to i... |
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard
# such that no two queens attack each other.
# Given an integer n, return the number of distinct solutions to the n-queens puzzle.
# Example:
# Input: 4
# Output: 2
# Explanation: There are two distinct solutions to the 4-queens puzzle as s... |
x = "Hello world Python"
print(x)
# ------------------------------
print("\nTypes of data:")
print(type(42))
print(type(0b1010))
print(type(99111999111999111999111999))
print(type(3.14))
print(type('a'))
print(type( (1,2,3) ))
print(type( {} ))
print(type( {1,2,3} ))
print(type(["b", 42, 3.14]))
class ClassName:
pass... |
titulo = 'BANC Actuli'
print('='*40)
print(titulo.center(40))
print('='*40)
saque = int(input('Qual o valor a sacar? R$'))
n = nota = nota1 = nota20 = nota50 = nota10 = 0
while n < 2:
if saque >= 50:
nota= saque // 50
nota50 += 1
saque -= 50
elif saque >= 20:
nota = saque // 20
... |
# -*- coding: utf-8 -*-
"""
Raw time-series data from BES detectors.
BES detectors generate differential signals such that "zero signal" or "no light" corresponds to about -9.5 V. DC signal levels should be referenced to the "zero signal" output. "No light" shots (due to failed shutters) include 138545 and 138858,
... |
def transcribe(input: str) -> str:
out = ''
for i in input:
if i == '🅰️':
out += 'A'
elif i == '🅱️':
out += 'B'
elif i == '🅾️':
out += 'O'
elif i == 'Ⓜ️':
out += 'M'
elif i != '\uFE0F':
# hooray for multi-char... |
"""Support for all kinds of Smappee plugs."""
class SmappeeActuator:
"""Representation of a Smappee Comfort Plug, Switch and IO module."""
def __init__(self, id, name, serialnumber, state_values, connection_state, type):
# configuration details
self._id = id
self._name = name
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 23 03:17:10 2017
@author: coskun
Exercise: eval quadratic
5/5 points (graded)
ESTIMATED TIME TO COMPLETE: 5 minutes
Write a Python function, evalQuadratic(a, b, c, x),
that returns the value of the quadratic a⋅x2+b⋅x+c.
This function takes in fo... |
# 黒板に N 個の正の整数 A_1 ,...,A_N
# が書かれています.
# すぬけ君は,黒板に書かれている整数がすべて偶数であるとき,次の操作を行うことができます.
# 黒板に書かれている整数すべてを,2 で割ったものに置き換える.
# すぬけ君は最大で何回操作を行うことができるかを求めてください.
n = int(input())
a = list(map(int, input().split()))
cnt = 0
# 一番初めに全部偶数だった場合に+1するため
flg = True
while 1:
for i in range(n):
if (a[i]/2) % 2 != 0:
... |
ninjas = (
("Kakashi", ["Raiton", "Doton", "Suiton", "Katon"]),
("Tobirama", ["Suiton", "Doton"]),
("Minato", ["Raiton", "Katon", "Futon"]),
("Naruto", ["Futon"])
)
print(ninjas[0])
print(ninjas[2][1]) |
username = ""
password = ""
studentPassword = ""
|
_base_ = [
'../_base_/default_runtime.py'
]
fp16 = dict(loss_scale='dynamic')
# dataset settings
dataset_type = 'PornJson'
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='Res2Net',
depth=50,
scales=8,
base_width=26,
deep_stem=False,
... |
"""
Helpers for Python's logging.
"""
__all__ = ['BASE_LOGGING']
BASE_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s %(name)s %(levelname)s %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
... |
def who_eats_who(zoo_input):
animals = {'antelope': ['grass'], 'big-fish': ['little-fish'], 'bug': ['leaves'],
'bear': ['big-fish', 'bug', 'chicken', 'cow', 'leaves', 'sheep'],
'chicken': ['bug'], 'cow': ['grass'], 'fox': ['chicken', 'sheep'],
'giraffe': ['leaves'], 'lio... |
"""
[7/30/2012] Challenge #83 [intermediate] (Indexed file search)
https://www.reddit.com/r/dailyprogrammer/comments/xdx4o/7302012_challenge_83_intermediate_indexed_file/
For this challenge, write two programs:
* 'index file1 file2 file3 ...' which creates an index of the words used in the given files (you can assu... |
class Subaccount():
def __init__(self, base):
self.method = ""
self.base = base
def create(self, params={}):
self.method = "createSubAccount"
return self.base.request(self.method, params=params)
def delete(self, params={}):
self.method = "delSubAccount"
retu... |
for x in range(3):
print("Iteration" + str(x+1) + "of outer loop")
for y in range(2):
print(y+1)
print("Out of inner loop")
print("Out of outer loop")
|
s1=input()
s2=input()
s3=input()
a = "".join(sorted(s1+s2))
b = "".join(sorted(s3))
if a==b:
print("YES")
else:
print("NO") |
p = 2
f = 1
MAXITER = 60000
def setup():
size(600, 600)
this.surface.setTitle("Primzahl-Spirale")
background(51)
frameRate(1000)
def draw():
colorMode(HSB)
global p, f, i
translate(width/2, height/2)
noStroke()
fill(p%255, 255, 255)
# Satz von Wilson
if f%p%2:
... |
lista=[1,2,3,4,5,6,7,8,8]
l=len(lista)
n=False
for x in range(l):
for y in range(l):
if x!=y and lista[y]==lista[x]:
n=True
if n==True:
print ('Yes')
else:
print('No')
|
class ConditionsMixin(object):
conditions_url = 'conditions/conditions/'
def list_conditions(self, **kwargs):
return self.list(self.conditions_url, **kwargs)
def index_conditions(self, **kwargs):
kwargs.update({'list_route': 'index'})
return self.list(self.conditions_url, **kwargs... |
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.A = []
self.B = []
def push(self, x: int) -> None:
self.A.append(x)
if len(self.B) == 0 or self.B[-1] >= x:
self.B.append(x)
def pop(self) -> None:
... |
# -*- coding: utf-8 -*-
cyrillic_layout = """
йцукенгшщзхъ\
фывапролджэ
ячсмитьбю.
ЙЦУКЕНГШЩЗХЪ/
ФЫВАПРОЛДЖЭ
ЯЧСМИТЬБЮ,
Ё!"№;%:?*()_+
ё1234567890-=
"""
latin_layout = """
qwertyuiop[]\
a... |
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Use this to run several variants of the tests.
ALL_VARIANT_FLAGS = {
"default": [[]],
"future": [["--future"]],
"liftoff": [["--liftoff"]],
"mino... |
wh = 4
wl = 4
pc = wh-1
for x in range(0,wh+1):
pchar = ord('A')
for y in range(0,(wh*wl*2)):
if y%(wh*2)==pc or y%(wh*2)==wh+x:
print(chr(pchar),end='')
else:
print(' ',end='')
pchar+=1
if pchar>ord('Z'):
pchar = pchar-26
pc-=1
print(... |
"""Module with exceptions for virtual machine and bytecode compiler."""
class BadOperationSize(Exception):
"""Bad operation size genegerated/written to bytecode."""
|
markup = var('Markup (%)', 0, '', number)
if part.material:
set_operation_name('{} Markup {}%'.format(part.material, markup))
markup_cost = get_price_value('--material--') * (markup / 100)
PRICE = markup_cost
DAYS = 0
|
'''
You are given an m x n binary matrix grid. An island is
a group of 1's (representing land) connected 4-directionally
(horizontal or vertical.) You may assume all four edges
of the grid are surrounded by water.
The area of an island is the number of cells with a value
1 in the island.
... |
# Faça um programa que leia o sexo de uma pessoa, mas só aceite os
# valores 'M' ou 'F'. Caso esteja errado, peça a digitação novamente
# até ter um valor correto.
sexo = input('Informe seu sexo: [M/F] ').upper()
while sexo not in 'MF':
sexo = input('Informe seu sexo: [M/F] ').upper()
print(f'Sexo {sexo} registrad... |
def teardown_function(function):
pass
def test():
pass
|
'''
937. Reorder Data in Log Files
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
Each word after the identifier will consist only of lowercase letters, or;
Each word after the identifier will consist o... |
def parenMenu(choices,prompt="> "):
i = 0
for item in choices:
i += 1
print("{!s}) {!s}".format(i,item))
while True:
try:
choice = int(raw_input(prompt))
choice -= 1
if choice in [x for x in range(0,len(choices))]:
return choice
except:
continue
|
print('==============Calculadora de diretamente proporcional==============')
num1=int(input('escolha o primeiro numeros:'))
num2=int(input('escolha o segundo numeros:'))
num3=int(input('escolha o terceiro numeros:'))
total=int(input('qual o total:'))
b=num2/num1
c=num3/num1
result=1+b+c
result2=total/result
result... |
class Sample:
def __init__(self, num: int) -> None:
self.num = num
def __add__(self, other: "Sample") -> int:
return self.num + other.num
|
#!/usr/local/bin/python3.3
X = 88
print(X)
def func():
global X
X = 99
return
func()
print(X)
y, z = 1, 2
def func2():
global x
x = y + z
return x
print(func2())
y, z = 3, 4
print(func2())
|
# -*- coding: utf-8 -*-
''' Some utilities
.. moduleauthor:: David Marteau <david.marteau@mappy.com>
'''
def enum(*sequential, **named):
""" Create an enum type, as in the C language.
You can, as i C, list names without any value, or set a value by using a named argument.
But, of course,... |
""" Strings for application and fuzzy vault modules """
# Application strings
APP_WELCOME = "Welcome to the fuzzy vault fingerprint recognition application!"
APP_CHOOSE_FUNCTION = "Please choose the functionality you want to use from the following list:"
APP_FUNCTIONAILTIES = {'1': "Enroll new fingerprint",
... |
"""
https://leetcode.com/problems/employee-importance/
You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have import... |
def fully_connected(qubits: int, *args, **kwargs):
"""
This function returns the value False. Use like any other function that
creates and architecture when using analyse.
"""
return False
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
ans = 0
def dfs(node, gp=None, p=None):
if node is not N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.