text
stringlengths
38
1.54M
from django.db import models from django.contrib.auth import get_user_model # Create your models here. class Appointment(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=40) name_of_location = models.CharField(max_length=40) latitude = models.DecimalFiel...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from dateutil.parser import parse from datetime import timedelta import re def parseTIME(string): return parse(string) def parseTIMEDELTA(string): result = re.match( "(?P<hours>.+)\:(?P<minutes>.+)\:(?P<seconds>.+)\.(?P<milliseconds>.+)", string) re...
from turtle import * t1 = Turtle() t2 = Turtle() t1.forward(100) t2.pencolor("red") t2.right(20) t2.forward(100) goto(20, 30) t2.goto(20,30) goto(20,50)
import requests import cPickle def api_call(params, port): params = cPickle.dumps(params, protocol=2) response = requests.post(url='http://142.0.203.36:%d/api' % port, data=params) return cPickle.loads(response.content)
"""import library""" from tqdm import tqdm import time, urllib.request, requests, os from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import Web...
a = 1 b = 3 # Make sure you keep note of the values per variable for i in range(3): a = b # indentation = 4 spaces b = a + 1 print('What are the values of a and b?')
import logging import base64 import boto3 import uuid import time import json import requests from io import BytesIO from PIL import Image, ImageFont, ImageDraw, ImageEnhance from chalice import Chalice, Response, BadRequestError from chalicelib import get_stage # from chalicelib.db.models import DetectedPeopleModel f...
from PIL import Image, ImageDraw, ImageFont import operator class ViewModel: SIZE = (128,64) FONT = 'consola.ttf' def generateView(self): raise NotImplementedError( "Should have implemented this" ) def drawInversedText(self, draw, xy, text, font): size = font.getsize(text) tillx...
import bs4 import requests import csv writerFileHandle = open("data.csv", "w", newline='') writer1 = csv.writer(writerFileHandle) requestObj = requests.get("http://www.weather.gov.sg/weather-currentobservations-temperature") requestObj.raise_for_status() soup = bs4.BeautifulSoup(requestObj.text, 'html.parser') data...
""" Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. """ class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ MAX_INT = 2147483647 ...
from flask.blueprints import Blueprint from flask import render_template from flask import request from managers.dbService import DatabaseManager from extensions import db db_manager = DatabaseManager(db) addGroup = Blueprint('addGroup', __name__, template_folder='templates', ...
import requests import os.path from unrar import rarfile from clint.textui import progress fias_url = 'https://fias-file.nalog.ru/ExportDownloads?file=5158f5b0-3e7a-44a4-acf9-efaddee71fe2' fias_file = 'fias_db.rar' def extract_addrob(file_path): r_file = rarfile.RarFile(file_path) for f in r_file.infolist(): ...
import fileinput # input is .txt list of coordinates in form: x,y # output is .txt list of code to paste on arduino IDE X = [] Y = [] every_n = 2 # remove every other pixel to increase refresh rate i = 0 for line in fileinput.input(): i += 1 if i % every_n != 0: continue x, y = line.strip().split(",") ...
#!/usr/bin/env python3 # Resilience #Problem 243 #A positive fraction whose numerator is less than its denominator is called a proper fraction. #For any denominator, d, there will be d−1 proper fractions; for example, with d = 12: #1/12 , 2/12 , 3/12 , 4/12 , 5/12 , 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 . #We sh...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline,make_pipeline from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn...
from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.auth.views import ( password_reset, password_reset_done, password_reset_confirm...
#Find the sum of the series 2 +22 + 222 + 2222 + .. n terms n = int(input('Enter the iteration number:')) sum = 0 for i in range (1,n+1): x = int('2' * i) sum += x print(sum)
mystr = "Rehan is a good man" print(len(mystr)) print(mystr[0:5]) print(mystr[::-1]) print(mystr[11:-4]) print(mystr.isalnum()) print(mystr.endswith("man")) print(mystr.endswith("manw")) print(mystr.capitalize()) print(mystr.upper()) print(mystr.lower()) print(mystr.replace("Rehan", "Reho")) print(mystr.cou...
from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.app import App import firebase url = "https://elainejomane.firebaseio...
import re from django.db.models import Max from django.test import TestCase from django.core.urlresolvers import reverse from ..models import Mineral from ..forms import MineralSearchForm from ..templatetags.mineral_extras import GROUPS, COLOURS, ALPHABET class GlobalsTests(TestCase): def test_groups_list(self)...
#!/usr/bin/env python def generate_plane(): plane_length = [row for row in range(128)] plane_width = [column for column in range(8)] return plane_length, plane_width def split_plane(seat_values, seat_range): seat_tracker = seat_range for value in seat_values: if value == "F" or value == "L...
import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile import pyaudio import oscilators # ADSR (Attack-Destroy-Sustain-Release) Envelope # outputs a(t), amplitude as a function of time def envelope(t, start, final, rate): dur = t[t.size-1] return (final - start) * np.power(t/dur,rate) +...
from PIL import Image import os, glob image_size = 50 from_dir = "C:/Users/masho/Desktop/work/python/Python/lib/movie/20191114231101207027"#編集したい動画のパス to_dir = "C:/Users/masho/Desktop/work/python/Python/lib/movie/aaaa/"#トリミングしたい動画のパス for path in glob.glob(os.path.join(from_dir, '*.png')): img = Image....
import numpy as np from torch import optim from .history import History from .earlystopping import EarlyStopping from ...utils.progress import Progress class Trainer: def __init__(self, model, loader, optimizer = None, keep_history = None, early_stopping = EarlyStopping()): ...
# Iterable:可迭代对象 能够通过for循环来遍历里面的元素的对象 # 可以被next()函数调用并不断返回下一个值的对象称为迭代器 # 使用isinstance()方法判断一个对象是否是迭代器 from collections.abc import Iterable from collections.abc import Iterator a = {} b = (1,) c = [] def tesdt1(args): if isinstance(args, Iterable): print('是可迭代对象') else: print('不是可...
import pytest from Zimperium import Client, events_search, users_search, user_get_by_id, devices_search, device_get_by_id, \ devices_get_last_updated, app_classification_get, file_reputation, fetch_incidents, report_get from test_data.response_constants import RESPONSE_SEARCH_EVENTS, RESPONSE_SEARCH_USERS, RESPONSE...
feature_names = [ "z", "y", "x", "Sum", "Mean", "Std", "Var", "bb_vol", "bb_vol_log10", "bb_vol_depth", "bb_vol_height", "bb_vol_width", "ori_vol", "ori_vol_log10", "ori_vol_depth", "ori_vol_height", "ori_vol_width", "seg_surface_area", "seg_vo...
from datetime import date def solution(mon: int, day: int) -> str: return date(2016, mon, day).strftime("%a").upper()
# Generated by Django 2.2 on 2019-05-13 20:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0017_auto_20190429_2238'), ] operations = [ migrations.AddField( model_name='lecture', name='free', ...
class NotIterable: pass no = NotIterable() def iterate(): for i in no: print(i) def assert_not_iterable(): try: iterate() except TypeError as e: assert e.args == ("'NotIterable' object is not iterable",) else: assert False, 'Should not be iterable' assert_not_...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
__author__ = 'dustinlee' url = 'http://www.daehyunlee.com/dustinlee_new/' url = 'http://127.0.0.1/dokuwiki/' import tkinter import wiki wiki.connect(url, 'dustinlee', 'sisa0822')
from PIL import Image from torchvision import transforms import os import torch from torch.autograd import Variable from torch import nn from torchvision import models from torch import optim import matplotlib.pyplot as plt '''1.加载图像''' #定义图像加载函数 def load_img(img_path): img=Image.open(img_path).convert('RGB') ...
# Generated by Django 3.1.5 on 2021-05-20 19:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('hotel', '0003_hotel_created'), ] operations = [ migrations.RenameField( model_name='hotel', old_name='created', ...
## 문제 6. ## 소수를 크기 순으로 나열하면 2, 3, 5, 7, 11, 13, ... 과 같이 됩니다. ## 이 때 10,001번째의 소수를 구하세요.
import secrets class User(): """ Model a user as it is kept in the database. """ __slots__ = ['name', 'password', 'crypt_key'] def __init__(self, name, password, crypt_key): """ Initialize all fields. """ self.name = name self.password = password self.crypt_key = crypt_key def db_data(self):...
import os import sqlite3 import pandas as pd import psycopg2 # Create a database for local environment # conn = sqlite3.connect('flow-ez.db') # conn = sqlite3.connect('flow-ez.db', check_same_thread=False) ## Important # cursor = conn.cursor() # conn.row_factory = sqlite3.Row # Create Huroku remote DB connecti...
x=5 x=input("Enter value of x:") y=10 y=input("Enter value of y:") #create a temporary varibles and swap the values temp=x x=y y=temp print("The value of x after swapping:{}"format(x)) print("The value of y before swapping:{}"format(y))
''' OFFLINE TIMER for future use''' import atexit import datetime import os import pickle import time def save(): # save daty uplyniecia czasu with open('timersave.pkl', 'wb') as f: pickle.dump(stop, f) atexit.register(save) # print(stop) # test if os.stat("timersave.pkl").st_size != 0: # Load t...
# Generated by Django 2.0.5 on 2018-09-12 18:31 import uuid import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("barriers", ...
from django.http import response from django.test import TestCase, client from .models import Tweet from django.contrib.auth.models import User from rest_framework.test import APIClient class TweetTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(username="abc",password="password") ...
class Message(object): def __init__(self, data, conn, stream): self.data = data self.conn = conn self.stream = stream
from flask import Flask from flask import jsonify import json import sqlite3 app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/api/v1/info') def home_index(): conn = sqlite3.connect(jdbc:sqlite:identifier.sqlite) print("Open DB successfully!") api_list = [] ...
class Scene(object): """Abstract Scene""" def __init__(self, scene_manager): self.manager = scene_manager def render(self, screen): raise NotImplementedError def update(self): raise NotImplementedError def handle_events(self, e): raise NotImplementedError
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 01:09:06 2020 @author: dd394 """ import pygame pygame.init() class BUTTON: def __init__(self,position,text): self.width = 310 self.height = 65 self.left, self.top = position self.text = text def draw(self,screen): ...
"""Web application for XFormTest http://xform-test.pma2020.org http://xform-test-docs.pma2020.org """ import json from glob import glob import os import sys from flask import render_template, jsonify, request, Blueprint from werkzeug.utils import secure_filename # noinspection PyProtectedMember from .static_methods ...
import mnistDataLoader from neural_network import NeuralNetwork from config import * import torch net = NeuralNetwork() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("Using device: "+str(device)) net.to(device) criterion = net.get_criterion() optimizer = net.get_optimizer() train...
import unittest # class definition for Operation class Operation(object): def __init__(self, n1, n2): self.n1 = n1 self.n2 = n2 def add(self): return self.n1 + self.n2 def sub(self): return self.n1 - self.n2 def mul(self): return self.n1 * self.n2 ...
import numpy as np #trova la matrice inversa di A modulo 26, dato il suo determinante (che controlla essere coprimo con 26) def modular_inverse(A, detA): m = len(A) inverse = np.zeros(shape=(m, m)) detminus1 = mulinv(detA, 26) for i in range(m): for j in range(m): newA = getsubmatri...
#!/usr/bin/env python import sys from optparse import OptionParser p = OptionParser() p.add_option("-g", "--gui", dest="gui", default="Term", help="Which gui to use, Term or QT") p.add_option("-c", "--config", dest="configfile", help="Use this config file instead of the system ones.") (optio...
from django.db import models from cms.models.fields import PlaceholderField class Message(models.Model): message = PlaceholderField('message') def __str__(self): return self.message class Meta: verbose_name = 'Message' verbose_name_plural = 'Messages' class User(models.Model): ...
""" 三个图形获取面积的接口不一样,如果形状有这个属性 """ # from lib1 import Circle # from lib2 import Triangle # from lib3 import Rectangle from operator import methodcaller class Circle: def __init__(self,r): self.r = r def area(self): return self.r **2 *3.14 class Triangle: def __init__(self,a,b,c): se...
''' Bitwise Operation Operation each bit example : int 1 = 00000001 int 2 = 00000010 int 9 = 00001001 ''' a = 8 b = 5 c = a | b # Bitwise OR (|) print ('=============OR============') print (' int:',a,',binary:',format(a,'08b')) print (' int:',b,',binary:',format(b,'08b')) print ('----------...
import numpy as np from .cykmeans import cy_ikmeans, cy_ikmeans_push, algorithm_type_ikmeans def ikmeans(data, num_centers, algorithm="LLOYD", max_num_iterations=200, verbose=False): """ Integer K-means Parameters ---------- data : [N, D] `uint8` `ndarray` Data to be clustered...
#python with open("container.yaml","r") as stream : try : yaml_data = yaml_load(stream) download = yaml_data['Download'] except yaml.YAMLERROR as exc: print(exc)
from PyQt5.Qt import * from PyQt5 import QtGui from Object_IQA_Software.resource.main_iqa_ui import Ui_MainWindow #记得改!!!!!!!!!!!!!!!! # from Object_IQA_Software.Batch_NR_Pane import BatchNRPane from Object_IQA_Software.method.NR_IQA_method.NR_IQA_algorithm import * from Object_IQA_Software.method.FR_IQA_method.FR_IQ...
#! /usr/local/bin/python #-*- coding: utf-8 -*- __author__ = "Cedric Bonhomme" __version__ = "$Revision: 0.1 $" __date__ = "$Date: 2010/10/01 $" from PIL import Image def a2bits(chars): """ Convert a string to its bits representation as a string of 0's and 1's. """ return bin(reduce(lambda x, y : (x<...
# -*- coding:utf-8 -*- """ Урамшууллын хүснэгт """ from django.db import models # from django.utils import timezone from django.core.validators import MaxValueValidator, MinValueValidator from django.urls import reverse_lazy from src.core import constant as const from src.core.validate import validate_nonzero from ...
import sys previousTries = [] listOfNumbers = sys.stdin.readline().strip().split("\t") listOfNumbers = list(map(int, listOfNumbers)) controllerList = list(listOfNumbers) previousTries.append(controllerList) counter = 0 controller = True currentList = list(listOfNumbers) while controller: maxVal = -1 for i in rang...
def load_clean_descriptions(filename): train_doc = load_doc(filename) train_text = list() for line in train_doc.split('\n'): identifier = line.split('.')[0] train_text.append(identifier) train_desc = dict() for txt in train_text: if txt in descriptions: ...
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst')) as f: README = f.read() setup(name='datashare-preview', version='1.1.0', description="App to show document previews with a backend Elasticsearch", ...
import pandas as pd import tushare as ts import datetime import time from datetime import date from matplotlib.dates import drange # Set up token # only run this line for the 1st time or when needed: # ts.set_token("a2ecd994e3833787987ca0fc216ee1cfe42e895fd37634c21b0b322b") # Save files to user-specified...
# -*- coding: utf-8 -*- """ Created on 05 February, 2018 @ 10:42 PM @author: Bryant Chhun email: bchhun@gmail.com Project: BayLabs License: """ import numpy as np from scipy.interpolate import LinearNDInterpolator as plinear def scale_contour(x, y, z, space_x, space_y, space_z): ''' The spacing values mus...
# import pytest from loadmatlab_workspace import load_mat before=load_mat("before-updateseries-nopinone-unsure") s=before['s'] def comparinginput(python_in): return python_in def test_answer(): assert comparinginput(s)=s
def add_total(n): res=0 for x in range(n+1): res+=x return res def mul_total(n): global g_mul for x in range(1,n+1): g_mul*=x n=int(input()) g_mul=1 mul_total(n) print("add_total():", add_total(n)) print("gMul:", g_mul)
from .resolver import Pushrod, pushrod_view from .renderers import UnrenderedResponse from . import renderers, resolver
# 1486. 장훈이의 높은 선반 D4 # https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV2b7Yf6ABcBBASw&categoryId=AV2b7Yf6ABcBBASw&categoryType=CODE # binary subset 을 이용하는 방식보다 Stack 을 이용하는 방식이 퍼포먼스가 좋다. for TC in range(1, int(input()) + 1): n, b = map(int, input().split()) t = list(map(int, inpu...
pylab.ion() def cumprobdist(ax,data,xmax=None,plotArgs={}): if xmax is None: xmax = numpy.max(data) elif xmax < numpy.max(data): warnings.warn('value of xmax lower than maximum of data') xmax = numpy.max(data) num_points = len(data) X = numpy.concatenate(([0.0],data,data,[xmax]))...
# from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import range from builtins import object import MalmoPython import json import logging import os import random import sys import time from string import Template class UserAgent(object): ""...
#!/usr/bin/env python3 # coding=utf-8 # # Copyright (c) 2020 Huawei Device Co., Ltd. # 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...
#!/usr/bin/env python # -*- coding: utf-8 -*-import unittest import unittest import json from signature import MTSigner class TestSignature(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSign(self): fo = open("../sample.txt", "r") str = fo...
import numpy as np import pandas as pd from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.feature_extraction import DictVectorizer # 数据加载 train = pd.read_csv('./train.csv') test = pd.read_csv('./test.csv') # 使用平均年龄来填充年龄中的nan值 train['Age'].fillna(tr...
import sys f = open(sys.argv[1]) s = f.readlines() f.close() #Get the include list incLibs = [] codeLines = [] for i in s: j=i.strip() if len(j.split()) == 2 and j.split()[0]=="include": incLibs.append(j.split()[1]) continue codeLines.append(i) #Get all the library code to be attached libC...
import enum class ContainerStatus(enum.Enum): CREATED = 'created' RESTARTING = 'restarting' RUNNING = 'running' PAUSED = 'paused' EXITED = 'exited' DEAD = 'dead' @staticmethod def from_str(status): if status == 'created': return ContainerStatus.CREATED if ...
import logging from bunch import Bunch from django.http import JsonResponse from rest_framework.decorators import api_view from fof.model.model import OfflineTaskModel from fof.service import logic_processor, manager_service from fof.service import offline_score_service from util import uuid_util from util.bus_const ...
import xml.etree.ElementTree as ET import re # regex import numpy as np import pandas as pd def search(root, term): reg = re.compile(term) list = [] if reg.search(root.tag.lower()): list.append(root) for i in range(len(root)): search_list = search(root[i], term) try: ...
s = input('请输入除数:') try: result = 20 / int(s) print('20除以%s的结果是:%g' % (s, result)) except ValueError: print('值错误,必须输入数值!') except ArithmeticError: print('算术错误,不能输入0') else: print('没有出现异常')
#!/usr/bin/env python # # MagicaVoxel2MinecraftPi # from voxel_util import create_voxel, post_to_chat, ply_to_positions from magicavoxel_axis import axis from all_clear import clear from time import sleep # polygon file format exported from MagicaVoxel ply_file = 'piyo.ply' # Origin to create (Minecra...
import sqlite3 import os import pandas as pd # get file name and create a database BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_csv_file = os.path.join(BASE_DIR, 'buddymove_holidayiq.csv') db_file = os.path.join(BASE_DIR, 'buddymove_holidayiq.sqlite3') #new db def create_connection(db_file): """Create...
def power(N, P): if P == 0 or P == 1 : return N else: return (N*power(N, P-1))
# -*- coding: utf-8 -*- """ Created on Tue Apr 30 19:35:54 2019 @author: Rizwan1 """ import pandas as pd import nltk import string from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer porter = PorterStemmer() data = pd.read_csv("D:\\typed...
# -*- coding: utf-8 -*- """ Coaffect Visuals Module Core Objects: Visuals """ import datetime from .visual import Visual __all__ = ["Visual"] __title__ = 'visuals' __version__ = '0.1.0' __license__ = 'MIT' __copyright__ = 'Copyright %s Stanford Collective Emotion Team' % datetime.date.today().year
import pandas as pd import pickle import numpy as np import sys predictfile_path = sys.argv[1] predict_file = pd.read_csv(predictfile_path) predict_file_og = predict_file predict_file['Gender'].fillna(predict_file['Gender'].mode()[0], inplace=True) predict_file['Self_Employed'].fillna(predict_file['Self_Employed'].m...
import requests import json # query func def webex_api(url, headers, params): if params == {}: res = requests.get(url, headers=headers) else: res = requests.get(url, headers=headers, params=params) return res # PrettyPrinter def webex_print(res): formatted_message = """ Webex Teams...
""" GREP Plugin for Logout and Browse cache management NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log """ from owtf.plugin.helper import plugin_helper DESCRIPTION = "Searches transaction DB for Cache snooping protections" def run(PluginInfo): title = "This plugin look...
import discord from discord.ext import commands description = 'Corp Bot made by ApparenticBubbles.' bot_prefix = 'corp?' client = commands.Bot(description=description, command_prefix=bot_prefix) @client.event async def on_ready(): print('Logged in') print('Name : {}'.format(client.user.name)) print('ID : {}...
import pytest import numpy as np import audtorch as at xfail = pytest.mark.xfail @pytest.mark.parametrize('nested_list,expected_list', [ ([1, 2, 3, [4], [], [[[[[[[[[5]]]]]]]]]], [1, 2, 3, 4, 5]), ([[1, 2], 3], [1, 2, 3]), ([1, 2, 3], [1, 2, 3]), ]) def test_flatten_list(nested_list, expected_list): ...
import socket #Biblioteca responsável por habilitar os sockets de redes do computador/S.O client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Make the conection UDP/IP. ip_dominio = "192.168.0.18" #IP/DOMINIO. serverPort = 3000 #Server port. entrada = 'teste' # Input that will b...
#!/usr/bin/python import sys import re def checkScript(): """ Outputs lines which contains comma and/or quote It is here to monitor (and check) if the preprocessed file is still a well-built csv file """ with open(sys.argv[1]) as fread: while True: line = fread.readline() ...
"""sexadvices URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
# -*- coding: utf-8 -*- # # Copyright 2017 Spotify AB. # # 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 applicab...
""" http://www.geeksforgeeks.org/level-maximum-number-nodes/ Find the level in a binary tree which has maximum number of nodes. The root is at level 0. Examples: Input : 2 / \ 1 3 / \ \ 4 6 8 / 5 Output : 2 2 / \ 1 3 / \ \ ...
a=float(input("valor de a: ")) b=float(input("valor de b: ")) c=float(input("valor de c: ")) d=float(input("valor de d: ")) e=float(input("valor de e: ")) f=float(input("valor de f: ")) p1=(a/d) p2=(b/e) if (p1 != p2): x=((c*e)-(b*f))/((a*e)-(b*d)) y=((a*f)-(c*d))/((a*e)-(b*d)) print(x) print(y) else: prin...
class DatabaseConfig(object): dbhost = 'localhost' dbuser = 'root' dbpassword = 'Skipper2605' dbname = 'civil_crime_database' class Config(object): PORT = 5000 DEBUG = True threaded = True class DevelopmentConfig(object): ENV='development' DEVELOPMENT = True ...
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. consumo = float(input("Digite o consumo: ")) tipo = input("tipo de consumo: ").upper() r = consumo*(0.44) r1 = consumo*(0.65) c = consumo*(0.55) c1 = consumo*(0....
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-03-22 13:57 from __future__ import unicode_literals from django.conf import settings import django.core.files.storage from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ...
import torch import torchvision.datasets as dsets import torchvision.transforms as transforms import torch.nn.init class CNN(torch.nn.Module): def __init__(self): super(CNN, self).__init__() self.keep_prob = 0.5 self.layer1 = torch.nn.Sequential( torch.nn.Conv2d(1, 32, kerne...
from .. import utils #from .api import API import psycopg2 from PIL import Image from io import BytesIO import requests class data: @staticmethod def repr(obj): items = [] for prop, value in obj.__dict__.items(): try: item = "%s = %r" % (prop, value) ...
''' 문제) 준규가 사는 나라는 우리가 사용하는 연도와 다른 방식을 이용한다. 준규가 사는 나라에서는 수 3개를 이용해서 연도를 나타낸다. 각각의 수는 지구, 태양, 그리고 달을 나타낸다. 지구를 나타내는 수를 E, 태양을 나타내는 수를 S, 달을 나타내는 수를 M이라고 했을 때, 이 세 수는 서로 다른 범위를 가진다. (1 ≤ E ≤ 15, 1 ≤ S ≤ 28, 1 ≤ M ≤ 19) 우리가 알고있는 1년은 준규가 살고있는 나라에서는 1 1 1로 나타낼 수 있다. 1년이 지날 때마다, 세 수는 모두 1씩 증가한다. 만약, 어떤 수가 범위를 넘어가는 경우에는 1이...
import numpy as np import pandas as pd import seaborn as sns import lightgbm as lgb # Identify Categorical featurs def categorical_featurs(): categorical_featurs = ["Location_ID", "Auditorium_Type", "Language", "Business_Day", ...