content stringlengths 7 1.05M |
|---|
""" Optional problems for Lab 3 """
def is_prime(n):
"""Returns True if n is a prime number and False otherwise.
>>> is_prime(2)
True
>>> is_prime(16)
False
>>> is_prime(521)
True
"""
"*** YOUR CODE HERE ***"
def gcd(a, b):
"""Returns the greatest common divisor of a and b.
... |
"""
551. Student Attendance Record I
"""
class Solution:
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
A = i = 0
while i < len(s):
if s[i] == 'A': A+=1
if A>=2: return False
if s[i] == 'L':
... |
print('ex01:')
for c in range (1, 6):
print('Oi')
print('FIM')
print('-=' *10)
print('ex02')
for c in range(0, 7, 2):#PULA DUAS CASAS(2)
print(c)
print('FIM')
print('-=' *10)
print('ex03')
i = int(input('Início: '))
f = int(input('fim:'))
p = int(input('Passo: '))
for c in range (i, f+1, p):
print(c)
prin... |
class dtype(object):
def __init__(self):
super().__init__()
def is_floating_point(self) -> bool:
raise NotImplementedError('is_floating_point NotImplementedError')
def is_complex(self) -> bool:
raise NotImplementedError('is_complex NotImplementedError')
def is_signed(self) -... |
data = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'Google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
... |
def print_conversion(prev_char, cur_count, first_char):
space = '' if first_char else ' '
if prev_char == '0':
print('{}00 {}'.format(space, '0' * cur_count), end='')
else:
print('{}0 {}'.format(space, '0' * cur_count), end='')
def solution():
binary = []
for char in input():
... |
class Exchange:
def __init__(self, name):
self.name = name
self.market_bases = {'BTC', 'ETH', 'USDT'}
self.coins = self.get_all_coin_balance()
self.dontTouch = {'XRP', 'XEM', 'BTC', 'DOGE', 'SC', 'NEO', 'ZEC', 'BTG', 'MONA', 'WINGS', 'USDT', 'IOTA', 'EOS', 'QTUM', 'ADA', 'XLM', 'LSK'... |
CELLMAP_WIDTH = 200
CELLMAP_HEIGHT = 200
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 1200
CELL_WIDTH = SCREEN_WIDTH / CELLMAP_WIDTH
CELL_HEIGHT = SCREEN_HEIGHT / CELLMAP_HEIGHT
FILL_CELL = 0
SHOW_QUADTREE = True
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RANDOM_CHANCE = 0.0625 |
# This is the output of analyzeImage.py (each value indicates a RGB color)
myScreenshot = """
0 4 264 267 527 530 789 66328
66588 66591 66849 132388 132647 132650 132908 198447
198706 198708 264503 264505 330299 330557 330560 396354
3966... |
#!/usr/bin/env python3
inversions = 0
def count_inversions(input):
_ = merge_sort(input)
return inversions
def merge_sort(input):
if len(input) <= 1:
return input
mid = len(input) // 2
left = input[:mid]
right = input[mid:]
left = merge_sort(left)
right = merge_sort(right)... |
test = { 'name': 'q3a',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> diabetes_2d.shape\n'
'(442, 2)',
'hidden': False,
'locked': False},
... |
def binary_diagnostic(input):
numberLength = (len(input[0]))
gammaRate = ''
for col in range(numberLength):
ones = 0
for line in input:
if line[col] == '1':
ones += 1
else:
ones -= 1
gammaRate += '1' if ones >= 0 else '0'
... |
def test(func, verbose=True):
""" Tests a sort function by comparing it to
Python's builtin 'Timsort.' """
tests = [
[5, 7, 1, 9, 89, 15, 14, 2],
[False, True, False, True, False, True, True, True, False, False],
['z', 'x', 'u', 'i', 'o', 'z', 'r', 'a', 'b'],
['grape', '... |
def maxmin(A):
if len(A) == 1:
return A[0], A[0]
elif len(A) == 2:
return max(A[0], A[1]), min(A[0], A[1])
maxl, minl = maxmin(A[:int(len(A) / 2)])
maxr, minr = maxmin(A[int(len(A) / 2):])
return max(maxl, maxr), min(minl, minr)
class Solution:
# @param A : list of integers
... |
#!/usr/bin/env python
class DocumentProperty(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute typ... |
class StartTimeVariables:
@classmethod
def Checklist(cls):
cls.INTAG = None
return cls
|
class Encoder():
def encode_char(self, char, order):
return char
def _to_index(self, char):
return ord(char) - ord('A')
def _to_char(self, index):
return chr(index + ord('A'))
|
# EXERCICIO 048 - SOMA IMPARES MULTIPLOS DE 3
soma = 0
cont = 0
for cont in range(1,501,2):
if cont % 3 == 0:
cont += 1
soma += cont
print('A soma dos {} impares multiplos de 3 é {}'.format(cont,soma))
|
# ----------------------Cutter Model Error Messages---------------------------
NEG_OVERLAP_LAST_PROP_MESSAGE = \
"the overlap or last segment proportion should not be negative"
LARGER_SEG_SIZE_MESSAGE = \
"the segment size should be larger than the overlap size"
INVALID_CUTTING_TYPE_MESSAGE = "the cutting type ... |
base = 40
altura = 47
print('area del cuadrado =', base*altura)
|
def main():
K = input()
D = int(input())
L = len(K)
dp = [[[0, 0] for _ in range(D)] for _ in range(L+1)]
mod = 10 ** 9 + 7
dp[0][0][1] = 1
for i in range(L):
d = int(K[i])
for j in range(D):
for k in range(10):
dp[i+1][(j + k) % D][0] += dp[i][j][... |
# Twitter error codes
TWITTER_PAGE_DOES_NOT_EXISTS_ERROR = 34
TWITTER_USER_NOT_FOUND_ERROR = 50
TWITTER_TWEET_NOT_FOUND_ERROR = 144
TWITTER_DELETE_OTHER_USER_TWEET = 183
TWITTER_ACCOUNT_SUSPENDED_ERROR = 64
TWITTER_USER_IS_NOT_LIST_MEMBER_SUBSCRIBER = 109
TWITTER_AUTOMATED_REQUEST_ERROR = 226
TWITTER_OVER_CAPACITY_ERRO... |
dados = {}
dados['nome'] = str(input('Qual o nome do aluno: ')).strip().upper()
nota1 = float(input(f'Digite a primeira nota de {dados["nome"]}: '))
nota2 = float(input('Digite a segunda nota: '))
media = float((nota1 + nota2)/2)
dados['media'] = media
if media < 5.0:
dados['situacao'] = 'Reprovado'
elif media < 7... |
valores = list()
rodando = True
while rodando:
valor = int(input("Digite um valor: "))
if valor in valores:
print("Valor duplicado! Não irei adicionar...")
else:
valores.append(valor)
print("Valor adicionado com sucesso...")
while True:
continuar = input("De... |
with open('./inputs/04.txt') as f:
passphrases = f.readlines()
first = 0
second = 0
are_only_distinct = lambda x: len(x) == len(set(x))
for line in passphrases:
words = line.split()
first += are_only_distinct(words)
anagrams = [''.join(sorted(word)) for word in words]
second += are_only_distinct(... |
{
"CDPCQ04700": "계좌 거래내역", # order / 5 / 현물
"CEXAQ21100": "유렉스 주문체결내역조회", # order / 5 / 유렉스
"CEXAQ21200": "유렉스 주문가능 수량/금액 조회", # order / 5 / 유렉스
"CEXAQ31100": "유렉스 야간장잔고및 평가현황", # order / 4 / 유렉스
"CEXAQ31200": "유렉스 예탁금 및 통합잔고조회", # order / 4 / 유렉스
"CEXAQ44200": "EUREX 야간옵션 기간주문체결조회", # ord... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
res = []
num = root.val
val=0
s... |
def cart_prod(*sets):
result = [[]]
set_list = list(sets)
for s in set_list:
result = [x+[y] for x in result for y in s]
if (len(set_list) > 0):
return {tuple(prod) for prod in result}
else:
return set(tuple())
A = {1}
B = {1, 2}
C = {1, 2, 3}
X = ... |
class Solution:
def getRow(self, rowIndex):
def n_c_r(n, r):
numerator = 1
for i in xrange(1, r + 1):
numerator *= n - (i - 1)
numerator /= i
return numerator
return [n_c_r(rowIndex, i) for i in xrange(rowIndex + 1)]
|
def somme_consecutive(n: int) -> bool:
"""
Description:
Verifie si un nombre peut être exprimé en somme de deux ou plusieurs nombres entiers positifs consecutifs.
Paramètres:
n: {int} -- Le nombre à tester.
Retourne:
{bool} -- True si le nombre peut être exprimé en somm... |
class Solution:
def removeOuterParentheses(self, S: str) -> str:
stack = []
is_assemble = False
assembler = ""
result = ""
for p in S:
if p == "(":
if is_assemble:
assembler += p
if not stack:
... |
message = "Hello python world"
print(message)
message = "Hello python crash course world"
print(message) |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = {}
for n in nums:
if n in d:
d[n] += 1
else:
d[n] = 1
for k in d:
if d[k] == 1:
return k
|
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootVal())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阶乘,
n! 分成 n 和 (n - 1)!
"""
def test(fact):
assert fact(0) == 1
assert fact(1) == 1
assert fact(2) == 2
assert fact(4) == 2 * 3 * 4 == 24
def fact(n):
if n < 2:
return 1
t = 1
for i in range(2, n + 1):
t *= i
return t
te... |
# Set random seed
np.random.seed(0)
# Generate data
true_mean = 5
true_standard_dev = 1
n_samples = 1000
x = np.random.normal(true_mean, true_standard_dev, size = (n_samples,))
# We define the function to optimise, the negative log likelihood
def negLogLike(theta):
""" Function for computing the negative log-likel... |
__version__ = "0.8.10"
__format_version__ = 3
__format_version_mcool__ = 2
__format_version_scool__ = 1
|
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
row_max = list(map(max, grid))
col_max = list(map(max, zip(*grid)))
return sum(
min(row_max[i], col_max[j]) - val
for i, row in enumerate(grid)
for j, val in enumerate(row)... |
# hw08_02
for i in range(1, 9+1, 2):
print("{:^9}".format("^"*i))
'''
^
^^^
^^^^^
^^^^^^^
^^^^^^^^^
''' |
#
# @lc app=leetcode id=430 lang=python3
#
# [430] Flatten a Multilevel Doubly Linked List
#
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Node:
def __init__(sel... |
# http://www.codewars.com/kata/55c933c115a8c426ac000082/
def eval_object(v):
return {"+": v['a'] + v['b'],
"-": v['a'] - v['b'],
"/": v['a'] / v['b'],
"*": v['a'] * v['b'],
"%": v['a'] % v['b'],
"**": v['a'] ** v['b']}.get(v.get('operation', 1))
|
a = 5
b = 3
c = 72
d = 304
s1 = 'string'
pi = 3.141592
print('{0:-^48}'.format(' % 사용 '))
print('%d + %d = %d' % (a, b, a + b))
print('%d + %d = %d' % (c, d, c + d))
print('*' * 16)
print('%2d + %2d = %2d' % (a, b, a + b))
print('%2d + %2d = %2d' % (c, d, c + d))
print('*' * 16)
print('%03d + %03d = %03d... |
def oddNumbers(l, r):
result = []
for i in range(l, r + 1):
if i % 2 == 1:
result.append(i)
return result
|
description = 'Lambda power supplies'
group = 'optional'
tango_base = 'tango://172.28.77.81:10000/antares/'
devices = dict(
I_lambda1 = device('nicos.devices.entangle.PowerSupply',
description = 'Current 1',
tangodevice = tango_base + 'lambda1/current',
precision = 0.04,
timeout = ... |
def solution():
def integers():
num = 1
while True:
yield num
num += 1
def halves():
for i in integers():
yield i / 2
def take(n, seq):
take_list = []
for num in seq:
if len(take_list) == n:
return take... |
def longest_consecutive_subsequence(input_list):
# TODO: Write longest consecutive subsequence solution
input_list.sort()
# iterate over the list and store element in a suitable data structure
subseq_indexes = {}
index = 0
for el in input_list:
if index not in subseq_indexes:
... |
"""DNA na RNA"""
DNA_RNA = {
'G':'C',
'C':'G',
'T':'A',
'A':'U',
}
def transcribe_rna(dna):
rna = ''
for i in dna:
rna += DNA_RNA[i]
return rna
def validate_dna(dna):
return set(dna).issubset(set('GCTA'))
def main():
while True:
my_dna = input('Type DNA sequence:... |
def value_2_class(value):
if value < 0.33:
return [1, 0, 0]
elif 0.33 <= value < 0.66:
return [0, 1, 0]
else: # I know that he is not necessary the else but I like it
return [0, 0, 1]
|
lista = []
maior = 0
menor = 9 ** 9
maiorn = list()
menorn = list()
while True:
pessoa = [str(input('Nome: ')), float(input('Peso: '))]
lista.append(pessoa[:])
co = str(input('Continuar?[S/N]: '))
if co in 'Nn':
break
for l in lista:
if l[1] >= maior:
if l[1] > maior and l != lista[... |
# all jobs for letters created via the api must have this filename
LETTER_API_FILENAME = 'letter submitted via api'
LETTER_TEST_API_FILENAME = 'test letter submitted via api'
# S3 tags
class Retention:
KEY = 'retention'
ONE_WEEK = 'ONE_WEEK'
|
class Queue:
def __init__(self, number_of_queues, array_lenght):
self.number_of_queues = number_of_queues
self.array_length = array_lenght
self.array = [-1] * array_lenght
self.front = [-1] * number_of_queues
self.back = [-1] * number_of_queues
self.next_array = list(... |
hora = float(input('INFORME AS HORAS POR FAVOR: '))
if hora <=11:
print ('BOM DIA!!!')
if hora >= 12 and hora <= 17:
print ('BOA TARDE!!!')
if hora >= 18 and hora <= 23:
print ('BOA NOITE!!!')
print ('OBRIGADO, VOLTE SEMPRE!!!') |
# Your Fitbit access credentials, which must be requested from Fitbit.
# You must provide these in your project's settings.
FITAPP_CONSUMER_KEY = None
FITAPP_CONSUMER_SECRET = None
# The verification code for verifying subscriber endpoints
FITAPP_VERIFICATION_CODE = None
# Where to redirect to after Fitbit authentica... |
N, K = map(int, input().split())
ans = 0
for i in reversed(range(1, N+1)):
n = 1
# i番目のサイコロの目(=i)がKを超えるには何回コインで面を出す必要があるか
while i < K:
# 2倍にしている
n = n*2
i = i*2
# Kを超える確率(=超えるために必要なコインが連続で表になる確率をansに加算する)
ans += 1/n
# ansには各目が出る確率の合計が格納されているので値をN(サイコロの目の数)で割る
print(ans/N)
|
# -*- coding: utf-8 -*-
def main():
s = input()[::-1]
w_count = 0
ans = 0
for si in s:
if si == 'W':
w_count += 1
else:
ans += w_count
print(ans)
if __name__ == '__main__':
main()
|
src = ['board.c']
component = aos_board_component('board_mk3060', 'moc108', src)
aos_global_config.add_ld_files('memory.ld.S')
build_types=""
linux_only_targets="athostapp blink coapapp helloworld http2app id2_app itls_app linkkit_gateway linkkitapp meshapp modbus_demo mqttapp otaapp prov_app tls udataapp udevap... |
class Config(object):
pass
class Production(Config):
ELASTICSEARCH_HOST = 'elasticsearch'
JANUS_HOST = 'janus'
class Development(Config):
ELASTICSEARCH_HOST = '127.0.0.1'
JANUS_HOST = '127.0.0.1'
|
string = input()
vowels = {'a', 'e', 'i', 'o', 'u'}
v = sum(1 for char in string if char.lower() in vowels)
print(v, len(string)-v)
|
#Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/enums.py
__version__='3.3.0'
__doc__="""
Container for constants. Hardly used!
"""
TA_LEFT = 0
TA_CENTER = 1
TA_RIGHT = 2
TA_JUSTIFY = 4 |
_base_ = [
'../../_base_/models/convnext/convnext-tiny.py',
'./dataset.py',
'./schedule.py',
'./default_runtime.py',
]
custom_hooks = [dict(type='EMAHook', momentum=4e-5, priority='ABOVE_NORMAL')]
model = dict(
type='TextureMixClassifier',
style_weight=1.5,
content_weight=0.5,
mix_lr=0... |
# -*- coding: utf-8 -*-
#Comentário de uma linha
print("Hello World!")
print("Olá Mundo!")
print (2 * 2)
print (2 / 2)
print (3 ** 2)
print (10 % 3)
minha_variavel = "Olá Mundo!"
print(minha_variavel)
"""
Comentário
com
diversas
linhas
"""
|
N = int(input())
X = input().split()
for i in range(N):
X[i] = int(X[i])
minimum = min(X)
result = X.index(minimum) + 1
print(result)
|
def generate(event, context):
print(event)
response = {
"statusCode": 200,
"body": "this worked"
}
return response |
__title__ = 'Voice Collab'
__description__ = "Let's harness the power of voice to collaborate and interact with your code and the people you work with"
__email__ = "santhoshkdhana@gmail.com"
__author__ = 'Santhosh Kumar'
__github__ = 'https://github.com/Santhoshkumard11/Voice-Collab'
__license__ = 'MIT'
__copyright__ =... |
# IBM Preliminary Test
direction,floor,floor_requests,z = input(),int(input()),sorted(list(map(int,input().split())),reverse=True),0
if(floor_requests[-1]>=0 and floor_requests[0]<=15 and (direction=="UP" or direction=="DN")):
while(floor_requests[z]>floor): z+=1
print(*(floor_requests[:z][::-1]+floor_request... |
"""
Bar configuration constants
"""
#
# Colours
#
BG_COL = "#1b1b1b"
BG_SEC_COL = "#262626"
FG_COL = "#9e9e9e"
FG_SEC_COL = "#616161"
HL_COL = "#7cafc2"
#
# Placeholder space
#
BATTERY_PLACEHOLDER = " "
WORKSPACE_PLACEHOLDER = " "
CLOCK_PLACEHOLDER = " "
VOLUME_PLACEHOLDER = " "
GENERAL_PLACEHOLDER = " ... |
"""
This file will generate output that will be in error because the
name of this module (tests) clashes with the @tests annotation.
"""
def this_wont_work():
pass
|
"""
A python file must contain a prefix to be detected by pytest as a test file.
You can run the test using:
pytest tests/must_have_a_prefx.py
To allow pytest to find this file add the test_ prefix, e.g.:
test_basics.py
once done you can run it using:
pytest test.py
"""
def test_assertions():
"""
Most ... |
def compute_single_neuron_isis(spike_times, neuron_idx):
"""Compute a vector of ISIs for a single neuron given spike times.
Args:
spike_times (list of 1D arrays): Spike time dataset, with the first
dimension corresponding to different neurons.
neuron_idx (int): Index of the unit to compute ISIs for.
... |
sequence = input("Enter your sequence: ")
sequence_list = sequence[1:len(sequence)-1].split(", ")
subset_sum = False
for element in sequence_list:
for other in sequence_list:
if int(element) + int(other) == 0:
subset_sum = True
print(str(subset_sum))
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"get_py_files": "01_nbutils.ipynb",
"get_cells_one_nb": "01_nbutils.ipynb",
"write_code_cell": "01_nbutils.ipynb",
"py_to_nb": "01_nbutils.ipynb",
"get_module_text": "01_nb... |
#
# PySNMP MIB module MITEL-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-DHCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:56 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... |
def setup():
print(10*'=' + ' Notas SIGAA setup ' + 10*'=')
username = str(input('SIGAA username: '))
password = str(input('SIGAA password: '))
webdriver_path = str(input('Webdriver path (always use / and, if in the same dir, use ./): '))
csv_output = str(input('CSV output path (always use / and, i... |
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print("*** Caesar Cipher ***")
shift = int(input("Please enter a number from -26 to 26: "))
if input("Press 'd' to decipher, anything else to encipher: ").lower() == "d":
msg = input("Please enter your message: ")
decrypted = []
for char in msg:
index = ALP... |
"""This is where we store the created dicts of callbacks for
global and template execution"""
REGISTERED_GLOBAL_BEFORE_CALLBACKS = {}
REGISTERED_GLOBAL_AFTER_CALLBACKS = {}
REGISTERED_TEMPLATE_AFTER_CALLBACKS = {}
REGISTERED_TEMPLATE_BEFORE_CALLBACKS = {}
callback_kinds = {
"GLOBAL_BEFORE": REGISTERED_GLOBAL_BEF... |
"""
Allure Framework是一种灵活的轻量级多语言测试报告工具。 它提供清晰的图形报告,并允许开发过程中的每个人从日常测试过程中提取最大的信息。
先安装 allure
pip3 install allure-pytest -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
$ pip install allure-pytest
$ py.test --alluredir=%allure_result_folder% ./tests
$ allure serve %allure_result_folder%
pytest --allure... |
_CALCULATIONS_GRAPHVIZSHAPE = "ellipse"
def _raise(e):
raise e
|
def preprocess_data(_data):
nul, shape = _data.shape[0], _data.shape[1:]
print(nul)
print(shape)
_data = _data.reshape(nul, shape[0], shape[1], 1)
_data = _data.astype('float32')
_data /= 255
return _data |
class NotFound(Exception):
"""The requested data was not found during a call to .get()."""
pass
|
# @Title: 二叉搜索树的后序遍历序列 (二叉搜索树的后序遍历序列 LCOF)
# @Author: 18015528893
# @Date: 2021-01-20 21:49:53
# @Runtime: 40 ms
# @Memory: 14.8 MB
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def recur(i, j):
if i >= j:
return True
m = i
whi... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def rectree(orderlist):
if len(orderlist) == 0:
... |
class TypeLibFuncAttribute(Attribute,_Attribute):
"""
Contains the System.Runtime.InteropServices.FUNCFLAGS that were originally imported for this method from the COM type library.
TypeLibFuncAttribute(flags: TypeLibFuncFlags)
TypeLibFuncAttribute(flags: Int16)
"""
def __init__(self,*args):
""" ... |
class IcmpException(OSError):
pass
class BufferTooSmall(IcmpException):
pass
class DestinationNetUnreachable(IcmpException):
pass
class DestinationHostUnreachable(IcmpException):
pass
class DestinationProtocolUnreachable(IcmpException):
pass
class DestinationPortUnreachable(IcmpException):
... |
test = {
'name': 'has-cycle',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (has-cycle s)
#f
scm> (has-cycle cycle)
#t
scm> (has-cycle cycle-within)
#t
""",
'hidden': False,
'locked': ... |
for x in range(6, 0, -1):
if (x % 2 != 0):
ctrl = x + 1
else:
ctrl = x
for y in range(0, ctrl):
print("*", end="")
print() |
day_of_week = input()
work_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
vacation_days = ['Saturday', 'Sunday']
if day_of_week in (work_days):
print('Working day')
elif day_of_week in (vacation_days):
print('Weekend')
else:
print('Error') |
x = 10
y = 2
a = x*y
print(a)
b = 12 |
# pma.py --maxTransitions 100 --output synchronous_graph synchronous
# 4 states, 4 transitions, 1 accepting states, 0 unsafe states, 0 finished and 0 deadend states
# actions here are just labels, but must be symbols with __name__ attribute
def send_return(): pass
def send_call(): pass
def recv_call(): pass
def recv... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 11:46:46 2021
@author: Easin
"""
in1 = input()
#flag = True
for elem in range(len(in1)):
if in1[elem] == "H" or in1[elem] == "Q" or in1[elem] == "9":
flag = False
break
else:
flag = True
if flag == False:
print("YES"... |
fr = open('cora/features.features')
a = fr.readlines()
fr.close()
fw = open('cora/features.txt','w')
for i in range(len(a)):
s = a[i].strip().split(' ')
fw.write(s[0]+'\t')
for j in range(1,len(s)):
if (s[j]=='0.0'):
fw.write('0\t')
else:
fw.write('1\t')
fw.write('\n')
fw.close()
|
"""
[2017-03-17] Challenge #306 [Hard] Generate Strings to Match a Regular Expression
https://www.reddit.com/r/dailyprogrammer/comments/5zxebw/20170317_challenge_306_hard_generate_strings_to/
# Description
Most everyone who programs using general purpose languages is familiar with regular expressions, which enable yo... |
'''
While the very latest in 1518 alchemical technology might have solved their
problem eventually, you can do better.
You scan the chemical composition of the suit's material and discover that
it is formed by extremely long polymers.
The polymer is formed by smaller units which, when triggered,
react with each other ... |
""" A collection of command-line tools for building encoded update.xml
files.
"""
class InfoFile:
update_file = ""
version = None
checksum = None
# A multi-line HTML document describing the changes between
# this version and the previous version
description = ""
@classmethod
def from... |
'''
# 977. [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/)
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: ... |
"""
The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be writt... |
__all__ = ["decoder"]
def decoder(x: list) -> int:
x = int(str("0b" + "".join(reversed(list(map(str, x))))), 2)
return x |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repos():
http_archive(
name = "vim",
urls = [
"https://github.com/vim/vim/archive/v8.1.1846.tar.gz",
],
sha256 = "68de2854199a396aee19fe34c32c02db5784c76c0334d58b510266436c7529bb",
... |
class InvalidInput(Exception):
def __init__(self):
Exception.__init__(self, "Sorry, your input doesn't look good. "
"Or, Maybe you've tried too many times and "
"google thinks you aren't receiving the phone code?")
|
_formats = {
'cic': [100, "CIrculant Columns"],
'cir': [101, "CIrculant Rows"],
'chb': [102, "Circulant Horizontal Blocks"],
'cvb': [103, "Circulant Vertical Blocks"],
'hsb': [104, "Horizontally Stacked Blocks"],
'vsb': [104, "Vertically Stacked Blocks"]
}
|
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017-2018 SUSE LLC
#
# 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-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.