content stringlengths 7 1.05M |
|---|
# La funcion calcula sobre un promedio de notas ingresadas de 0 a 100
def nota_quices(codigo: str, nota1: int, nota2: int, nota3: int, nota4: int, nota5: int)-> str:
notasEstudiate=(nota1, nota2, nota3, nota4, nota5)
notaMin= min(notasEstudiate) # Elegir la menor nota para descartar
promedioAcordado= (n... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 20:00:03 2021
@author: User
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
def isPrime(n):
result = True
for i in range(2, n, 1):
if n % i == 0 :
result =... |
name = "core_pipeline"
version = "2.1.0"
build_command = "python -m rezutil {root}"
private_build_requires = ["rezutil-1"]
_environ = {
"PYTHONPATH": [
"{root}/python",
],
}
def commands():
global env
global this
global system
global expandvars
for key, value in this._environ.it... |
#!/usr/bin/env python3
intList = [1,2,3]
def normalList():
print("initial list: " + str(intList)) # must be str, not list or type
# list items can be reassigned
normalList()
print(intList + [4,5]) # temp print list with more indexes
intList.append(6) # permenently add a 6 to list.
# Using .append METHOD from f... |
try:
aa = 1.0/0
except Exception as e:
print(e)
print(aa)
class Animal():
def __init__(self):
self.age = 1
class Cat(Animal):
def __init__(self):
super().__init__()
self.age = 2
self.name = 'Cat'
c = Cat()
print(c.age)
print(c.name)
class Student():
def fu... |
# optimizer
optimizer = dict(type='SGD', lr=0.003, momentum=0.9, weight_decay=0.0005) #0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=10, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[16])
total_epochs = 22
|
def set_age(name, age):
if not 0 < age < 120:
raise ValueError('年龄超出范围')
print('%s is %d years old' % (name, age))
def set_age2(name, age):
assert 0 < age < 120, '年龄超出范围'
print('%s is %d years old' % (name, age))
if __name__ == '__main__':
# set_age('崔军', 244)
try:
set_age('崔... |
courses = {}
commands = input()
while not commands == "end":
commands = commands.split(" : ")
if commands[0] not in courses:
courses[commands[0]] = []
courses[commands[0]].append(commands[1])
else:
courses[commands[0]].append(commands[1])
commands = input()
#a = sorted(... |
"""
This file contains different status codes for NetConnection, NetStream and SharedObject.
The source code was taken from the rtmpy project (https://github.com/hydralabs/rtmpy)
https://github.com/hydralabs/rtmpy/blob/master/rtmpy/status/codes.py
"""
# === NetConnection status codes and what they mean. ===
... |
# Time: O(logn)
# Space: O(logn)
# 1104
# In an infinite binary tree where every node has two children, nodes are labelled in row order.
#
# In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right,
# while in the even numbered rows (second, fourth, sixth,...), the labelling is righ... |
# Common utilities
def get_mi2idf(tree):
root = tree.getroot()
mi2idf = dict()
# dirty settings
ellipsises = [
'e280a6', # HORIZONTAL ELLIPSIS (…)
'e28baf', # MIDLINE HORIZONTAL ELLIPSIS (⋯)
]
# loop mi in the tree
for e in root.xpath('//mi'):
mi_id = e.attrib.ge... |
#
# PySNMP MIB module BENU-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
'''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
def prime_sum(n):
if n < 2: return 0
if n == 2: return 2
if n % 2 == 0: n += 1
primes = [True] * n
primes[0],primes[1] = [None] * 2
sum = 0
for ind,val in enumerate(primes):
... |
engine_repository = [ ['https://github.com/Relintai/godot.git', 'git@github.com:Relintai/godot.git'], 'engine', '' ]
module_repositories = [
[ ['https://github.com/Relintai/entity_spell_system.git', 'git@github.com:Relintai/entity_spell_system.git'], 'entity_spell_system', '' ],
[ ['https://github.com/Relinta... |
# Approach 2 - Optimized
# Time: O(n)
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
l = len(flowerbed)
flowerbed = [0] + flowerbed + [0]
for i in range(1, l+1):
if flowerbed[i] == flowerbed[i-1] == flowerbed[i+1] == 0:
... |
"""
Given a binary tree, return all root-to-leaf paths.
Example 1:
Input:{1,2,3,#,5}
Output:["1->2->5","1->3"]
Explanation:
1
/ \
2 3
\
5
Solution:
DFS + Backtracking
"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = No... |
#ENTRADA DE VALORES
lista = list(map(float, input().split()))
#ORGANIZANDO A LISTA PARA QUE O PRIMEIRO ELEMENTO SEJA O MAIOR VALOR
lista.sort(reverse=True)
a, b, c = lista[0], lista[1], lista[2]
if a >= b+c:
print("NAO FORMA TRIANGULO")
elif a**2 == b**2 + c**2:
print("TRIANGULO RETANGULO")
elif a**2 > b**2 + c**... |
class Game:
def __init__(self, id, match_up):
self.id = id
self.match_up = match_up
def __unicode__(self):
return '{0} - {1}'.format(self.get_additional_unicode(), self.get_base_unicode())
def get_base_unicode(self):
return 'id: {id} | match up: {match_up}'.format(self.id,... |
#
# PySNMP MIB module OMNI-gx2EDFA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OMNI-gx2EDFA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:33:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
# [기초-종합] 주사위를 2개 던지면?(설명)
# minso.jeong@daum.net
'''
문제링크 : https://www.codeup.kr/problem.php?id=1081
'''
n, m = map(int, input().split())
for i in range(n):
for j in range(m):
print(i+1, j+1) |
class Config(object):
#Google API keys
OAUTH2_SCOPE = 'https://www.googleapis.com/auth/drive'
DRIVE_CLIENT_ID = 'your drive client id'
DRIVE_CLIENT_SECRET = 'your drive client secret'
DRIVE_REDIRECT_URI = 'your redirect uri'
|
nome = 'fazenda', 'caro', 'notebook', 'agua', 'helicoptero', 'aviao'
for n in nome:
print(f'\no nome {n} tem as vogais:', end=' ')
for vogal in n:
if vogal.lower() in 'aeiou':
print(vogal, end=' ')
|
load("@rules_vulkan//glsl:repositories.bzl", "glsl_repositories")
load("@rules_vulkan//vulkan/platform:windows.bzl", "vulkan_windows")
load("@rules_vulkan//vulkan/platform:linux.bzl", "vulkan_linux")
def vulkan_repositories():
"""Loads the required repositories into the workspace
"""
vulkan_windows(
... |
#
# PySNMP MIB module RFC1382-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1382-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:32:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
class ResponseStatusError(Exception):
status: int
def __init__(self, message: str, status: int):
super().__init__(message)
self.status = status
def __reduce__(self): # pragma: no cover
return (type(self), (*self.args, self.status))
class ConfigDependencyError(Exception):
pas... |
input = [16, 11, 15, 0, 1, 7]
x = input.pop()
seen = {v: i for (i, v) in enumerate(input)}
target = 30000000
for i in range(len(input), target - 1):
s = seen.get(x)
seen[x] = i
x = 0
if s is not None:
x = i - s
print(x)
# 0
# 8
# 14
# 8
# 2
# 165
# 1811
# 15075
# 182867
# 623065
# 0
# 10
#... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Author: Sz
WeChat: itlke-sz
-------------------------------------------------
"""
__author__ = 'Sz'
print("撩课") |
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False
return True
str = input("enter a sentence :\n ")
if ispangram(str):
print('contains all alphabets')
else:
print('does not contain all alph... |
def bit_floor(n: int) -> int:
"""Calculate the largest power of two not greater than n.
If zero, returns zero."""
if n:
# see https://stackoverflow.com/a/14267825/17332200
exp = (n // 2).bit_length()
res = 1 << exp
return res
else:
return 0
|
html = """
<!DOCTYPE html>
<html>
<head>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
... |
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = int(input("Enter choice(1/2/3/4): "))
# check if choice is one of the four options
if choice in (1, 2, 3, 4):
num1 = float(input("Enter first numb... |
def test_home_retorna_status_code_200(client):
response = client.get("/")
assert response.status_code == 200
def test_home_retorna_texto_ola(client):
response = client.get("/")
assert response.text == "ola"
def test_echo_retorna_status_code_200(client):
response = client.get("/echo")
assert ... |
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. 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 require... |
bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9
print(bool_one) #True
print(bool_two) #False
print(bool_three) #True
my_bool = "true"
print(type(my_bool)) #<class 'str'>
my_bool_two = True
print(type(my_bool_two)) #<class 'bool'>
my_bool_three = 452
print(type(my_bool_three)) #<class 'int'> |
a = int(input())
b = int(input())
range = range(a, b + 1)
list = list(filter(lambda x: x % 3 == 0, range))
print(sum(list) / len(list))
|
# angle.py: A class describing an angle between three atoms.
class Angle:
atom1 = ""
atom2 = ""
atom3 = ""
angle = 0.0
def __init__(self, atom1, atom2, atom3, angle):
self.atom1 = atom1
self.atom2 = atom2
self.atom3 = atom3
self.angle = angle
|
#!/usr/bin/env python3
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
# the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci
# sequence whose values do not exceed four million, find the sum of th... |
def solve(data):
X, Y, N, W, P1, P2 = data
for _ in range(int(input())):
data = [int(num) for num in input().split(" ")]
print(solve(data)) |
# -*- coding: utf-8 -*-
def main():
n = int(input())
h = int(input())
w = int(input())
print((n - w + 1) * (n - h + 1))
if __name__ == '__main__':
main()
|
class NoInteractionsFound(Exception):
def __init__(self, description: str = None, hint: str = None):
super(NoInteractionsFound, self).__init__('No CellPhoneDB interacions found in this input.')
self.description = description
self.hint = hint
|
# 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 findSecondMinimumValue(self, root: TreeNode) -> int:
small = root.val
res = []
... |
#encoding:utf-8
subreddit = 'Genshin_Impact'
t_channel = '@Genshin_Impact_reddit'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
#
# PySNMP MIB module DEC-ATM-SIGNALLING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DEC-ATM-SIGNALLING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
#!/usr/bin/python
print("Hello world")
print("GOD LOVES YOU")
print("John 3:16\n")
print("CHRIST JESUS: EMMANUEL...")
print("Full of TRUTH & GRACE")
print("John 1:17\n")
print("Love God: with ALL you are... + the kitchen sink!")
print("Love ya Neighbour: as you already love ya self...")
print("ENJOY THE DISCIPLESHIP... |
class Category:
ANTIQUES_COLLECTABLES = '/for-sale/antiques-collectables/66/'
ANTIQUES_COLLECTABLES__AUTOGRAPHS = '/for-sale/antiques-collectables/autographs/984/'
ANTIQUES_COLLECTABLES__BOTTLES = '/for-sale/antiques-collectables/bottles/985/'
ANTIQUES_COLLECTABLES__CALL_CARDS = '/for-sale/antiques-coll... |
i = 0
v = "test"
c = 0.1
print("{0} {1} {2}".format(i, c, v))
|
{
"origin": [ "Where in the world am I? #Place#? I should be in prison. ", "#greeting#, remember to thank #Place# for their sacrifice of hosting Trump today! Someone save me.", "I escaped to #Place# but Trumps on my tail! I need help!", "Things I overhear: collusion....Idoit....#Phrase#......", "I'm having a great... |
hour_test = 6
if not args.hr:
hr = convertMonDayHr(hour_test)
elif hour_test < 12:
hr = convertMonDayHr(hour_test)
hr = "上午" + hr
elif hour_test > 12:
hr = convertMonDayHr(hour_test - 12)
hr = "下午" + hr
else:
hr = convertMonDayHr(hour_test)
hr = "下午" + hr |
'''def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0,n-i-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
arr = [10,9,15,1,5,2,6,3]
bubbleSort(arr)
print('Sorted array: ')
for i in range(len(arr)):
... |
# Create 2 variables for future operations
x = 0b101001 # Here we create 2 variables with values x = 41, y = 38
y = 0b100110 # We create bit numbers with the "0b" notation.
print(x, y)
# Bitwise AND -- "&"
# It returns 1 if two of the bits 1 and 0 if one of the bits 1 or both 0
z = x & y # which makes z = 0b001... |
# -*- coding:utf-8 -*-
'''
A string is considered to be in title case if each word in the string is either (a) capitalised
(that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower
case unless it is the first word, which is always capitalised.
... |
class Node:
"""Create a Node object"""
def __init__(self, val, next=None):
"""Constructor for the Node object"""
self.val = val
self._next = next
if val is None:
raise TypeError('Must pass a value')
def __repr__(self):
return '{val}'.format(val=self.val)... |
def is_same(num):
if (sum(map(int, str(num))) % 3 != 0):
return False
a = set()
for i in range(1,6):
val = str(num * i)
a.add(''.join(sorted(val)))
if (num == 142857):
print(a)
return len(a) == 1
for i in range(1000,10000000):
for j in range(10, 15):
... |
#
# PySNMP MIB module FILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FILTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:13:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
#Passwd file for passwordmanager app
loginpass='windowsADpasswd'
user='domain.name\\username'
passwordReset = 'staticPassword'
new_pass = 'newadpassword'
adServer='adServer.domain.name'
|
#Algoritmos Computacionais e Estruturas de Dados
#1a Lista de Exercícios
#Prof.: Laercio Brito
#Dia: 23/08/2021
#Turma 2BINFO
#Alunos:
#Victor Kauã Martins Nunes
#Dora Tezulino Santos
#Guilherme de Almeida Torrão
#Mauro Campos Pahoor
#Victor Pinheiro Palmeira
balas=5
rodando=True #bool para checar se outra chec... |
# Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars.
# Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can
# «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, a... |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Bake
# COLOR: #685777
# TEXTCOLOR: #ffffff
#
#----------------------------------------------------------------------------------------------------... |
"""Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1
to n and obeys the following requirement: Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|,
|a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
If there are ... |
def sayhi(name):
print("Hello "+ name)
sayhi(" vaibhav .")
def data(name,age):
print("Hello " + name +" You are " + str(age)+ ".")
nm=input("Enter the name: ")
age=int(input("Enter the age: "))
data(nm,age)
|
#
# @lc app=leetcode id=1289 lang=python3
#
# [1289] Minimum Falling Path Sum II
#
# https://leetcode.com/problems/minimum-falling-path-sum-ii/description/
#
# algorithms
# Hard (62.37%)
# Likes: 355
# Dislikes: 37
# Total Accepted: 16K
# Total Submissions: 25.5K
# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'
#... |
class MemberStore:
members = []
last_id = 1
def get_all(self):
return MemberStore.members
def add(self, member):
member.id = MemberStore.last_id
MemberStore.members.append(member)
MemberStore.last_id += 1
def get_by_id(self, id):
member_list = self.get_al... |
"""Sorting Algorithms In Python
"""
"""
Dutch national flag problem
https://en.wikipedia.org/wiki/Dutch_national_flag_problem
"""
def sort_colors(nums: [int], pivot: int)->[int]:
small = 0
current = 1
big = len(nums)-1
while current < big:
if nums[current] == pivot:
current += 1
... |
# -*- coding: utf8 -*-
class DogEvent(object):
def __init__(self, event_type, data):
self.event_type = event_type
self.data = data
def get_event(self):
tmp = ""
if isinstance(self.data, dict):
for k in self.data.keys():
tmp += "{}={}~".format(... |
# Version of the specification for MDF
MODECI_MDF_VERSION = "0.1"
# Version of the python module. Use MDF version here and just change minor version
__version__ = "%s.3" % MODECI_MDF_VERSION
|
#Write a program that asks the user for an input 'n' and prints a square of n by n asterisks "*".
number = int(input("Give me a number: "))
line = '*'*number
for x in range(0, number):
print (line) |
def find_min_idx(i, count, arr, min_element):
min_idx = 0
while i <= count and i < len(arr):
if arr[i] < min_element:
min_element = arr[i]
min_idx = i
i += 1
return min_idx
def find_min_array(arr, k):
min_element = 1_000_000
i = 0
count = k
while ... |
"""
The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to
all sequences in a set of sequences (often just two sequences).
It differs from the longest common substring problem: unlike substrings, subsequences are not required to
occupy consecutive positions within the ... |
liste_caracteres_bloques = ["!", "#", "&", "=", "~", "+", "é", "4", "5", "6", "7", "8", "9", "i", "j", "k", "n", "p", "q", "r", "s", "t", "u", "s", "t", "u"]
liste_caracteres_fleche = ["w", "x", "y", "z"]
liste_caracteres_maison = ["v"]
coordonnees_interieur_maison = [[384, 352]]
# coordos de l'emplacement de la porte
... |
temp = {}
galera = []
soma = 0
while True:
temp['nome'] = str(input('Nome da pessoa: ')).capitalize()
while True:
temp['sexo'] = str(input(f'Sexo de {temp["nome"]}: ')).strip().upper()
if temp['sexo'] in 'MF':
break
else:
print('Sexo invalido, por favor ... |
"""Utilities for Java brotli tests."""
_TEST_JVM_FLAGS = [
"-DBROTLI_ENABLE_ASSERTS=true",
]
def brotli_java_test(name, main_class = None, jvm_flags = None, **kwargs):
"""test duplication rule that creates 32/64-bit test pair."""
if jvm_flags == None:
jvm_flags = []
jvm_flags = jvm_flags + _T... |
expected_output = {
'caf_service': 'Not Running',
'ha_service': 'Not Running',
'ioxman_service': 'Not Running',
'sec_storage_service': 'Not Running',
'libvirtd': 'Running',
'dockerd': 'Not Running',
'redundancy_status': 'Non-Redundant'
} |
# The following templates are markdowns
overview = """
## Context
Manufacturing process feature selection and categorization
## Content
Abstract: Data from a semi-conductor manufacturing process
Data Set Characteristics: Multivariate
Number of Instances: 1567
Area: Computer
Attribute Characteristic... |
def test():
assert gato_hash == nlp.vocab.strings["gato"], "Você atribuiu o código hash corretamente?"
assert 'nlp.vocab.strings["gato"]' in __solution__, "Você selecionou a string corretamente?"
assert gato_string == "gato", "Você selecionou a string corretamente?"
assert (
"nlp.vocab.strings[g... |
total = 0
current = 1
prev = 1
while current < 4000000:
temp = current
current = current + prev
prev = temp
if current % 2 == 0:
total += current
print (total) |
f = open("Acc_2021-02-21_231529.txt", "r")
acc = []
for line in f.readlines()[1:]:
aa = line.split()[1:]
bb = line.split()[1:]
for i, a in enumerate(bb):
bb[i] = f"{a}f"
acc.append(bb)
acc = acc[0::8]
dataTowrite = []
dataTowrite.append(f"const float accData[{len(acc)}][3] = {{\n")
fo... |
class MarkupFile:
def __init__(self, data):
self.data = data
self.parse()
def parse(self):
raw = self.data.split('\n')
no_comments = []
for line in raw:
line += line.split('#')[0]
in_block_comment = False
no_block_comments = []
... |
class Solution:
def binarySearch(self, nums, start, end, target, lower):
ret = -1
while start <= end:
mid = (end + start) // 2
if nums[mid] < target:
start = mid + 1
elif nums[mid] > target:
end = mid - 1
else:
... |
class VnfListNotAvailable(Exception):
"""VNF list is not included in the openmano instance"""
pass
class VmListNotAvailable(Exception):
"""VM list is not included in the VNF record, part of the openmano instance"""
pass
class InstanceNotFound(Exception):
"""Openmano instance not found"""
pas... |
__copyright__ = 'Copyright (C) 2019 rtafds'
__version__ = '0.0.1'
__license__ = 'MIT'
__author__ = 'rtafds'
__author_email__ = 'n.rtafds@gmail.coms'
|
__all__ = [
'base_controller',
'forms_controller',
'landing_page_controller',
'messages_controller',
'objects_controller',
'tasks_controller',
'transactions_controller',
] |
# from aoc2019.day_six.planetary_composite import CentralMassComposite
class BFSPlanetaryIterator:
"""
This is an implementation of the iterator design pattern. It is applied to
the n-ary tree structure of planetary components. Each returned element is
a binary tuple (component, depth).
"""
de... |
# 1. var names cannot contain whitespaces
# 2. var names cannot start with a number
my_age = 27 # int
price = 0.5 # float
my_name_is_jan = True # bool
my_name_is_peter = False # bool
my_name = "Jan Schaffranek" # str
print(my_age)
print(price)
|
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4744, "depth": 1}
if obj[0]>1:
# {"feature": "Distance", "instances": 5889, "metric_value": 0.4618, "depth": 2}
if obj[3]<=2:
# {"feature": "Occupation", ... |
class HandlerMissingException(Exception):
"""Raised when an event handler is missing a handler for a specific event."""
pass
class DataTypeError(Exception):
"""Raised when data type doesn't correspond to the connection's data type."""
pass
class HeaderSizeError(Exception):
"""Raised when the hea... |
class Hello:
def __init__(self):
while True:
print("Hello!")
|
'''
Given four lists A, B, C, D of integer values, compute
how many tuples (i, j, k, l) there are such that
A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same
length of N where 0 ≤ N ≤ 500. All integers are in the
range of -228 to 228 - 1 and the resul... |
"""
Extends the scitables core to display tables in a browser.
UITable is a rendering independent user API to tables.
DGTable is an API to tables that gets rendered in YUI DataTable
"""
|
# In python you have this set of boolean expression
# == to check for equality or 'is'
# === to compare actual objects together
# True and False
# and, or, not
if 1 is 3:
print('What!! is that for real?')
elif 1 > 3:
print('Really????')
else:
print('Yeah that\'s what I know')
|
trainers = get_trainers(env, num_agents, "learner", obs_shape_n, arglist,session)
U.initialize()
obs_n = env.reset()
train_step=0
while True:
#Interaction step
iter_step=0
#Interact with environment to get experience
while True:
# get action
action_n = [agent.action(obs) for agent, obs... |
##----- Class Queue with their Operations -----##
class Queue:
def __init__(self):
print("Queue is all set to work on......\n")
self.Queue = []
def __Insertion__(self):
self.Queue.append((input("Enter Element :: ")))
print("\nElement Inserted Successfully!!!\n")
def __Trave... |
# creating a txt file
write_file = open('sample.txt', 'w')
write_file.write("this is just a sample text\n")
write_file.close()
# reading file
read_file = open('sample.txt' , 'r')
text = read_file.read()
print(text)
|
def countSwaps(a):
n = len(a)
swaps = 0
for i in range(0, n):
for j in range(0, n-1):
if a[j] > a[j+1]:
aux = a[j]
a[j] = a[j+1]
a[j+1] = aux
swaps += 1
print('Array is sorted in',swaps, 'swaps')
print ('First Elem... |
def slices(series, length):
if not series:
raise ValueError("invalid series")
if length <= 0:
raise ValueError("Length must be positive integer")
if length > len(series):
raise ValueError("Length must be less or equal to series length")
return [
series[start : start + len... |
"""
This is a undirected graph
A---C---E
| | |
B---D---|
"""
class createGraph:
def __init__(self, vertices) -> None:
self.vertices = vertices
self.graph_dict = {}
# create blank values for all the vertices
for node in self.vertices:
self.graph_dict[node] = []
d... |
# Informe duas notas e sem seguida mostre sua média.
n1 = float(input('Informe a primeira nota: '))
n2 = float(input('Informe a segunda nota: '))
print("As notas do aluno foram {} e {}, logo sua média será {:.2f}".format(n1, n2, (n1 + n2)/2))
|
"""
Dada uma String "str", retorne uma nova que será uma cópia "n" vezes da original.
"n" não será negativo.
"""
def string_times(str, n):
return str*n
print(string_times("CASA", 0))
|
# RUN: test-ir.sh %s
# IR-LABEL: while.0:
# IR: br i1 %{{[0-9]+}}, label %loop.0, label %endwhile.0
while True:
# IR-LABEL: loop.0:
if True:
# IR-LABEL: then.0:
# IR: br label %endwhile.0
break
# IR-LABEL: endif.0:
# IR: br label %while.0
# IR-LABEL: endwhile.0:
|
#Faça um programa que pergunte o preço de três produtos e informe qual produto você deve
#comprar, sabendo que a decisão é sempre pelo mais barato.
prod1 = float(input("Informe o valor do primeiro produto: "))
prod2 = float(input("Informe o valor do segundo produto: "))
prod3 = float(input("Informe o valor do terceir... |
# 4. Convert Meters to Kilometers
# You will be given an integer that will be distance in meters.
# Write a program that converts meters to kilometers formatted to the second decimal point.
meters = int(input())
km = meters/1000
print(f'{km:.2f}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.