text
stringlengths
38
1.54M
from flask import Flask, render_template, redirect, request, session, flash from mysqlconnection import MySQLConnector from flask.ext.bcrypt import Bcrypt import re app = Flask(__name__) app.secret_key = 'key' #change this bcrypt = Bcrypt(app) mysql = MySQLConnector(app, 'the_wall2') #regex variables to check new use...
import yaml import json from .model import Model def initialize_db(db_file_name, yaml_file_name): with open(yaml_file_name) as file: data = yaml.load(file) models = {model: Model(fields).dict() for model, fields in data.items()} json.dump({ 'models': models, 'tables': {model: ...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def updatefig(i): im.set_array(Termo[i]) return im, def alfa_x_go(): for i in range(X_full - 1): alfa_x[i + 1] = Ax / (Bx - Cx * alfa_x[i]) def alfa_y_go(): for i in range(Y_full - 1): alfa_y[...
from django.db import models from menu.models import Meal as MenuMeal from menu.models import Drink as MenuDrink from menu.models import Side as MenuSide from menu.models import Topping as MenuTopping from django.core.exceptions import ValidationError from django.core.validators import RegexValidator # Ticket: contai...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='PhotoFUSE', version='1.0', description="PhotoFUSE: Show photos based on ratings and tags", author='Tim Freund', author_email='tim@freunds.net', license = 'MIT License', url='http://github.com/timfreund/photofu...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMarketingActivityOrdervoucherSendModel(object): def __init__(self): self._activity_id = None self._biz_dt = None self._ch_info = None self._merchant_order_ur...
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class Bdd100kDataset(CustomDataset): """Pascal VOC dataset. Args: split (str): Split txt file for Pascal VOC. """ CLASSES = ('road', 'sidewalk', 'building', 'wall', 'fence', 'po...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 3 14:46:51 2020 @author: billcoleman Extract all the .wav files from the IEMOCAP database and prepare them for training with the CNN Isolate each file Convert to LPMS (better representation for audio deep learning) Remove silence Chop into 0.4 se...
import tensorflow as tf import tensorflow_datasets as tfds import numpy as np from PIL import Image, ImageDraw import PIL import sys import os outPath = sys.argv[1] print("Will export the training DS to {0}".format(outPath)) if not os.path.exists(outPath): os.mkdir(outPath) idx = 0 for ex in tfds.load('stanford_d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: Olivier Noguès import re import os import time import json import sys import inspect import importlib import logging import ares.doc DSC = { 'eng': ''' :category: Markdown :rubric: PY :type: Base class :dsc: ## Markdown Framework Thi...
"""Various intepolation schemes for PyTorch""" import os import sys import time import numpy as np import torch from matplotlib import pyplot as plt from skimage.io import imread from core import Interpolator from kernels import BilinearKernel, GaussianKernel dtype = torch.FloatTensor dtype_long = torch.LongTensor ...
import unittest import brulib.clone import os import shutil temp_root = './temp_clone' class LibraryTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.tearDownClass() @classmethod def tearDownClass(cls): if os.path.exists(temp_root): shutil.rmtree(temp_roo...
"""Main module.""" from typing import List, Tuple from collections import deque from datetime import datetime, date from dataclasses import dataclass from random import randint, randrange class Pesel: SEX = {'male', 'female'} ODD_MONTHS = (1, 3, 5, 7, 8, 10, 12, 21, 23, 25, 27, 28, 30, 32) EVEN_MONTHS = (...
import math ''' This function takes 3 numbers and calculates if they where the a, b and c values of a 2d equation what would the results be ''' def equation2D(a,b,c): delta = b**2 - (4*a*c) if(delta < 0): return "There is no answeres for it" elif(delta == 0): return "There is one re...
#!/usr/bin/python # -*- coding: utf-8 -*- LITTER = 1 FEMALE = 2 MALE = 3 adv_dog_type_litter = { LITTER: {"name_edit" : u"Щенков", "name_view" : u"щенков"} } adv_dog_type_female = { FEMALE : {"name_edit" : u"Девочку / суку", "name_view" : u"девочку"} } adv_dog_type_male = { MALE : {"name_edit" : ...
# -*- coding: utf-8 -*- """ Created on Sat Apr 4 09:27:12 2020 @author: Philippine """ import script_get_data as data import pandas as pd import numpy as np #Nettoyage aéroport liste_indice=[7031,7032,7137,7138,7158,7160,7161,7164,7165,7184,7191,7221,7233,7236,7237,7238,7249,7250,7251,7252,7253, 7254...
# Create your models here. from django.db import models # HR Models class Department(models.Model): name = models.CharField(max_length=30) location = models.CharField(max_length=30) def __str__(self): return self.name class Meta: db_table = 'Departments' class Employee(models.Mod...
import numpy as np def l1_distance(t1, t2): assert t1.shape[0] == t2.shape[0] return np.sum(np.absolute(t1 - t2))
import os import datetime import time import re import pandas as pd import numpy as np import requests class CryptoCompareAPI(): def __init__(self): self.url = 'https://min-api.cryptocompare.com/data' def _safeRequest(self, url): while True: try: response = reque...
from random import randint dogs=0 watches=0 concert_tickets=0 candies=0 yachts=0 for i in range(0,100000): years = randint(0,5) months = randint(0,11) days = randint(0,30) relationship_length = [years, months, days] if relationship_length[0] >= 4: dogs += 1 elif relationship_length[0]>=1: watches += 1 el...
import os import json import boto3 from datetime import datetime from flask.json import JSONEncoder def send_message(name, body, delaySec=0): session = boto3.session.Session() client = session.client(service_name="sqs", endpoint_url="http://localhost:4576") queueUrl = client.get_queue_url(QueueName=name)[...
from get_data_robust import get_dataloader from unimodals.common_models import LSTM from fusions.common_fusions import Stack from torch import nn import torch.nn.functional as F import torch import pmdarima import numpy as np import argparse import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.getcwd...
def uglynumbers(n): arr = [0]*n arr[0] = 1 idx_2,idx_3,idx_5=0,0,0 next_of_2 = 2 next_of_3 = 3 next_of_5 = 5 for i in range(1,n): arr[i]= min(next_of_2,next_of_3,next_of_5) if arr[i] == next_of_2: idx_2 += 1 next_of_2 = 2 * arr[idx_2] if arr[i]...
#!/usr/bin/env python3 from mcpi.minecraft import Minecraft from mcpi import block # Connect to Minecraft mc = Minecraft.create() # Determine the Player's current position. x,y,z = mc.player.getTilePos() # Number of rooms... xrooms = 1 # Change this constant to adjust the number of rooms in the x-axis (left-right)...
import asyncio from aiohttp import web from . import db, smtpd, static, ws, views def configure(app, *, size, smtp_hostport, loop): app['db'] = db.DB(size=size) smtpd.configure(app, hostport=smtp_hostport, loop=loop) static.configure(app, loop) app.router.a...
# coding: utf-8 import os import sys import traceback import socket from socketserver import ThreadingMixIn from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer current_dir = os.path.dirname(os.path.abspath(__file__)) homedir = os.path.join(current_dir, '../') sys.path.insert(0, os.path.join(...
__author__ = 'hyeonsj' inputRDD = sc.textFile("log1.log") errorsRDD = inputRDD.filter(lambda x: "error" in x) warningsRDD = inputRDD.filter(lambda x: "warning" in x) badLinesRDD = errorsRDD.union(warningsRDD) badLinesRDD.count()
import json import io import time import os import pytest from unittest import mock from unittest.mock import patch import dateparser from CommonServerPython import DemistoException from CofenseTriagev3 import MESSAGES from test_data import input_data BASE_URL = "https://triage.example.com" API_TOKEN = "dummy_token" ...
# Game-manipulating functions. (Games are just dicts so they can be easily # passed around and serialized and such.) from collections import defaultdict from random import choice, shuffle hotel_names = 'sackson zeta america fusion hydra quantum phoenix'.split() class GameError(Exception): """Superclass for al...
from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.utils.timezone import now # Create your models here. class Myblogpost(models.Model): id=models.AutoField(primary_key=True) blog_title=models.CharField(max_length=30) blog_descr...
# Get Data from Google Sheets # Standard Libary import pdb import sys # 3rd Party import gspread from oauth2client.service_account import ServiceAccountCredentials from sql import Table, Field, SQLConnect scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_nam...
from django.contrib.auth.models import User from django.db.models import Q from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from .models import LobbyType, Lobby, LobbyUser, LobbyQuestions, Category, QuestionType, Question, Answer from rest_framework import seriali...
import matplotlib.pyplot as plt import pandas as pd import sys import os from functions import importMappedData, trackMeta, mbzMeta, getUsers from collections import OrderedDict, Counter from operator import itemgetter user = sys.argv[1] data = importMappedData() userData = getUsers() userInfo = userData[userData["u...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tests to manage schedules """ import pytest from nodeping_api import schedules try: import parameters except ModuleNotFoundError: from . import parameters TOKEN = parameters.TOKEN CUSTOMERID = parameters.CUSTOMERID SCHEDULE_NAME = "PYTEST_test_schedule" d...
from parametros import * import requests import json import sys from pprint import pprint try: from thehive4py.api import TheHiveApi except ImportError: sys.exit(1) def set_case_resolved(alert_id): api = TheHiveApi(hiveURL, apiKey, None, {'http': '', 'https': ''}) case_promote_alert = api.promote_a...
import abc from typing import List from .session import SessionType, ServerInfo, Session class Plugin(metaclass=abc.ABCMeta): '''所有插件应该实现该接口,插件指的是实现了Plugin的类 插件类的类属性表示插件的属性,派生类需覆盖这些属性来配置当前插件 ''' name = 'plugin' # 插件名称 author = 'r00tnb' # 插件作者 plugin_id = '' # 该字段会在插件加载时自动填充 supported_sess...
#craps-game.py """ Simulating the dice game craps """ import random #initialize a gamestatus variable game_status = None def roll_dice(): """ Roll 2 dice and return their value as tuple""" die_1 = random.randrange(1,7) die_2 = random.randrange(1,7) return (die_1,die_2) def display_dice(dice): """D...
# for splat from __future__ import print_function # for reg match import re class SearchEngine: def __init__(self): pass #get the numbers needed def get_total_lines(self): first_line = input() n_and_q = list( map(int, first_line.strip().split()) ) n = n_and_q[0] ...
def main(): #escribe tu código abajo de esta línea def calc_cuenta(saldo,ing,eg,che): tot_che = che * 13 tot = (saldo + ing - eg -tot_che) inte = tot * 0.075 tot_m_int = tot - inte return tot_m_int sal = float(input("Saldo anterior: ")) ing = float(input("Ingresos: ")) ...
from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router(admin.router) @app...
from inference.inference_general_utils import * from inference.inference_plot_neuralnets import * import time import numpy as np import pandas as pd class VideoAnalyzer: """ Implements a frame capturar from the webcam """ def __init__(self, cap, age_net, ...
from numpy import zeros,linspace,array,dot from Legendre import Legendre from Integration import Integration from Base import Base class GD: #Galerkin discontinu def __init__(self,ordre,a,b,N): #param self.ordre = ordre self.a = a self.b = b self.N = N #...
#!/usr/bin/env python # coding=utf-8 import os import sys os.chdir('/usr/local/bluedon') if '/usr/local/bluedon' not in sys.path: sys.path.append('/usr/local/bluedon') import sqlite3 import time import json import sys import shelve from collections import defaultdict import commands from operator import itemgetter...
# Generated by Django 3.1.5 on 2021-01-12 14:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('artists', '0002_actorrole'), ('plays', '0002_auto_20210112_1555'), ] operations = [ migrations.AlterField( model_name='v...
import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__main__': # 灭一个pyqt5程序必须创建一个应用程序对象 sys.argv 是一个参数列表 app = QApplication(sys.argv) # QWidget部件是pyqt5所有用户界面对象的基类 w = QWidget() # 设置窗口大小 w.resize(250, 150) # 移动窗口位置到屏幕的就位置 w.move(50, 50) # 设置窗口的标题 w.setWin...
high_income = False good_credit = True student = False if high_income and good_credit: print("Eligible") else: print("Not Eligible") if not student: print("Eligible") else: print("Not Eligible") if (high_income or good_credit) and not student: print("Eligible") else: print("Not Eligible")...
class Solution: def removeOuterParentheses(self, S: str) -> str: stack = [] result = [] for each in S: if each == "(": if len(stack) > 0: result.append(each) stack.append(each) else: ...
from pathlib import Path from typing import Callable, Optional from paramiko import SSHException from scp import SCPException import consts from assisted_test_infra.test_infra.controllers.node_controllers import ssh from assisted_test_infra.test_infra.controllers.node_controllers.disk import Disk from service_client ...
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'classes', 'type': 'static_library', 'sources': [ 'MyClass.h', 'MyClass.m', ], ...
import argparse import os import json import pickle as pkl from utils import save_error from loading import save_results import numpy as np import time def check_round(val): try: return str(np.round(float(val), 5)) except ValueError: return str(val) def get_table_html(results): n_repeat...
# 11. Дано символьний файл, який містить принаймні один символ пробілу. # Видалити всі його елементи, розташовані після останнього символу пробілу, включаючи і цей пробіл. f = open('files/3.txt') str1 = f.read() str2 = "" for i in range(0, len(str1)): if str1[i] == ' ': str2 = str1[:i] f = open('files/3.tx...
#! /opt/local/bin/python2.7 # # Create people for a list of IDs in a text file, add content for each person # from text files, and get back LIWC profile. # # Modified from the sample code from Receptiviti (author: Abdul Gani). # Author: Jacqueline Kory Westlund, May 2017 # TODO: Some file paths, file names, and directo...
import discord from discord import utils import time import config import os class MyClient(discord.Client): async def on_ready(self): print('Властилин, {0} готова к работе!'.format(self.user)) async def on_message(self, message): print('[log] Сообщение от {0.author}: {0.content}'.f...
"""empty message Revision ID: f7a69be715b3 Revises: 5ce00ca1cea8 Create Date: 2016-02-10 19:46:11.975174 """ # revision identifiers, used by Alembic. revision = 'f7a69be715b3' down_revision = '5ce00ca1cea8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
from Proj4 import * import unittest class TestMovie(unittest.TestCase): def test_basic_search(self): results = get_results_for_movie("love") movie_objects,list_of_movie, list_of_ids = results self.assertEqual(len(results), 3) self.assertEqual(len(list_of_movie), 120) self.as...
numStars = int(input()) print("{}:".format(numStars)) for i in range(2,numStars): if numStars % (i-.5) == 0 or (numStars+i-1) % (i-.5) == 0: print("{},{}".format(i, i-1)) if numStars % i == 0: print("{},{}".format(i, i))
from hellosign_sdk.tests.functional_tests import BaseTestCase from hellosign_sdk.resource import Team from hellosign_sdk.utils import NotFound, HSException, BadRequest from time import time class TestTeam(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) try: self.client.get_tea...
import hoi4 import os import hoi4 import pyradox techs = hoi4.load.get_technologies() # child tech -> [parent_tech, ...] techs_or_dependencies = {} for tech_key, tech in techs.items(): if isinstance(tech, pyradox.Tree): for path in tech.find_all('path'): child_tech_key = path['leads_to_tech'...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: ritesh # @Date: 2015-11-24 19:52:16 # @Last Modified by: ritesh # @Last Modified time: 2015-11-29 20:25:25 import matplotlib.pyplot as plt from textblob import TextBlob import numpy as np import csv import pandas import cPickle from sklearn.feature_extract...
import mysql.connector #host, database, username , password conn = mysql.connector.connect(host = 'localhost',database = 'PythonAutomation', user = 'root', password = 'root') print(conn.is_connected())
# -*- coding: utf-8 -*- """ Module: cl_trial1.py Created on Sat Oct 26 17:09:11 2013 @author: gav Description: Smoke test for opencl routines """ ### Imports from __future__ import print_function import time ### Logging import logging logging.basicConfig(level=logging.DEBUG) debug, info, error = logging.debug, loggin...
import multiprocessing import signal import os import socket import json import sqlite3 from time import sleep, gmtime, strftime from http.server import BaseHTTPRequestHandler,HTTPServer dbpath = os.environ['dbpath'] hostname = os.environ['HOSTNAME'] interval = int(os.environ['interval']) class HttpProcessor(BaseHTTP...
import ast import sqlite3 import os import stat import threading import psycopg2 import psycopg2.extras from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from pymongo import Connection from oms_pds.pds.models import Profile from oms_pds.accesscontrol.models import Settings from oms_pds.accesscontrol.internal i...
#大型数组运算 import numpy as np ax=np.array([1,2,3,4]) ay=np.array([5,6,7,8]) print(ax*2) print(ax+10) print(ax+ay) print(ax*ay) #该模块还提供通用函数 print(np.sqrt(ax)) print(np.cos(ax)) #构造超大数组 grid=np.zeros(shape=(10000,10000),dtype=int) print(grid) #同样所有操作都会作用到每个元素 print(grid+10) #numpy扩展了列表的索引功能 a=np.array([[1, 2, 3, 4], [5, ...
import argparse import base64 import numpy as np import socketio import eventlet.wsgi from PIL import Image from flask import Flask, render_template from io import BytesIO from model import preprocess from keras.models import model_from_json sio = socketio.Server() app = Flask(__name__) model = None ...
''' 5. Tendo como dados de entrada a altura e o sexo de uma pessoa, faça um programa que calcule seu peso ideal, utilizando as seguintes fórmulas: a. Para homens: (72.7*altura) - 58 b. Para mulheres: (62.1*altura) - 44.7''' altura = float(input('Digite sua altura: ')) sexo = input('Digite seu sexo - F ou M: ') fem = ...
import argparse import os import pickle as pk import keras import numpy as np from keras import optimizers from keras.callbacks import CSVLogger, ModelCheckpoint from keras.layers import (ELU, GRU, LSTM, BatchNormalization, Bidirectional, Conv2D, Dense, Dropout, Flatten, Input, MaxPooling2D, ...
from core import block class chain(object): def __init__(self): self.data = [] def get_simple(self): blocks = [] for block in self.data: blocks.append(block.get()) return blocks def get_block(self, hash): block = [block for block in self.data if block.hash == hash] return block...
import json import math from fixtures.get_all_tles import set_all_tles from datetime import datetime, timedelta, timezone from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from satellite.satellite import Satellite from satellite.satellite_wrapper import SatelliteWrapper from ...
from django.urls import include, path from . import views urlpatterns = [ path('coords/', views.CoordListView.as_view(), name='coords'), path('coords/new/', views.CoordCreateView.as_view(), name='new_coord'), path('coords/<int:pk>/', views.CoordDetailView.as_view(), name='single_coord'), path('coords...
#------------------------------------------------------- # Taking number from user and check if it is Even or Odd #------------------------------------------------------- Number = int(input("Enter a value: ")) print("-----------------------------") Value = Number % 2 if Value == 0: print(Number, "is an even value"...
# Resource object code (Python 3) # Created by: object code # Created by: The Resource Compiler for Qt version 5.15.2 # WARNING! All changes made in this file will be lost! from PySide2 import QtCore qt_resource_data = b"\ \x00\x00\x0d\xd5\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x00\xc8\x00\x00\x00\x...
print("Введіть суму") a = int(input()) a1 = a * 0.14 b1 = (a+a1) a2 = (a+a1) * 0.14 b2 = (b1+a2) a3 = (a+a2) * 0.14 b3 = (b2+a3) print("Рік 1 - {:.2f}".format(b1)) print("Рік 2 - {:.2f}".format(b2)) print("Рік 3 - {:.2f}".format(b3))
import os import PIL from PIL import Image import simplejson import traceback import numpy from flask import Flask, request, render_template, redirect, url_for, send_from_directory, make_response from flask_bootstrap import Bootstrap from werkzeug.utils import secure_filename import multiprocessing lock = multiprocess...
import sys sys.stdin = open("문제1_input.txt") T = int(input()) move_x = [1,1,-1,-1] # 1시 / 5시 / 7시 / 11시 move_y = [-1,1,1,-1] def func(y, x, power) : cnt= 0 for tmp_power in range(0, power+1) : #크기 for i in range(4) : # 방향 tmp_x = x + tmp_power * move_x[i] tmp_y = y + tmp_power ...
import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import PySimpleGUI as sg import matplotlib import matplotlib.pyplot as plt matplotlib.use("TkAgg") def draw_figure(canvas, figure): figure_canvas_agg = FigureCanvasTkAgg(figure, canvas) figure_canvas_agg.draw() figure_canv...
#!/usr/bin/env python """\ Ex3 configure an input file with a json Usage: ex3 TODO ex2 (-h|--help) """ if __name__ == '__main__':
from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split #from wordcloud import WordCloud from math import log, sqrt import pandas as pd import numpy as np ...
""" Write a method element_replace that takes in an array and a dictionary. The method should return a new array where elements of the original array are replaced with their corresponding values in the dictionary. """ def element_replace(arr, hash_in): list1 = [] for i in range(len(arr)): if arr[i] in h...
import sys from agents.agent_setup import AgentConfig import agents.misc.config_evaluator as config # (optional) read path to config-file from opts # can be set manually as well path_config_file = config.get_path_to_config(sys.argv[1:]) # setup agent configuration agent_setup = AgentConfig(path_config_file) # creat...
#!/usr/bin/env python from ptpy import PTPy # TODO Fix import once ptpy module is better structured. camera = PTPy() with camera.session(): print('Initiating open capture') capture = camera.initiate_open_capture() print(capture) try: while True: evt = camera.event() if e...
import ctypes; from .iCharacterBaseType import iCharacterBaseType; cCharacterA = iCharacterBaseType.fcCreateClass( "iCharacterBaseTypeA", ctypes.c_ubyte, ); cCharacterW = iCharacterBaseType.fcCreateClass( "iCharacterBaseTypeW", ctypes.c_ushort, s0UnicodeEncoding = "UTF-16LE", );
from django import forms class CalculadoraForm(forms.Form): fecha = forms.DateField(widget=forms.DateInput) monto = forms.IntegerField(widget=forms.NumberInput) plazo = forms.IntegerField(widget=forms.NumberInput) is_reajustable = forms.BooleanField(widget=forms.CheckboxInput , required=False , initial...
import uuid from django.db import models from django.utils import timezone class Ticket(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) autor = models.ForeignKey('auth.User') ########tecnico = models.ForeignKey('tec.User', blank=True, null=True) #titulo = models.CharField...
# Create your views here. from django.db.models import Q from django.shortcuts import render_to_response from models import Book from forms import ContactForm from django.core.mail import send_mail def search(request): query = request.GET.get('req','') if query: qset = ( Q(title__icontains...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2018/8/2 14:52 # @Author : @乌鸦坐飞机 # Description : pandas import matplotlib.pyplot as PLT import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor # 回归决策树 一个demo 例子 #...
from tkinter import * from tkinter import messagebox from MYSQL1.Msql import Mysql from MYSQL1.Redis import myRedis class Login: def __init__(self): self.m=True self.ms = Mysql() self.mr=myRedis() self.index=0 #初始化答案列表 self.answer=[] #从redis获取答案与题目 s...
from django.conf.urls import include, url from django.contrib import admin from golfapp import views from django.contrib.auth import views as auth_views from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm from django.core.urlresolvers import reverse_lazy urlpatterns ...
from distutils.core import setup setup(name='albumsync', version='0.1', py_modules=['albumsync'], scripts=['albumsync.py'] )
from flask import jsonify, request, redirect, url_for, make_response, render_template from app import app, bcrypt, jwt from db import mysql from flask_jwt_extended import (create_access_token) import hashlib @app.route('/api/signup', methods=['POST']) def signup(): data = request.get_json()['user'] email = data['ema...
# from django.http import HttpResponse # # # def hello(request): # return HttpResponse("Hello world ! ") from django.http import HttpResponse from django.shortcuts import render from models.predict_Minute_v2 import get_data from models.common_tool import get_modelName_dict import models.django_config import json t...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url urlpatterns = patterns('', # Examples: # url(r'^$', 'povary.views.home', name='home'), # url(r'^povary/', include('povary.foo.urls')), url(r'^recipe_gallery/(?P<recipe_slug>.*)/$', 'gallery.views.recipe_gallery_upload', name='recipe_...
''' case 6 - Moskow Subway developers: Aldaeva.A 33%, Litvinov.K 33%, Shulgin.N 33% ''' from tkinter import * from random import * from math import * class Metro(object): def __init__(self, x1, y1, x2, y2, color, _width, outline): self.x1 = x1 self.y1 = y1 self.x2 = x2 ...
#Vedanth M n = int(input("enter the size:")) sum = 0 for i in range(1,n+1): i = i * i sum = sum + i print(sum)
import pytest import numpy as np from aizynthfinder.context.scoring import ( StateScorer, NumberOfReactionsScorer, AverageTemplateOccurenceScorer, NumberOfPrecursorsScorer, NumberOfPrecursorsInStockScorer, PriceSumScorer, RouteCostScorer, ScorerCollection, ScorerException, ) from ai...
#time series forecasting using ARIMA model - for the problem staement 'Predict Future Sales' https://www.kaggle.com/c/competitive-data-science-predict-future-sales #https://www.kaggle.com/jagangupta/time-series-basics-exploring-traditional-ts #changing the directory and getting the list in a directory import os ...
import os import torch import torch.nn as nn from datetime import datetime from .logger import Logger import pdb class _BaseModel: def __init__(self): pass def initialize(self, opt): self.opt = opt self.isTrain = opt.isTrain self.save_dir = os.path.join(opt.checkpoints_dir, op...
from .config import t,tran_classification import numpy as np import pandas as pd import datetime import time from .util import ROR,Tag,Configuration_Options from dateutil.relativedelta import relativedelta from calendar import monthrange class CalcBasic(object): def __init__(self,**kwargs): self._parse(*...
# Month percentile import sys, os, random sys.path.append("../lib/") import iemplot import network nt = network.Table("IACLIMATE") import mx.DateTime now = mx.DateTime.now() import pg coop = pg.connect('coop','iemdb',user='nobody') # Extract normals lats = [] lons = [] vals = [] rs = coop.query("""SELECT station, a...
import torch from torch.utils.tensorboard.writer import SummaryWriter from torchvision.utils import make_grid TENSORBOARD_LOG_DIR = "tensorboard_logs" class Tensorboard(): """ A wrapper around Tensorboard. """ def __init__(self, log_dir=TENSORBOARD_LOG_DIR): self.writer = SummaryWriter( ...