content stringlengths 7 1.05M |
|---|
def pad(n):
if(n>=10):
return "" + str(n)
return "0" + str(n)
class Time:
def __init__(self,hour,minute):
self.hour=hour
self.minute=minute
def __str__(self):
if self.hour<=11:
return "{0}:{1} AM".format(pad( self.hour),pad(sel... |
input_program = [line.strip() for line in open("input.txt")]
#Pass 1
macro_name_table,mdtable = [],[]
macro = 0
for linenumber,line in enumerate(input_program):
if line == "MACRO":
continue
elif input_program[linenumber-1] == "MACRO":
macro_name_table.append(line)
mdtable.append(line)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
############################
# File Name: download_file.py
# Author: One Zero
# Mail: zeroonegit@gmail.com
# Created Time: 2015-12-29 02:11:10
############################
# HTTP头部
print("Content-Disposition: attachment; filename=\"foo.txt\"\r\n\n")
# 打开文件
fo = open("foo... |
class Mappings:
"""Class with mapping, one for the condensed games (cg) and another for the
recap of the games (hl). The dictionaries' keys are the teams' names and
the values are the keywords for each of the type of videos.
"""
team_cg_map = {
"Los Angeles Angels": "laa",
"Houston ... |
K = int(input())
N = 1 << K
R = [int(input()) for _ in range(N)]
def winp(rp, rq):
return 1. / (1 + 10 ** ((rq - rp) / 400.))
dp = [1.0] * N
for i in range(K):
_dp = [0.0] * N
for l in range(0, N, 1 << (i + 1)):
for j in range(l, l + (1 << (i + 1))):
start = l + (1 << i) if j - l < (1... |
class PubSub(object):
def __init__(self):
self._subscriptions = {}
def publish(self, data=None, source=None):
heard = []
if source in self._subscriptions.keys():
for listener in self._subscriptions[source]:
listener(data, source)
heard.append(listener)
if None in self._subscri... |
#!/usr/bin/python3
with open('input.txt') as f:
input = f.read().splitlines()
lights = []
for i in range(1000):
lights.append([])
for j in range(1000):
lights[i].append(0)
for command in input:
offset = 0
if command.startswith('turn on'):
offset = 8
elif command.startswith('turn off'):
offse... |
# Rule class used by the grammar parser to represent a rule
class Rule:
def __init__(self, left, right):
self.label = left.label
self.op = right.op
self.priority = right.priority
self.condition = left.condition
if left.paramNames != None:
self.op.addParams... |
# source: http://www.usb.org/developers/docs/devclass_docs/CDC1.2_WMC1.1_012011.zip, 2017-01-08
class SUBCLASS:
DIRECT_LINE_CONTROL_MODEL = 0x01
ABSTRACT_CONTROL_MODEL = 0x02
TELEPHONE_CONTROL_MODEL = 0x03
MUTLI_CHANNEL_CONTROL_MODEL = 0x04
CAPI_CONTROL_MODEL = 0x05
ETHERNET_NETWORKING_CONTROL... |
def power(x, b, n):
a = x
y = 1
while b > 0:
if b % 2 != 0:
y = (y * a) %n
b = b >> 1
a = (a * a) % n
return y
if __name__ == '__main__':
x = power(7, 21, 100)
for m in range(30, 2000):
if power(100, 293, m) == 21:
print(m)
brea... |
def test_something(space):
assert space.w_None is space.w_None
class AppTestSomething:
def test_method_app(self):
assert 23 == 23
def test_code_in_docstring_failing(self):
"""
assert False # failing test
"""
def test_code_in_docstring_ignored(self):
"""
... |
"""
Created on Tue Mar 19 09:32:52 2019
@author: Amanda Judy Andrade
"""
def writefile(x):
i=0
for i in range(1,5,1):
text=input("Enter a string:")
x.write(text)
x.close()
def openfile():
x=open("sample.txt",'w')
return x
x=openfile()
writefile(x) |
option_list = BaseCommand.option_list + (
make_option('-d', '--db',
dest='db',
metavar='DB_ID',
help='Mandatory: DATABASES setting key for database'),
make_option('-p', '--project',
dest='project',
default='UNGA',
me... |
## @file moMapDefs.py
## @brief Definition of the map that is the VIM API.
"""
Definition of the map that is the VIM API.
The map consists of a list of definitions that describe how classes
refer to other classes through property paths as well as a managed
object class hierarchy.
Relevant managed object class hierar... |
aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = float(input(f'Média do {aluno["nome"].title()} '))
while aluno['media'] > 10:
aluno['media'] = float(input('Não é possível que a média de aluno seja maior que 10. Favor digitar novamente: '))
if aluno['media'] < 7:
aluno['situacao'] = 'Reprovado!'... |
print(42 == 42)
print(3 != 3)
print(3 >= 4)
print(0 < 6)
print(6 < 0) |
#MenuTitle: Change LayerColor to Grey
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
thisGlyph.layers[font.selectedFontMaster.id].color = 10
|
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
res, r = [], 0
for a in A:
r = (r * 2 + a) % 5
res.append(r == 0)
return res
|
# -*- Python -*-
load("//tensorflow:tensorflow.bzl", "tf_py_test")
# Create a benchmark test target of a TensorFlow C++ test (tf_cc_*_test)
def tf_cc_logged_benchmark(
name=None,
target=None,
benchmarks="..",
tags=[],
test_log_output_prefix="",
benchmark_type="cpp_microbenchmark"):
if not na... |
def product(values) :
n = 1
for val in values:
n *= val
return n |
[print(i) for i in range(int(input())+1)]
[print(n**2) for n in range(0, int(input()), 2)]
s = 0
while(True):
a = input()
if a == 'The End':
print(s)
break
s += int(a)
# or print(sum(map(int, iter(input, 'The End'))))
for word in input().split():
if word[0] != '*': print(word)
#or [p... |
#
# Loop Version --- Iterations in Python
#
# Array Initialization for Inner Values
iv = np.zeros((M + 1, M + 1), dtype=np.float)
z = 0
for j in range(0, M + 1, 1):
for i in range(z + 1):
iv[i, j] = max(S[i, j] - K, 0)
z += 1
#
# Vectorized Version --- Iterations on NumPy Level
#
# Array Initialization... |
# coding: utf-8
# In[1]:
class Match(object):
def __init__(self, price, volume, isLong, step):
self.price = price
self.volume = volume
self.isLong = isLong
self.step = step
|
# Copyright 2017 - 2018 Modoolar <info@modoolar.com>
# Copyright 2018 Brainbean Apps
# Copyright 2020 Manuel Calero
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
{
"name": "Web Actions Multi",
"summary": "Enables triggering ... |
def dict_filter(dic, keys: list) -> list:
"""
Get values from a dict given a list of keys
:param dic: dictionary to be filtered
:param keys: list of keys to be used as filter
:return:
"""
return [(dic[i]) for i in keys if i in list(dic.keys())]
|
#----
# Рационы домашних животных:
metadict_detail['Воловий рацион (животное/год)'] = {
# Волы питаются в стойле во время сельскохозяйственных работ:
# https://ru.wikisource.org/wiki/ЭСБЕ/Вол
'Воловий рацион стойловой (дней/год)':200,
'Воловий рацион пастбищный (дней/год)':160,
... |
# ActivitySim
# See full license in LICENSE.txt.
__version__ = '0.9.5.2'
__doc__ = 'Activity-Based Travel Modeling'
|
if condition:
pass
else:
assert something
another_statement()
|
""" Discrete Meyer (FIR Approximation) wavelet """
class Meyer:
"""
Properties
----------
near symmetric, orthogonal, biorthogonal
All values are from http://wavelets.pybytes.com/wavelet/dmey/
"""
__name__ = "Meyer Wavelet"
__motherWaveletLength__ = 62 # length of the mother wavele... |
def code(x):
return {
'61' : 'Brasilia',
'71' : 'Salvador',
'11' : 'Sao Paulo',
'21' : 'Rio de Janeiro',
'32' : 'Juiz de Fora',
'19' : 'Campinas',
'27' : 'Vitoria',
'31' : 'Belo Horizonte'
}.get(x, 'DDD nao cadastrado')
print(f"{code(input())}") |
class Anagram:
@staticmethod
def is_anagram(a, b):
if (a is b):
return False
f = lambda c: c not in [' ', '\n']
a_arr = list(filter(f, list(a)))
b_arr = list(filter(f, list(b)))
a_len = len(a_arr)
b_len = len(b_arr)
if (a_len != b_len):
... |
# Zip Function
list1 = [1,2,3]
list2 = [10,10,30]
#print(list(zip(list1, list2)))
print(list(zip('abc', list1, list2)))
|
def email_domain_loader():
return [
"0-mail.com",
"0815.ru",
"0815.su",
"0clickemail.com",
"0sg.net",
"0wnd.net",
"0wnd.org",
"10mail.org",
"10minutemail.cf",
"10minutemail.com",
"10minutemail.de",
"10minutemail.ga",
... |
# -*- coding: utf-8 -*-
BANCO_DO_BRASIL = {
'valid_combinations': [
{'bank_code': '001', 'branch': '0395', 'branch_digit': '6', 'account': '45939', 'account_digit': '9'},
{'bank_code': '001', 'branch': '2995', 'branch_digit': '5', 'account': '14728', 'account_digit': '1'},
{'bank_code': '00... |
"""
camply __version__ file
"""
__version__ = "0.2.3"
__camply__ = "camply"
|
# This is to find the sum of digits of a number until it is a single digit
def sum_of_digits(n):
n = int(input()) # here n is the number
if n % 9 != 0:
print(n % 9)
else:
print("9")
# This method reduces time complexity by a factor of n and also without using any loop
|
class Layover:
"""This class defines a layover period between two legs of a trip.
"""
def __init__(self, arr_leg, dept_leg, conn_time):
"""Initialises the Layover object.
Args:
arr_leg (Leg): the leg on which pax arrived at the
layover airport.
... |
s = input()
searched = ""
no_match = False
for i in range(len(s)):
if s[i] in searched:
continue
else:
counter = 0
no_match = True
for j in range(i+1, len(s)):
if s[j] == s[i]:
no_match = False
break
if no_match:
... |
try:
arr= []
print(" Enter the integer inputs and type 'stop' when you are done\n" )
while True:
arr.append(int(input()))
except:# if the input is not-integer, just continue to the next step
l = len(arr)
print("Enter the values of a,b and c \n")
a=int(input())
b=int(input())
c=i... |
#!/bin/false -- # do not execute!
#
# foxLanguagesBase.py - base class for foxLanguages classes.
#
class foxLanguagesBase(object):
#
# define the names that all foxLanguages* classes must define:
#
# comment -> either a single string for comment-line-start,
# or a tuple of ( comment-block-start, com... |
def list_sum(L):
s = 0
for l in L:
s += l
return s
def list_product(L):
s = 1
for l in L:
s *= l
return s
V = [1, 2, 3, 4, 5, 6]
print(list_sum(V))
print(list_product(V))
|
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
nums = sum(grid, [])
k %= len(nums)
nums = nums[-k:] + nums[:-k]
col = len(grid[0])
return [nums[i:i + col] for i in range(0, len(nums), col)]
|
# Time: O(n)
# Space: O(n)
class Solution(object):
def maxNonOverlapping(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
lookup = {0:-1}
result, accu, right = 0, 0, -1
for i, num in enumerate(nums):
accu +... |
class Trie(object):
def __init__(self):
self.nexts = collections.defaultdict(Trie)
self.valid = False
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root=Trie()
def addWord(self, word):
"""
... |
firstAioConfigDefault = {
'db': {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'fastormtest',
'is_use': True
},
'http': {
'host': '0.0.0.0',
'port': 8080,
'templates': 'C:\\Users\\admin\\Deskt... |
n, m, k = [int(x) for x in input().split()]
applicants = [int(x) for x in input().split()]
apartments = [int(x) for x in input().split()]
applicants.sort()
apartments.sort()
total = 0
i = 0
j = 0
while i < n and j < m:
# print(i,j)
if applicants[i]-k <= apartments[j] <= applicants[i]+k:
total += 1
... |
b = 10
def outer():
b = 1
def inner():
# b = 10
nonlocal b
b = b + 1 # 此时 b 变量所在的命名空间属于 local作用域
print('inner_b is %d' % b)
inner()
global b
b = 20
print('outer_b is %d' % b)
outer() |
# Basic colors defined here
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)
Green = (0, 255, 0)
snakeGreen = (0, 127, 0)
Blue = (0, 0, 255)
Yellow = (255, 255, 0)
Magenta = (255, 0, 255)
Cyan = (0, 255, 255)
|
"""
Shared settings
IMPORTANT NOTE:
These settings are described with docstrings for the purpose of automated
documentation. You may find reading some of the docstrings easier to understand
or read in the documentation itself.
http://earthgecko-skyline.readthedocs.io/en/latest/skyline.html#module-settings
"""
RED... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-04-04
算法思想:跳跃游戏II--贪心
"""
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
last = 0 # 上一跳所能到达的最远距离
curMax = 0 # 当前一跳可达最远距离
step = 0 # 当前跳数
fo... |
class Starrable:
"""
Represents an object that can be starred.
"""
__slots__ = ()
_graphql_fields = {
"stargazer_count": "stargazerCount",
"viewer_has_starred": "viewerHasStarred",
}
@property
def stargazer_count(self):
"""
The number of stars on the st... |
def _add_to_dict_if_present(dict, key, value):
if value:
dict[key] = value
objc_merge_keys = [
"sdk_dylib",
"sdk_framework",
"weak_sdk_framework",
"imported_library",
"force_load_library",
"source",
"link_inputs",
"linkopt",
"library",
]
def _merge_objc_providers_dict(p... |
class BaitSegment(object):
def __init__(self, chromosome, start, stop, strand, isoform_exons, bait_length):
self.label = None
self.chromosome = chromosome
self.start = start # 1-based
self.stop = stop # 1-based
self.strand = strand # Strand of the isoforms for this segme... |
def binary_classification_metrics(prediction, ground_truth):
precision = 0
recall = 0
accuracy = 0
f1 = 0
# TODO: implement metrics!
tp = np.sum(np.logical_and(prediction, ground_truth))
fp = np.sum(np.greater(prediction, ground_truth))
fn = np.sum(np.less(prediction, ground_truth)... |
"""f451 Communications module."""
__version__ = "0.1.1"
__app_name__ = "f451-comms"
|
class Config:
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@localhost:3306/focusplus'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'super-secret-key'
JWT_ERROR_MESSAGE_KEY = 'message'
JWT_BLACKLIST_ENABLED = True
JWT_BLACKLIST_TOKEN_CHECKS = ['access', 'refresh'] |
{
"targets": [
{
"target_name": "sharedMemory",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/sharedMemory.cpp" ],
"libraries": [],
},
{
"target_name": "messaging",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!":... |
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# this default context will only work in the build time
# during the flow/task run, will use context in flow/task as the initial context
DEFAULT_CONTEXT = {
'default_flow_config': {
'check_cancellation_interval': 5,
'test__': {
'test__': [1, 2, 3]
},
'log_stdout': True,
... |
"""
This file contains quick demonstrations of how to use xdoctest
CommandLine:
xdoctest -m xdoctest.demo
xdoctest -m xdoctest.demo --verbose 0
xdoctest -m xdoctest.demo --silent
xdoctest -m xdoctest.demo --quiet
"""
def myfunc():
"""
Demonstrates how to write a doctest.
Prefix with `>>>... |
# -*- coding: utf-8 -*-
# Scrapy settings for pkulaw project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topi... |
niz = [4,1,2,3,5,10,7,3,5,1]
print(sorted(niz))
for el in range(1,20):
print(el) |
"""Map file definitions for postfix."""
class DomainsMap(object):
"""Map to list all domains."""
filename = 'sql-domains.cf'
mysql = (
"SELECT name FROM admin_domain "
"WHERE name='%s' AND type='domain' AND enabled=1"
)
postgres = (
"SELECT name FROM admin_domain "
... |
#t3.py module
pix = 134
def pipi(a='aasasa'):
print(a)
|
# build decoder model
latent_inputs = kl.Input(shape=(latent_dim,), name='z_sampling')
x = kl.Dense(intermediate_dim, activation='relu')(latent_inputs)
outputs = kl.Dense(n_input, activation='sigmoid')(x)
# instantiate decoder model
decoder = km.Model(latent_inputs, outputs, name='decoder') |
class Solution:
def bagOfTokensScore(self, tokens, P):
tokens.sort()
l, r, score = 0, len(tokens) - 1, 0
while l <= r:
if P >= tokens[l]:
P -= tokens[l]
score += 1
l += 1
elif score and l != r:
P += token... |
# list, row, column and box initalizations
lst = [ [ [ False, '-', [], 0 ] for col in range(9)] for row in range(9)]
row = [[ False, 9, [c for c in range(1, 10)] ] for r in range(9)]
col = [[ False, 9, [c for c in range(1, 10)] ] for r in range(9)]
box = [[ False, 9, [c for c in range(1, 10)] ] for r in range(9)]
... |
""" Main module, launches foo daemon
"""
def main():
pass
if __name__ == 'main':
main()
|
#!/usr/bin/env python3
# This was adopted from sq2hex.py from https://github.com/davidar/subleq/blob/master/util/sq2hex.py by Josh Ellis.
# Copyright (c) 2009 David Roberts <d@vidr.cc>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation file... |
# Time: O(log(n))
# Space: O(log(n))
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
col_num = []
while n>0:
cur_char = chr(int((n-1)%26)+ord('A'))
col_num.append(cur_char)
n = (n-1)//26
... |
salario = float(input('Informe o seu salário: '))
aumento = salario + (salario * 0.15)
print('Um funcionario que ganhava RS{}, com 15% de aumento, passa a receber {:.2f}'.format(salario, aumento))
|
#DFS using Recursion
class Node():
def __init__(self,value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self,value):
self.value = value
def set_left_child(self,le... |
config = {
"beta1": 0.9,
"beta2": 0.999,
"epsilon": [
1.7193559220924876e-07,
0.00019809119366335256,
1.4745363724867889e-08,
3.0370342703184836e-05,
],
"lr": [
0.000592992422167547,
0.00038001447767611315,
7.373656030831236e-06,
1.0011... |
# Solution to Project Euler Problem 3
def sol():
n = 600851475143
i = 2
while i <= n:
if i < n and n % i == 0:
n //= i
i += 1
return str(n)
if __name__ == "__main__":
print(sol())
|
sql92_dialect = {
"dialect": "sql",
"insert_sql": "INSERT INTO {table} ({columns}) VALUES ({values})",
"select_sql": ("SELECT{distinct} {columns} FROM {table}"
"{where}{groupby}{having}{orderby}{limit}"),
"update_sql": "UPDATE {table} SET {set_columns}",
"delete_sql": "DELETE FROM... |
# -*- coding:utf-8 -*-
'''
/**
* This is the solution of No.3 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
* <p>
* The description of problem is as follow:
* ===================================================... |
def menor_nome(nomes):
menor = nomes[0]
menor.strip()
for nome in nomes:
comparado = nome.strip()
if len(comparado) < len(menor):
menor = comparado
menor.lower()
return menor.capitalize()
|
# a program to compute employee fee
hours = int(input('Enter hours:'))
rate = float(input('Enter rate:'))
# calculating hours above 40
eth = (hours - 40)
# for hours above forty
if hours > 40:
pay = ((eth * 1.5 * rate) + (40 * rate))
print(pay)
# for hours less than or equal to 40
else:
pay2 = (rate * hours... |
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
NUM_ROWS = 3
NUM_COLS = 5
# construct a matrix
my_matrix = {}
for row in range(NUM_ROWS):
row_dict = {}
for col in range(NUM_COLS):
row_dict[col] = row * col
my_matrix[row] = row_dict
print(my_matrix)
# print the matrix
for ... |
class FieldsEnum:
ACCOUNT: str = 'account'
ASC: str = 'asc'
BALANCE: str = 'balance'
GAS_PRICE: str = 'eth_gasPrice'
LATEST: str = 'latest'
PROXY: str = 'proxy'
TXLIST: str = 'txlist'
TXLIST_INTERNAL: str = 'txlistinternal'
|
fps = 30
width = 960
height = 700
screenDimensions = (width, height)
backgroundColor = (161, 173, 255)
mario_x = 100
mario_y = 500
jumpCount = 10 |
# coding: utf-8
class ModelDatabaseRouter(object):
"""
A router to control all database operations on models for different databases.
In case an model object's Meta is provided with db_name, the router
will take that database for all its transactions.
Settings example:
class Meta:
db... |
def par(i):
return i % 2 == 0
def impar(i):
return i % 2 == 1 |
# README
# Substitute the layer string point to the correct path
# depending where your gis_sample_data are
myVector = QgsVectorLayer("/qgis_sample_data/shapfiles/alaska.shp", "MyFirstVector", "ogr")
QgsMapLayerRegistry.instance().addMapLayers([myVector])
# get data provider
myDataProvider = myVector.dataProvider()
#... |
class UnknownTld(Exception):
pass
class FailedParsingWhoisOutput(Exception):
pass
class UnknownDateFormat(Exception):
pass
class WhoisCommandFailed(Exception):
pass
|
"""
Module: 'uasyncio.funcs' on pyboard 1.13.0-95
"""
# MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG')
# Stubber: 1.3.4
core = None
gather = None
wait_for = None
def wait_for_ms():
pass
|
mouse, cat, dog = "small", "medium", "large"
try:
print(camel)
except:
print("not difined")
finally:
print("Defined Animals list is:")
print("mouse:" , mouse, "cat:", cat, "dog:", dog) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
return self.traverse(s, t)
def helper(self, s: TreeNode, t: TreeN... |
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
file = fileLines[0]
file = file.strip('\n')
fileLength = len(file)
counter = -1
bracketOpen = False
repeatLength = ''
repeatTimes = ''
repeatLengthFound = False
... |
def prime(x):
print(f'{x%17}')
def dprime(x):
print(f'{x%13}')
prime(41) |
assert xxx and yyy # Alternative 1a. Check both expressions are true
assert xxx, yyy # Alternative 1b. Check 'xxx' is true, 'yyy' is the failure message.
tuple = (xxx, yyy) # Alternative 2. Check both elements of the tuple match expectations.
assert tuple[0]==xxx
assert tuple[1]==yyy
|
def named_property(name, doc=None):
def get_prop(self):
return self._contents.get(name)
def set_prop(self, value):
self._contents[name] = value
self.validate()
return property(get_prop, set_prop, doc=doc)
|
'''
57-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 o valor correto.
'''
sexo=str(input('Digite o seu sexo:[M/F] ')).strip().upper()[0]
while sexo not in 'MF':
sexo=str(input('\033[31m DADOS INVÁLIDOS!!!\n\033[mDigite novamente... |
USER_AGENT_LIST = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36',
'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; ... |
"""
Author: Mauro Mendez.
Date: 02/11/2020.
Hyperparameters for a run.
"""
parameters = {
# Random Seed
'seed': 123,
# Data
'train_file': '../data/train_labels.csv', # Path to the training dataset csv
'val_file': '../data/val_labels.csv', # Path to the validation dataset csv
'tes... |
"""
Using a Queue, this isn't as hard. Going with recursion and (by their definition, O(1) space) is
trickier. This is a first inefficient solution. `total_nodes` and `visited` show how this isn't O(N)
(for 1043 nodes, we visit 23k times). I need to look into this again.
"""
class Solution:
def connect(self, root... |
class FieldProperty:
def __init__(self, data_type, required=False, if_missing=None):
"""
:param data_type:
:param required:
:param if_missing: callable or default value
"""
self.data_type = data_type
self.required = required
self.if_missing = if_missi... |
# Ex072.2
"""Create a program that has a fully populated tuple with a count in full, from zero to twenty
Your program should read a number from the keyboard (between 0 and 20) and display it in full."""
number_in_full = ('Zero', 'One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven', 'Eight', 'Nine',
... |
largura = int(input("digite a largura: "))
altura = int(input("digite a altura: "))
x = 1
while x <= altura:
y = 1
while y <= largura:
if x == 1 or x == altura:
print("#", end = "")
else:
if y == 1 or y == largura:
print("#", end = "")
else:
... |
#
# PySNMP MIB module CISCO-CIDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CIDS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:35:57 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.