text
stringlengths
38
1.54M
# A ViT designed from what I heard # 92% accuracy on CIFAR10 using only CIFAR10 training data, # python3 -m playground.vit.train_cifar10_my --data-dir ./tmp/vit --model-dir ./tmp/vit from torchvision.datasets import CIFAR10 from torchvision import transforms as T from torchvision.transforms import functional as TF impo...
import os from everett.manager import ConfigManager, ConfigOSEnv, ListOf import dj_database_url config = ConfigManager([ # Pull configuration from the OS--no ini files. ConfigOSEnv(), ]) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.p...
import datetime from http import HTTPStatus from django.test import TestCase from django.urls import reverse from accounts.models import User from category.models import Category from menu.models import Menu from restaurant.models import Restaurant from yosigy.models import YosigyMenu, Yosigy class YosigyDetailList...
nome = input("Qual é o seu nome? ") num_filhos = int(input("Qual é o número de filhos que você deseja ter? ")) cidade = input("Em qual cidade você gostaria de morar? ") profissao = input("Qual é a profissão dos seus sonhos? ") print(f"{nome} terá {num_filhos} filhos e viverá em {cidade} trabalhando como {profissao} em...
import unittest from unittest.mock import patch from falcon import testing from dingolib.rest.app import application class FalconTestCase(testing.TestCase): def setUp(self): super(FalconTestCase, self).setUp() self.app = application class TestApp(FalconTestCase): """ Tests for app.py wsgi ap...
#!/usr/bin/env python import sys import numpy as np import fileinput if __name__ == "__main__": sifts = \ [ np.array( map(float, # Each line needs to be stripped, and cleaned up a bit line.strip().replace(' \n',' ').replace('\n',' ').split(' '))) for line in sys.stdin.read...
import os import sys import time import tempfile from collections import OrderedDict import numpy os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = "true" # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '4' from src.utils.core.trainercore import trainercore import datetime import tensorfl...
import os from dotenv import load_dotenv load_dotenv() DB_USER = os.environ["DB_USER"] DB_PASS = os.environ["DB_PASS"] DB_HOST = os.environ["DB_HOST"] DB_PORT = os.environ["DB_PORT"] DB_NAME = os.environ["DB_NAME"] DB_SOCKET_DIR = os.environ.get("DB_SOCKET_DIR", "/cloudsql") CLOUD_SQL_CONNECTION_NAME = os.environ["CL...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import wx import os import abcxrc import wx.xrc as xrc import modules.group as group import modules.log4py as log4py import string import codecs import tools.encdet as encdet log = log4py.log4py('[abclfrm]') class abclfrm(abcxrc.xrcmframe): def __init__(self,parent):...
#<ImportSpecificModules> from ShareYourSystem.Standards.Classors.Representer import _print from ShareYourSystem.Standards.Objects import Commander #</ImportSpecificModules> #Print a version of the class _print(dict(Commander.CommanderClass.__dict__.items())) #Print a version of this object _print(Commander.CommanderC...
import torch.multiprocessing as mp #actor critic version of tictactoe from actorcriticutils import ActorCritic,worker if __name__ == '__main__': Masta = ActorCritic(9,30,29,26,9,1) Masta.share_memory() processes=[] params={'epochs':2000,'workers':2} counter=mp.Value('i',0) for i in range(param...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import os import decimal decimal.getcontext().prec = 3 const1 = 1.013 const2 = 1.02 path = 'D:\Data\liuyangshuju' files = os.listdir(path) save_dir = 'D:\Data\AfterProcess' #print files N = len(files) for i in range(N): new_path ...
""" Author: Leigh Stauffer Project 3-1 File: game.py This program plays a guessing game with the user. The program thinks of a number between 1 and 100. The user inputs guesses until a guess equals the number. The program then displays the total number of guesses. However, if the user is unable to correctly guess t...
import unittest class Task01Test(unittest.TestCase): def test_first_cycle(self): banks = [0, 2, 7, 0] redistribute(banks) self.assertEqual([2, 4, 1, 2], banks) def test_second_cycle(self): banks = [2, 4, 1, 2] redistribute(banks) self.assertEqual([3, 1, 2, 3],...
from django.shortcuts import render_to_response from django.http import HttpResponse from blog.models import posts # Create your views here. def home(request): return render_to_response('blog.html', {'posts':posts.objects.all()})
""" Implementation of SFM to investigate oscillations. """ #------------------------------------------------------------- # from numpy import * from numpy import * import numpy as np import logging import time import matplotlib.pyplot as plt from sys import * #----------------------- Parameter ----------------------...
# 프로필 import numpy as np import pandas as pd from pandas import Series, DataFrame from numpy import nan as NA import matplotlib.pyplot as plt import re import mglearn import os os.chdir("./pjt_data") # 데이터 가져오기 train = pd.read_csv("train.csv") train.head() train.info() # 깊은 복사 apart = train[:] # 컬럼명 수정 apart.column...
import torch import torch.nn as nn import torch.nn.functional as F from .networks_other import init_weights def passthrough(x, **kwargs): return x class InputTransition(nn.Module): """ modified compared to original vnet res connection added differently """ def __init__(self, outChans): ...
# def는 정의 def create(): print('db데이터 insert 처리') def read(): print('db데이터 insert 처리') def update(): print('db데이터 insert 처리') def delete(): print('db데이터 insert 처리')
from dataclasses import dataclass, field from enum import Enum from typing import List, Optional from xsdata.models.datatype import XmlDate, XmlTime from btlx.x3d_3_3 import X3DshapeNode __NAMESPACE__ = "http://www.design2machine.com" class AlignmentHorizontalType(Enum): """ Alignment of a text (left, center...
# -*- coding: utf-8 -*- """ """ # Importing Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from s...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2018-08-04 07:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('post', '0004_auto_20180802_0018'), ] operations = [ migrations.AlterField( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This function is used to generate a batch shell script for filtering miRAW prediction result files. Those files needs to be either in the original folder of miRAW predition or in a single folder This code is used in the follwoing format python filepath1/cutoffBat...
#!/usr/bin/env python3 x = int(input()) t = 1 while 1: if x <= t*-~t//2: print(t) exit() t += 1
from models.task import Task import copy class Repository: """ Class contains the working data for the application. Structured as a list of states, where each state is a list of tasks. """ def __init__(self, silent=False, empty=False): """ A repository adds tasks from the data.i...
from __future__ import division, absolute_import import numpy as np import tflearn from tflearn.layers.core import input_data, dropout, fully_connected, flatten from tflearn.layers.conv import conv_2d, max_pool_2d, avg_pool_2d from tflearn.layers.merge_ops import merge from tflearn.layers.normalization import local_res...
import Algorithm as alg import numpy as np repetions = 50 final_noise = 1.0 starting_noise = 0.0 dataset = "circles+" linksFile = "dati/" + dataset +"/links_data.npy" minFile = "dati/" + dataset + "/min_data.npy" lenFile = "dati/" + dataset + "/len_data.npy" best_links = np.zeros(repetions) min_layers = np.zeros(re...
from itertools import chain import numpy as np from tqdm import tnrange from cvtk.utils import view_along_axis from cvtk.cov import stack_temporal_covariances, temporal_replicate_cov def bootstrap_ci(estimate, straps, alpha=0.05, method='pivot', axis=0, stack=True): """ Return pivot CIs This confidence ...
import django_tables as tables from models import Hosts class HostTable(tables.ModelTable): id = tables.Column(sortable=False, visible=False) hostname = tables.Column(data = "hostname") static_ip = tables.Column(data = "static_ip") dhcp_ip = tables.Column(data = "dhcp_ip") status = tables.Column(da...
import os import json import sys import numpy as np import glob from PIL import Image import json sys.path.insert(0, "..") from otn_modules.utils import get_mask_bbox, cross2otb def gen_config(seq_name, label_id): # generate config from a sequence name seq_home = '../DAVIS/trainval' save_home = '../result...
import unittest from main import intersection class TestMain(unittest.TestCase): def test_intersection(self): print(intersection(1, 2, 3, -4, 1, -6)) if __name__ == '__main__': unittest.main()
# Написать свой cache декоратор c максимальным размером кеша и его очисткой при необходимости. # Декоратор должен перехватывать аргументы оборачиваемой функции # Декоратор должен иметь хранилище, где будут сохраняться все перехваченные аргументы и результаты выполнения декорируемой функции # Декоратор должен проверять ...
#!/usr/bin/env python # -*- coding: utf8 -*- """ Usage: exdate.py FLOAT... Options: """ import datetime from docopt import docopt import xlrd __author__ = 'peter' def main(): args = docopt(__doc__) for f in args['FLOAT']: print('{0}:\t{1}'.format(f, datetime.datetime(*xlrd.xldate_as_tuple(float(f),...
import cv2 import numpy as np # These 4 are too slow # BIG anime eyes def apBigErode(frame): return cv2.erode(frame, kernBigEllipse) # Makes thin things disappear def apOpen(frame): return cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernBigEllipse) # Very funky looking - blackens and makes...
distancia = float(input('Qual a distância percorrida em km: ')) dias = float(input('Qual a quantidade de dias que o carro foi alugado: ')) valordias = 60.00 * dias valordistancia = 0.15 * distancia total = valordias + valordistancia print(f'R${total:.2f}')
import sys line = sys.stdin.readline() print('import sys\n\n', end='') print('l = [', end='') while line: line = line.split(' ') print((int(line[1]) % 100000007), end=', ') line = sys.stdin.readline() print('}') print('line = sys.stdin.readline()') print('while line:') print('\tprint(l[int(...
from exts import db from datetime import datetime class Article_type(db.Model): id = db.Column(db.Integer, autoincrement=True, primary_key=True) type_name = db.Column(db.String(20), nullable=False) # relationship articles = db.relationship('Article', backref='article_type') class Article(db.Model): ...
from datetime import datetime from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBad...
import cv2 import numpy as np import pyrealsense2 as rs from socialresearchcv.processing import Utils from socialresearchcv.processing.CONFIG import CONFIG from scipy.spatial import ConvexHull class PoseViewer: def __init__(self, intrinsics): self.depth_intrinsics = intrinsics def get_point(self, x,...
import onmt import torch import torch.nn as nn from onmt.modules.sparse_losses import SparsemaxLoss from onmt.utils.loss import LabelSmoothingLoss, LossComputeBase, shards def build_loss_compute(model, tgt_field, opt, train=True): """ Returns a LossCompute subclass which wraps around an nn.Module subclass ...
# format # day hour minute second cmd # # time format # * or */2 or 2 # * - run direct # */2 - run at every 2 (days, hours, minutes, seconds) # 2 - run at 2 (day, hour, minute, second) # # sample: * * * */5 gedit, means run gedit every 5 seconds # * * * 5 gedit, means run gedit at 5 second in every min...
from flask import Flask, abort, request import json app = Flask(__name__) data_ph = [ { "id" : 1, "ph" : "8", } ] @app.route('/ph', methods=['GET']) def index(): str_ph = json.dumps(data_ph) return(str_ph) @app.route('/ph/<int:id>', methods=['GET']) def get_ph(id): ph = None ...
# 用户输入一个字符串和一个子串,打印出给定子串在目标字符串中出现的次数 # 如,ABCDCDC和CDC,输出结果为2 str=input("请输入字符串:") s=input("请输入子串:") num=0 for i in range(len(str)): temp=str[i:i+3] if s in temp: num+=1 print(num)
#!/usr/bin/env python # encoding: utf-8 """ utils.py Created by jack ju on 2015-03-16. Copyright (c) 2015 TIKY. All rights reserved. """ import threading import time class Status(object): """ 状态机,封装起来为了保证多线程安全 """ INITINAL = 0 # 初始状态 CHECKING = 1 # Check 密码的阶段 INSERVICES = 2 ...
"""Python Script to generate a thumbnail of a webpage""" __author__ = "Surya Raman" __license__ = "MIT" import sys import requests as rq from bs4 import BeautifulSoup from newspaper import Article def send_request(url): """Function to get the html page""" try: resp = rq.get(url) return resp,...
# %% import os import math import numpy as np import pandas as pd from glob import glob import dataretrieval.nwis as nwis import datetime import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn import metrics import json import urllib.request as req import urllib import eval_func...
import os from dotenv import load_dotenv from starlette.datastructures import CommaSeparatedStrings, Secret ACCESS_COOKIE_EXPIRE_SECONDS = 60 * 60 # one hour in seconds REMEMBER_ME_COOKIE_EXPIRE_SECONDS = 60 * 60 * 24 * 7 # one week in seconds load_dotenv('.env') MAX_CONNECTIONS_COUNT = int(os.getenv('MAX_CONNECTIO...
from utilities import parse_arg from file_utils import * import os from random import shuffle import pickle data_base_dir = parse_arg('--data-base-dir', '/Users/balazs/real_data') pkl_file = os.path.join(data_base_dir, "data_trainingvalidation.pkl") if not file_exists(pkl_file): print("file does not exist" + pkl_...
''' Question: 체육복 * https://programmers.co.kr/learn/courses/30/lessons/42862 ''' def solution(n, lost, reserve): lost_ = list(set(lost) - set(reserve)) reserve_ = list(set(reserve)-set(lost)) attendees = n - len(lost_) reserve_.sort(reverse=True) for borrower in lost_: for lender in r...
''' InvertedIndexingGoogle.py reporduce the logic in chapter eric, park, tod, franco ''' from mrjob.job import MRJob from mrjob.step import MRStep import os #needed to get the name of the file import re #to get words WORD_RE = re.compile(r"[a-z|A-Z]+") class MRMostUsedWord(MRJob): ''' get the name of the fil...
from django.db import models from django.contrib.auth.models import User class Item(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(User, null=True) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) image = models.ImageFie...
import cv2 cap = cv2.VideoCapture(0) cap.set(3,640) # 设置宽度参数代码3,宽度640 cap.set(4,480) #高度 cap.set(10,100) #亮度 handCascade = cv2.CascadeClassifier('Resource/cascade.xml') #handCascade.load(r'F:\BaiduYunDownload\Hands.zipHands\xml6\cascade.xml') while True: success, img = cap.read() #cv2.imshow("Video...
from flask import render_template, request, redirect, session from private_wall_app import app from private_wall_app.models.Message import Message from private_wall_app.models.User import User from flask_bcrypt import Bcrypt from flask import flash bcrypt = Bcrypt(app) @app.route("/", methods=['GET']) def load_main_p...
import warnings from typing import Optional, Union from urllib import parse as urllib_parse from cas import CASClient from django.conf import settings as django_settings from django.contrib.auth import ( BACKEND_SESSION_KEY, REDIRECT_FIELD_NAME, SESSION_KEY, load_backend, ) from django.contrib.auth.mod...
import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable # cross entropy and center loss class CrossEntropyDistill(torch.nn.Module): """Cross entropy loss with label smoothing regularizer. Reference: Szegedy et al. Rethinking the Inception Architecture for Comp...
# run: python setup.py bdist_wheel to package into a distributable module from setuptools import setup setup( name="Webotron", version="1.0", author="Adam Wickenden", author_email="adam@wickenden.com", description="Automation of bucket/static site creation", license="GPLv3+", packages=["we...
""" Created on Jun 21, 2016 Files for training data @author: Levan Tsinadze """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from cnn.utils.file_utils import files_and_path_utils # Constants for files PATH_FOR_PARAMETERS = 'trained_data' P...
# -*- coding: utf-8 -*- # Basic implementation taken from # http://davisagli.com/blog/using-tiles-to-provide-more-flexible-plone-layouts from AccessControl import Unauthorized from Acquisition import aq_inner from Acquisition import aq_parent from collective.cover import _ from collective.cover.config import PROJECTNAM...
import numpy as np import matplotlib.pyplot as plt import scipy from numpy.testing._private.nosetester import NoseTester import math import cmath import scipy.interpolate import scipy from scipy import signal from quantiphy import Quantity SNRdb = 25 doppler_Frequency = 10 carrier_Freq = Quantity(100e6, '...
import random char = ['Mario', 'Luigi', 'Peach', 'Yoshi', 'Bowser', 'Donkey Kong', 'Toad', 'Koopa Troopa', 'Daisy', 'Wario', 'Rosalina', 'Metal Mario', 'Shy Guy', 'Honey Queen', 'Wiggler', 'Lakitu', 'Mii'] body = ['Standard', 'Gold Standard (Gold Kart)', 'Birthday Girl (Royal Ribbon)', 'Bumble V', 'Bruiser (Growl...
import ast import os import Game.config.config as config import Game.config.internal as internal import Game.program.misc.exceptions as exceptions import Game.program.misc.helpers as helpers _sentinel = object() def map_names(): map_names = [] for dirpath, dirnames, filenames in os.walk(internal.Maps.MAP...
def solution(gems): answer = [1,len(gems)] dic = {i:0 for i in gems} pick = set() s,e = 0,0 kind_n = len(dic) while e<=len(gems): if len(pick) == kind_n: if answer[1]-answer[0] > e-s-1: answer= [s+1, e] dic[gems[s]] -=1 if dic[gems[s]] ...
from Dane import * import matplotlib.pyplot as plt import numpy as np import datetime start = datetime.datetime.now() print('starting operation: ', start) # Read data from file data_generators = open('data/2018_5_generators.csv', 'rt') data_requirements = open('data/2018_5.csv', 'rt') power_requirement = np.loadtxt(d...
import sys from collections import Counter from typing import List, Dict, Tuple from arg.pf_common.base import ScoreParagraph from cache import load_from_pickle, save_to_pickle from list_lib import lmap from misc_lib import TimeEstimator from models.classic.stopword import load_stopwords from tlm.retrieve_lm.stem impo...
import sqlite3 import click from flask import current_app, g, logging from flask.cli import with_appcontext def get_db() -> sqlite3.Connection: """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if 'db' not...
from django.test import TestCase from django.urls import reverse from django.urls.exceptions import NoReverseMatch class SearchHelpPageTestCase(TestCase): def test_search_help_returns_200(self): response = self.client.get( reverse("search_help"), { "query": "fa", ...
import pandas as pd import numpy as np class Log1p_Norm: def __init__(self): self.Max = 0 def fit(self, data: pd.DataFrame, column_name: str): self.Max = data[column_name].max() def transform(self, data: pd.DataFrame, column_name: str): # do not need change new maximum value to o...
import os import argparse import subprocess import numpy as np import pandas as pd from tqdm import tqdm from pyntcloud import PyntCloud import pc_io parser = argparse.ArgumentParser( prog='eval.py', description='Eval decompressed point clouds PSNR and bitrate.', formatter_class=argparse.ArgumentDefaultsH...
from flask import Flask, render_template app=Flask(__name__) @app.route("/") def home(): return render_template('ImageBol.html') @app.route("/About") def about(): return render_template('AboutUs.html') app.run(debug=True)
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-11 16:27 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('activity', '0003_remove_activity_groupid'), ('signI...
from django.shortcuts import render #from qr_code.qrcode.utils import QRCodeOptions from django.contrib import messages from django.http import HttpResponse import pyqrcode import qrcode from django.contrib import auth # Create your views here. def QRcode(request): data = request.POST.get('data') # gets input fro...
import os import sys path = os.path.join(os.path.dirname(__file__), '../../../../..') sys.path.extend([path]) from automation.core.src.test_details import zid, category from automation.fluent_ml.prm.atoms.artifact import PRM @zid('98413') @category('work') def test_card_type_field(): """ Verify LK Card Type...
import io import os import pyaudio import wave import audioop from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types #audio format def record_audio(): CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 10 W...
import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.batchnorm import BatchNorm2d from torch.nn.modules.conv import Conv2d from torch.nn.modules.utils import _pair class MaxPool(nn.Module): """ MaxPool """ def __init__(self, kernel_size, stride, padding): super(MaxPool, ...
import unittest # Assume you have a method isSubstring which checks if one word is a substring of # another. Given two strings, s1 & s2, write code to check if s2 is a rotation of # s1 using only one call to isSubstring (e.g. "waterbottle" is a rotation of "erbottlewat") def string_rotation(st1, st2): if len(st1)...
#coding=utf-8 a=input('请输入字符串>>') ''' if a=='': print('为空!') ''' ''' if len(a)==0: print('为空') elif a[0]=='A' or a[0]=='E': print('yes') else: pass ''' if len(a)==0: print('null') elif a[0] in 'aeiouAEIOU': print(a+'ay') else: print(a[1:]+a[0]+'ay')
import mysql.connector import sys, csv, os from datetime import date, timedelta from priv import * # configs for database db = mysql.connector.connect(host=host, user=user, passwd=grantPass, db="real_estate") print("Connected to database \n") cur = db.cursor() today = date.today() first_day = today.replace(day=1) la...
""" class1 class2 class3 Training Set Points (2, 2), (4, 4), (2, 4) (6, 5), (5.4, 5.6), (3.6, 6.4) (1.8, 8), (5.6, 8.2) """ class1 = [[2,2],[4,4],[2,4]] class2 = [[6,5],[5.4,5.6],[3.6,6.4],[4.4,6]] class3 = [[1.8,8],[5.6,8.2]] train = [class1, class2, class3] def dist(p1,p2): return abs(p2[0]-p1[0])+abs(p2[1]-p1...
#!/usr/bin/env python # encoding: utf8 # # Copyright © Burak Arslan <burak at arskom dot com dot tr>, # Arskom Ltd. http://www.arskom.com.tr # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are ...
"""Pytorch Resnet_RS This file contains pytorch implementation of Resnet_RS architecture from paper "Revisiting ResNets: Improved Training and Scaling Strategies" (https://arxiv.org/pdf/2103.07579.pdf) """ from functools import partial import torch.nn as nn import torch.nn.functional as F from .base import StemBlock...
# -*- coding: utf-8 -*- """ Mudtable This is an advanced ASCII table creator. It was inspired by prettytable but shares no code. Example usage: table = MudTable("Heading1", "Heading2", table=[[1,2,3],[4,5,6],[7,8,9]], border="cells") table.add_column("This is long data", "This is even longer data") tab...
""" Python solution for DMOPC '13 Contest 3 Problem 3 - Crossing Field Submit with PyPy 3 to avoid TLE. """ import sys _lines = sys.stdin.read().split("\n") _line = -1 def input(): global _line _line += 1 return _lines[_line] n, h = input().split() n = int(n) h = int(h) grid = [[int(i) for i in input().s...
from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Blog # 홈페이지 함수 def home(request): blogs = Blog.objects return render(request, 'blog/home.html', {'blogs': blogs}) # 디테일 페이지 함수 def detail(request, blog_id): blog_detail = get_object_...
# Generated by Django 3.1.6 on 2021-02-12 13:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('meme_api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='meme', name='url', field...
#Normal Function # def fun1(): # print('hello') # fun1() #Call a function hello is printed # print(fun1()) #call a function hello is printed but function don't return anything so print returns none # print(fun1) #fun1 is an object whose address will be printed. # def func2(arg1, a...
# -*- coding: utf-8 -*- """ Created on Sat Jul 23 23:04:15 2016 @author: aditya """ import pandas as pd from sklearn.linear_model import LogisticRegression train_m = train.ix[:,['ID','Company_Level','Applicant_Gender', 'Applicant_Marital_Status', 'Applicant_Qualification', 'local', 'product1', 'Manage...
class Game: def __init__(self, move_count, last_player_elimination_score, player_elimination_score, trooper_elimination_score, trooper_damage_score_factor, stance_change_cost, standing_move_cost, kneeling_move_cost, prone_move_cost, commander_aura_...
from django.contrib import admin from .models import timePick , timeTest , sugarTest # Register your models here. admin.site.register(timePick) admin.site.register(timeTest) admin.site.register(sugarTest)
from os import sep, pardir from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # Declare the path to the sqlite database file. #path = pardir + sep + 'db' + sep + 'files' + sep path = '.' + sep + 'db' + sep + 'files' + sep # Declare the ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'backups_all.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from typecho.logic.operation import Operation class Ui_backups_all(object): ...
import pandas as pd import numpy as np import math import pickle from scipy import stats import scipy.io from scipy.spatial.distance import pdist from scipy.linalg import cholesky from scipy.io import loadmat import matlab.engine as engi import matlab as mat from sklearn.linear_model import LogisticRegression from s...
import shutil pyorbit = True simulation_parameters = False flat_files = False tune_files = False distn_gen = False master_directory = './00_Master' pyorbit_file = master_directory + '/pyOrbit.py' sim_params_file = master_directory + '/simulation_parameters.py' flat_file = master_directory + '/Flat_file.madx' tune_fil...
# -*- coding: utf-8 -*- from qiniu import Auth, create_timestamp_anti_leech_url from qiniu.compat import is_py2 from qiniu.compat import is_py3 import time def urlencode(str): if is_py2: import urllib2 return urllib2.quote(str) elif is_py3: import urllib.parse return urllib.par...
# Author: Wei Huang, Walter Castillo, Nicholas Matthew Gomez # Semester Year: Spring 2021 # CRN: 37239 # Purpose: Allow two player to play Scrabble Game by entering words def inputRounds(): x = int(input("Enter number of rounds: ") if type(x)!=int return x=2 def inputWord(currPlayer,lastWordEntered,Player1) ...
from flask import Flask, render_template, request, send_file from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import pandas as pd import psycopg2 from flask import request from io import BytesIO import matplotlib.pyplot as plt import base64 import matplotlib matplotlib....
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: def ambiguous_match(string, pattern, wildcards): """ Match strings via a custom, regular-expression-like syntax based on wildcard characters (e.g., * and ? and # etc....
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortcuts import HttpResponse, redirect, render from django.urls import reverse_lazy from django.contrib.auth.forms impo...
# print a regular string print('Mary had a little lamb.') # print the format string with the new string snow snow = "snow" print("Its fleece was white as {}.".format(snow)) # print the normal string print("And everywhere that Mary went.") # print the . 10 times print("." * 10) # what does that do? # declaring 12 varia...
class Template(object): def requiredAttributes(self): raise NotImplementedError(); def getSequenceGenerator(self, options): raise NotImplementedError(); class NSequencesTemplate(object): def requiredAttributes(self): return ['numSeq']+self.getAdditionalRequiredForSingleSequence();...
''' Created on Oct 29, 2017 ID3 @author: mabing ''' from math import log import operator ''' 计算给定数据集的信息熵 @param dataSet:数据集(包括类别) ''' def calcShannonEnt(dataSet): numEntries = len(dataSet) labelCounts = {} # key:类别,value:类别出现的次数 for featVec in dataSet: # 遍历数据集,统计类别出现的次数 currentLabel = featVec[-1...