text stringlengths 8 6.05M |
|---|
"""
MVC 패턴
Model: DTO (data transfer object) + DAO (data access object)
Service: Business Login (Algorithm)
Controller: RESTful 방식으로 React Axios 로 통신
""" |
from sys import argv
title = raw_input (" what's your recipe title?" )
ingredient = raw_input (" tell the ingredients:" )
step_by_step = raw_input (" tell the step by step guide:" )
first = title
second = ingredient
third = step_by_step
# script, first, second, third = argv
print "The script is called:" #, script
p... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-09 23:24
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('th', '0003_auto_20180309_2318'),
]
operations = [
... |
#import sys
#input = sys.stdin.readline
from heapq import heapq, heappop
def main():
if __name__ == '__main__':
main()
|
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'tools.views.get_form', name='get_form'),
)
|
a = int(input("a="))
b = int(input("b="))
c = int(input("c="))
if (c >= (a + b)) or (b >= (a + c)) or (a >= (b + c)):
print("YES")
else:
print("NO")
|
import scipy.linalg as splinalg
import numpy as np
import math
#test_Givens_out_of_for_loop = False
test_Givens_out_of_for_loop = True
class GMRES_API(object):
def __init__( self,
A_coefficient_matrix: np.array([], dtype = float ),
b_boundary_condition_vector: np.array([], dty... |
import pickle
import sys
vocab_file = 'word_vocab.pkl'
with open(vocab_file, 'rb') as f:
vocabs = pickle.load(f)
print(len(vocabs))
|
import pygame
from settings import Settings
class Menu:
"""Class to create the game menu start/pause menu."""
def __init__(self, ai_game):
"""Initialize main menu."""
super().__init__()
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.setting... |
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2013-2019, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
################################... |
# -*- coding: utf-8 -*-
import arcpy
from arcpy import env
iWorkspace=arcpy.GetParameterAsText(0)
oriShp=arcpy.GetParameterAsText(1)
newShp=arcpy.GetParameterAsText(2)
dist=arcpy.GetParameterAsText(3)
def LEI(iWorkspace, oriShp, newShp, dist):
try:
dist=float(dist)
env.workspace=iWorkspace
... |
def main():
l,w,h = parse("2x3x4")
print(surface_area(l,w,h)) # 52
l,w,h = parse("1x1x10")
print(surface_area(l,w,h)) # 42
print(iterateFile("02_data.txt", surface_area)) # 1586300
l,w,h = parse("2x3x4")
print(calculate_ribbon(l,w,h)) # 34
l,w,h = parse("1x1x10")
print(c... |
from flask import Flask, request, redirect, render_template
import sqlite3
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")
@app.route("/query", methods = ["POST", "GET"])
def query():
con = sqlite3.connect("flowers2019.db")
con.row_factory = sqlite3.Row
cur =... |
from bge import logic
from . import multitouchProcessor
import ctypes
CFArrayRef = ctypes.c_void_p
CFMutableArrayRef = ctypes.c_void_p
CFIndex = ctypes.c_long
MultitouchSupport = ctypes.CDLL("/System/Library/PrivateFrameworks/MultitouchSupport.framework/MultitouchSupport")
CFArrayGetCount = MultitouchSupport.CFAr... |
#! usr/bin/python3
# -*- coding: utf-8 -*-
import datetime
from flask import render_template
from markdown import markdown
def display_post_box(ticket=None, post=None, replies=None, loop=None, page=None):
"""
:param ticket: object containing ticket information
:param post:
:param replies:
:par... |
import bpy
from mathutils import Vector
obj = bpy.context.active_object
print(obj)
pos = obj.location
# get current frame
cf = bpy.context.scene.frame_current
# set current frame
bpy.context.scene.frame_current = 1
#insert key, e.g. on location
obj.keyframe_insert(data_path='location', frame=1)
obj.location = Vec... |
import time
from app import app
from app.Models.RunModel import Run
from app.Models.PlanModel import Plan
from app.Models.ProductModel import Product
from app.Models.ProductModel import ProductVersion
from flask_login import login_required, current_user
from flask import Blueprint, request, redirect, url_for, render_te... |
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import optimize
def func(t, A, tau, T, phi, C):
"""Function to fit data."""
return A*np.exp(-t/tau)*np.cos(2.0*math.pi*t/T + phi) + C
# Given constants and measured values
m_1 = 1.5 # [kg] - Mass of small masses... |
import random
# your code here
def generate_random():
random_number = random.randrange(0,9)
return random_number
print(generate_random()) |
import base64
import urllib
from hawkeye_test_runner import DeprecatedHawkeyeTestCase
from hawkeye_test_runner import HawkeyeTestSuite
class CertificateValidation(DeprecatedHawkeyeTestCase):
def run_hawkeye_test(self):
good_cert = 'https://redmine.appscale.com/'
bad_cert = 'https://ocd.appscale.net:8081/'
... |
#import sys
#input = sys.stdin.readline
def main():
Z = int( input())
A = [ list(input()) for _ in range(Z)]
N = int(input("N"))
K = 2**N
B = [[0]*K for _ in range(K)]
for k in range(Z):
for i in range(K-1):
for j in range(i+1,K):
if A[k][i] == A[k][j]:
... |
"""Compute the average money made by rolling the dice."""
import random
import sys
import argparse
import my_plot
def main(argv):
"""Run the experiments 'm' times consisting of 'n' trials."""
opt = parse_cmd_line(argv)
results = []
dispatcher = {'max': max, 'min': min,
'anamaya': anamaya... |
from pysubparser import parser
import jieba
import sys
word_count = {}
learned = [
'好',
'你',
'我',
'什么',
'了',
'不',
'好',
'说',
'的',
'啊',
'吧',
'是',
'吗',
'就',
'那',
'去',
'都', '我们', '呢',
'顾未易', # gu wei yi
'这', '吃', '走', '他', '给', '怎么', '在', '想', '也... |
from django.db import models
from django.contrib.auth.models import User
# Creating a Temporary Model for User Details
class UserDetails(models.Model):
details = models.OneToOneField(User,on_delete=models.CASCADE)
first_name = models.CharField(null=True,blank=False,max_length = 50)
last_name = models.Cha... |
import pytest
from domain import activity, vo2
from measurement.measures import Speed
vo2_inst_testdata = [
(0, 0, Speed(mph=0), 0, 3.5), # Should get resting constant value of 3.5
(1, 1, Speed(kph=6), 0, 103.5),
(vo2.O2_COST_HORIZ_RUN, vo2.O2_COST_VERT_RUN, Speed(kph=6), 0, 23.5),
(vo2.O2_COST_HORIZ_W... |
# 패키지 안의 함수 실행하기
import game.sound.echo
game.sound.echo.echo_test()
from game.sound import echo
echo.echo_test()
from game.sound.echo import echo_test
echo_test()
from game.graphic.render import render_test
render_test() |
"""
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the ... |
import mysql.connector
mydb = mysql.connector.connect(
host=database_ip,
user=database_user,
passwd=database_password,
database=database_name
)
print(mydb)
mycursor = mydb.cursor()
|
str=input("enter string:")
for i in range(len(str)):
if str[i] not in str[:i]:
print("%c occurs %d times"%(str[i],str.count(str[i])))
|
#!/usr/bin/env python3
"""
test for the Sinumber module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.sinumber import number_as_si, si_as_number, si_range
class TestSinumber(PschedTestBase):
"""
Sinumber tests.
"""
def test_si_as_number(self):
"""SI as number te... |
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots() # 生成子图,相当于fig = plt.figure(),ax = fig.add_subplot(),其中ax的函数参数表示把当前画布进行分割,例:fig.add_subplot(2,2,2).表示将画布分割为两行两列
# ax在第2个子图中绘制,其中行优先,
xdata, ydata = [], [] # 初始化两个数组
ln, ... |
from django.shortcuts import render
import telepot
import urllib3, json
from django.http import HttpResponse
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton
from bot.models import Worker, LoggingStep, TimeSheet
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
import log... |
#!/usr/bin/python
from bs4 import BeautifulSoup
import sqlite3
class DB:
"""
Abstraction for the profile database
"""
def __init__(self, filename):
"""
Creates a new connection to the database
filename - The name of the database file to use
"""
self.Filename = ... |
def is_sorted(string):
for i in range(len(string)-1):
if(string[i] > string[i+1]):
return False
return True
print(is_sorted("ABC"))
print(is_sorted("aBc"))
print(is_sorted("dog")) |
from flask import render_template, redirect, url_for, session
from . import main
from . forms import MatchForm
from .. import db
from ..models import Fenxi
@main.route('/', methods=['GET', 'POST'])
def index():
form = MatchForm()
match_list = None
if form.validate_on_submit():
match_list = Fenxi.q... |
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://www.126.com")
WebDriverW... |
from abc import abstractmethod, ABC
class AnswersDAO(ABC):
@staticmethod
@abstractmethod
def get_all_answers_for_question(question_id):
pass
@staticmethod
@abstractmethod
def create_answer(answer, question_id):
pass
|
from django.urls import include, path
from story import views
app_name = 'story'
urlpatterns = [
path('home/', views.home, name='home'),
path('about_game/', views.about_game, name='about_game'),
path('start/', views.start, name='start'),
path('next/<int:option_id>/', views.next_page, name='next'),
]
|
# Author : Xiang Xu
# -*- coding: utf-8 -*-
def purity(clusters, points):
purity = 0
for i in xrange(len(clusters)):
cluster = clusters[i]
mi = len(cluster['cluster']) # mi is the count of cluster i
mij = {} # mij is the count of class j in cluster i
for point in cluster['clu... |
import unidecode
import shutil
DAYS = 4
DAY_NAMES = ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")
people = {}
class Person():
def __init__(self, info):
info = info.split(";")
self.name = self.set_name(info)
self.times = {}
self.can_drive = [False, False, False, False]
... |
from rv.api import m
def test_gpio(read_write_read_synth):
mod: m.Gpio = read_write_read_synth("gpio").module
assert mod.flags == 81
assert mod.name == "GPIO"
assert not mod.out
assert mod.out_pin == 213
assert mod.out_threshold == 46
assert mod.in_
assert mod.in_pin == 210
assert ... |
#procurando uma string dentro de outra
nome = str(input('Digite o seu nome completo: ')).strip()
nome = nome.lower()
print('Seu nome contem Silva? {}'.format('silva' in nome))
|
import gym
from gym import envs
import numpy as np
# import sys
nstates = 8*8 # $B>uBV?t(B
nactions = 4 # $B9TF0?t(B
eM = 100000 # $BI>2A$r9T$&%(%T%=!<%I?t(B
alpha = 0.7
gamma = 0.9
policySelect = 2 # 1: e-greedy$B<jK!(B 2: softmax$B<jK!(B
tau = 0.0016 # softmax$B<jK!$N29EY(... |
from ScrapeWebsite import *
from GetTweets import *
from TweetParser import *
from JSONHelper import *
from GeoLocationData import *
map_1
###Parse Twitter Data
##Get the number of tweets to retrieve.
#TopN = 10000
#consumerKey = 'ipTb7DZ0LbJ18p9ATjdrSQ23p'
#consumerSecret = 'DT9OroScZI4HoGbx7PkRL6ojir5T4GWvmlqCkPTd9... |
#!/usr/bin/env python
# Funtion:
# Filename:
import binascii
import zlib
with open(r'E:\vscode_pragram\mine\Python3\Python_learning\wxpython_leanning\tools\md5_tools\MD5_Hash.py', 'rb') as f:
# print(f.read())
# print(binascii.crc32(f.read()))
z = 0
for i in f:
z=zlib.crc32(i)
print('... |
from gtnlplib.constants import OFFSET
import numpy as np
# hint! use this.
def argmax(scores):
items = list(scores.items())
items.sort()
return items[np.argmax([i[1] for i in items])][0]
# This will no longer work for our purposes since python3's max does not guarantee deterministic ordering
# argmax = la... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import re
import sys
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
LOGGER.setLevel(logging.DEBUG)
HASH_PATTERN = re.compile(r'#([0-9a-fA-F]{40})\b')
ESCAPE_PATTERN = re.compile(r'\[#([0-9a-fA-F]{40})\]\(([^... |
from linkedlist import LinkedList
def remove_duplicates(llist):
value_set = set()
current_node = llist.head
while current_node is not None:
if current_node.data in value_set:
temp_node = current_node
current_node = current_node.next
llist.delete(temp_node)
... |
# RF로 모델링 하시오!!!
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV, RandomizedSearchCV
from sklearn.decomposition import PCA
from sklearn.metrics import accuracy_score
from sklearn.ensemb... |
import numpy as np
from mesh import *
from basis_func import *
from assemble import *
from viewer import *
def clear_rows(A,b_nodes):
""" code to clear rows """
for node in b_nodes:
t = A[node, node]
A[node, :] = 0
A[node, node]=t
if __name__ == "__main__":
(topo , x , y , no... |
#!/usr/bin/python
#-*-coding:utf-8-*-
from wx import WxAPI
import requests
import os
import time
from runonce import start_spider
from dytt import start_grasp
from xyy import run_xyy
from mmjpg import start_mmjpg
from apscheduler.schedulers.background import BackgroundScheduler
def get_oneday_text():
url = 'http:/... |
DEFAULT_ARRAY = [[1,2,[3]],4]
LOG_LEVEL = 'INFO'
|
"""
------------------------------------
@Time :
@Auth :
@File : HomePage.py
@IDE : PyCharm
@Motto:
------------------------------------
"""
from time import sleep
from Page.BasePage import BasePage
from util.parseConFile import ParseConFile
class HomePage(BasePage):
# 配置文件读取元素
do_conf = ParseConFile()
... |
# 105. Construct Binary Tree from Preorder and Inorder Traversal
#
# Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
#
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
# Return the following bi... |
# Generated by Django 3.2 on 2021-04-21 18:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pie', '0004_auto_20210421_2343'),
]
operations = [
migrations.AlterField(
model_name='showchart',
name='customer_id',
... |
import yfinance as yf
import pandas as pd
#import tensorflow as tf
import math
from datetime import datetime
from matplotlib import pyplot as plt
def createList(r1, r2, t, k):
list = []
for i in range(r1, r2+1):
list.append(round(i*t, k))
return list
def mean(lst):
return sum(lst) / len(lst)
... |
# Text and categorical data problems!!
# Categorical and text data can often be some of the messiest parts of a dataset due to their unstructured nature. In this chapter, you’ll learn how to fix whitespace and capitalization inconsistencies in category labels, collapse multiple categories into one, and reformat strings... |
from DBHelper import DBHelper
from helper_functions import *
from Product import *
from Customer import *
class Receipt:
def __init__(self):
self.db = DBHelper()
def __updateReceiptTotal (self, receiptNo):
sql = ("UPDATE receipt SET "
"total_receipt = new_total_receipt"
... |
import numpy
a = [float(x) for x in input().split()]
arr = numpy.array(a)
numpy.set_printoptions(sign=' ')
print(numpy.floor(arr))
print(numpy.ceil(arr))
print(numpy.rint(arr))
|
import logging
import os
from autumn.core.db import Database
from autumn.core.plots.plotter import FilePlotter
from . import plots
logger = logging.getLogger(__name__)
def plot_uncertainty(targets: dict, powerbi_db_path: str, output_dir: str):
"""
works on powerbi version
Assumes a COVID model.
"""... |
#!/usr/bin/env python
import rospy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
import utils
import create_map
rospy.init_node('line')
pub_line_min_dist = rospy.Publisher('/vgraph_markers', Marker, queue_size=1)
rospy.loginfo('Publishing line')
edges, shortest_path = utils.get_waypoi... |
import pytest
import pdb
test_id = f"{'2.7.3':<10} - Can Be Term Server"
test_weight = 2
def test_test_act_as_term_server(host):
assert 0 == 1, "TODO - Write Test"
|
class OperaException(Exception):
pass
class MethodNotFound(OperaException):
pass
class ServiceNotFound(OperaException):
pass
|
def attackQueen(board , qr , qc):
n = len(board)
count = 0
#up/left
for i in range(1 , qr):
if board[i] == 0:
count += 1
#down/right
for i in range(qr + 1 , n):
if board[i] == 0:
count += 1
... |
def InitCharts(algorithm):
performance_plot = Chart('Performance Breakdown')
performance_plot.AddSeries(Series('Total Fees', SeriesType.Line, 0))
performance_plot.AddSeries(Series('Total Gross Profit', SeriesType.Line, 0))
algorithm.AddChart(performance_plot)
exposure_plot = Chart('Exposure/Leverag... |
from svmutil import *
import subprocess
shuffled_file = open('spambase.data.shuffled', 'r')
X_ORIGINAL = []
Y_ORIGINAL = []
with open("spambase.data.shuffled", "r") as shuffled_file:
for line in shuffled_file:
values = line.split(',')
Y_ORIGINAL.append(int(values[-1]))
x_temp = []
... |
import datetime
import webapp2
from google.appengine.api import datastore
from google.appengine.ext import db
class CronObj(db.Model):
last_update = db.DateTimeProperty()
class CronHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = "application/json"
query = self.re... |
import configparser
import os
import sys
import gamepedia_client
class GamepediaPagesRW:
gc = None
'''
Create new instance of GamepediaClient (required for name attribution)
'''
def create_gamepedia_client(self, username=None, password=None):
global cfg_file
if username is None:
... |
#!/usr/bin/python
import urllib2
import json
req = urllib2.Request("https://api.wheretheiss.at/v1/satellites/25544")
response = urllib2.urlopen(req)
obj = json.loads(response.read())
print obj['visibility']
|
from django.db import models
from datetime import datetime
class CounterName(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=500)
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.title + ' - ' + self.description
... |
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
class MLPAutoEncoder(nn.Module):
"""docstring for AutoEncoder"""
def __init__(self):
super(AutoEncoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(32*32*32*12,... |
from nmigen import *
from .lib import stream
from .protocol import Transfer
__all__ = ["USBInputArbiter", "USBOutputArbiter"]
class RoundRobin(Elaboratable):
def __init__(self, width):
self.width = width
self.request = Signal(width)
self.ce = Signal()
self.grant = Signal(range(w... |
from payment_gateway.models import *
from LandingPage.models import *
import json
import razorpay
from django.http import JsonResponse
client = razorpay.Client(auth=("rzp_test_0G5HtLCg0WpC26", "y8iPiSBFRf8w2Y1W0L6Q7F55"))
def CreateOrder(request,productId,action=None):
customer = request.user
product = Course.... |
import numpy as np
class EdgeDetector:
def __init__(self):
pass
# Given a mask, apply that mask on the given pixel as center
def apply_mask(self, image, mask, row, col):
sum_r, sum_g, sum_b = 0, 0, 0
for x in range(-1, 1, 1):
for y in range(-1, 1, 1):
ro... |
import pygame, sys, glob, ntpath
from random import shuffle
from pygame.locals import *
from image import *
pygame.init()
clock = pygame.time.Clock()
LENGTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((LENGTH,HEIGHT))
BKG= []
for bkg in glob.glob("./images/bkg-*.png"):
back= load_image(bkg,"",LENGTH,HEIGH... |
import socket
import json
import select
from util_m import *
class Server(BaseServer):
def __init__(self, addr, port):
super(Server, self).__init__(addr, port)
self.log = Log('Server')
self.messageListBuffer = MessageListBuffer(400, 50)
self.bytesListBuffer = BytesBuffer()
def ... |
import argparse
import torch
from collections import OrderedDict
from os.path import isdir
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
# Function get_input_args() parses keyword arguments from the command line
def get_input... |
import csv
import time
from lxml import html
import requests
import unidecode
#The first scraper take each website link (listing conferences) from the csv file, go through the website and get the name of the authors
#and print these names into a new csv
#The second scraper takes the titles of the publications and pri... |
# @Title: 反转链表 (Reverse Linked List)
# @Author: 2464512446@qq.com
# @Date: 2020-11-08 00:00:23
# @Runtime: 36 ms
# @Memory: 14.4 MB
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList... |
default_app_config = 'values.apps.ValuesConfig'
|
#!/usr/bin/env python
import random
nums = [x for x in range(3, 100)]
print nums
key = 14
checked = []
for i, n in enumerate(nums):
checked.append([i, n])
while True:
midInt = len(checked)/2 - 1
mid = checked[midInt][1]
if mid == key:
print 'Found it at index %d!' % checked[midInt][0]
... |
import requests
class Weather():
"""
Creates Weather object containing information about Current weather
"""
def __init__(self, area, appid):
self.area = area
self.weather_url = "http://api.openweathermap.org/"
self.appid = appid
def weather_condition(self):
"""
... |
from mlmodel import MLModel
from sklearn.neighbors import KNeighborsRegressor
class KNeighbors(MLModel):
def train(self, n_neighbors=5):
'''
'''
# Shuffle the training/test data:
self.shuffle()
# Create & Train Model:
self.model = KNeighborsRegressor(n_neighbors=n_n... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.conf import settings
import stripe
stripe.api_key=settings.STRIPE_SECRET_KEY
@login_required
def checkout(request):
publishKey = settings.STRIPE_PUBLISHABLE_KEY
if request.method =='POST':
token = request.POS... |
def setrate(roll, rate, fslist):
for fscount in fslist:
for fsrate in range(rate):
roll += [fscount]
return roll
roll0 = []
for u01 in range(23):
roll0 += ["Crab Long Bao"]
roll0 += ["Gingerbread"]
for u02 in range(61):
roll0 += ["Bamboo Rice"]
roll0 += ["Peking ... |
altura=float(input("Altura:"))
base=float(input("Lagura:"))
area= base*altura
print("O valor da area é de",area)
|
import networkx as nx
import numpy as np
import datetime
import pickle
import matplotlib.pyplot as plt
G = nx.read_graphml('G_10_power_3_2017-03-29-21:24.graphml')
mapping = {str(x):x for x in range(len(G.nodes()))}
nx.relabel_nodes(G, mapping, copy=False)
every_ngbd = np.load('every_ngbd_G_10_power_3_2017-03-29-21:24... |
num = int(input('Input a num: '))
def getfactors(num):
alist = []
for i in range(1, num+1):
if num % i == 0:
alist.append(i)
else:
continue
return alist
print(getfactors(num))
|
print("Let's practice everything.")
print("You'd need to know \' about escapes with \\ that do\n newlines"
,"and \t tabs.")
poem ="""
\tThe lovely world
with logic so firmly planted
cannot discern \nthe needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
""... |
from django import forms
from .models import *
from django.conf import settings
class ProduitForm(forms.ModelForm):
qte_stocke = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control','placeholder':'Quantite'}), required = True)
categorie = forms.ModelChoiceField(widget=forms.Select(attrs={ ... |
#
# Copyright 2015-2016 Bleemeo
#
# bleemeo.com an infrastructure monitoring solution in the Cloud
#
# 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/lice... |
import player
import numpy as np
import sys
import random
import matplotlib.pyplot as plt
sys.path.append("../")
number_of_pieces = 4
# states = ["home", "goal_zone", "goal", "danger", "glob","safe"]
total_number_of_states = 60
# actions = ["move_out", "normal", "goal_zone", "goal", "star", "globe", "protect", "kill"... |
import os, sys
from pprint import pprint
# print(sys.path)
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.data import parallel_reader
# import config as cfg
# 优化器
adadelta_rho = 0.95
adagrad_initial_accumulator_value = 0.1
adam_beta1 = 0.9
adam_beta2 = 0.999,
opt_epsilon = 1.0
ftrl_learning_rate_p... |
import torch.nn as nn
import torchvision.models as backbone_
import torch.nn.functional as F
import torch
from torchvision.ops import MultiScaleRoIAlign
from collections import OrderedDict
import torch
import torchvision
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from torch.nn.utils.rnn impor... |
"""
@author : Anish Lakkapragada
@date : 3 - 4 - 2021
Gaussian Mixtures are one of the best models today in the field of anomaly detection and unsupervised clustering.
But it's not just because of that that this is one of the best modules SeaLion has to offer.
"""
import numpy as np
class GaussianMixture() :
"""... |
from aiohttp import web
from serv.config import web_routes, home_path
import serv.main_views
import serv.grade_views
import serv.student_views
import serv.student_rest
import serv.course_view
import serv.course_rest
app = web.Application()
app.add_routes(web_routes)
app.add_routes([web.static("/", home_path / "sta... |
import pygame
from pygame.draw import *
from random import randint
pygame.init()
FPS = 20
screen = pygame.display.set_mode((1200, 900))
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
COLORS = [RED, BLUE, YELLOW, GREEN, MAG... |
from ast import literal_eval
from flask import Flask
from flask_graphql import GraphQLView
from schema import schema
from database import connector
from database.people_table import People
from database.planet_table import Planet
import os
server = Flask(__name__)
def load_database():
connector.Base.metadata.cre... |
"""
A script to back up files that have changed on the local store
to the specified cloud service.
Change is determined by modify time.
"""
import argparse
import os
import logging
import sync_drives.sync as sync
import providers.provider_list as provider_list
from common.basic_utils import check_for_user_quit
def ... |
# import the necessary packages
from lib.rgbhistogram import RGBHistogram
import argparse
import cPickle as pickle
import glob
import cv2
import os
def parse_args():
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required = True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.