from flask import render_template, redirect, url_for, abort, flash
from flask_login import current_user, login_required
from flask_moment import  datetime

from . import main
from .. import db
from .forms import ProfileForm, ProfileAdminForm, PostForm, PostAdminForm
from ..models import User, Role, Post, Permission, Language
from ..decorators import admin_required, permission_required

@main.route('/')
def index():
    pass

@main.route('/user/')
def user():
    users = User.query.order_by(User.last_seen.desc()).all()
    return render_template('user.html', users=users)

@main.route('user/profile/<username>/')
def user_profile(username):
    user = User.query.filter_by(username=username).first()
    posts = user.posts.order_by(Post.timestamp.desc()).all()
    if user is None:
        abort(404)
    else:
        return render_template('user_profile.html', user=user, posts=posts)

@main.route('/user/edit-profile/', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = ProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.main_language = form.main_language.data
        current_user.main_function = form.main_function.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash('Your profile has been updated')
        return redirect(url_for('main.user', username=current_user.username))
    else:
        form.name.data = current_user.name
        form.location.data = current_user.location
        form.main_language.data = current_user.main_language
        form.main_function.data = current_user.main_function
        form.about_me.data = current_user.about_me
        return render_template('edit_profile.html', form=form)

# TODO pagination
@main.route('/article/')
def article():
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('article.html', posts=posts)

@main.route('/article/<int:id>/')
def user_article(id):
    posts = Post.query.filter_by(author_id=id).all()
    return render_template('user_article.html', posts=posts)

@main.route('/article/write/', methods=['GET', 'POST'])
@login_required
@permission_required(Permission.WRITE_ARTICLES)
def write_article():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        flash('Your article has been posted')
        return redirect(url_for('main.user_profile',
                                username=current_user.username))
    else:
        return render_template('write_article.html')

@main.route('/article/edit/<int:id>/', methods=['GET', 'POST'])
@login_required
def edit_article(id):
    post = Post.query.get_or_404(id=id)
    form = PostForm()
    if current_user.id != post.author_id:
        abort(403)
    elif form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        post.timestamp = datetime.utcnow()
        db.session.add(post)
        flash('Your article has been update')
        return redirect(url_for('main.user_article', id=current_user.id))
    else:
        form.title.data = post.title
        form.body.data = post.body
        return render_template('edit_article.html', form=form, post=post)

@main.route('/manage/')
@login_required
@admin_required
def manage():
    pass

@main.route('/manage/user/<int:id>/', methods=['GET', 'POST'])
@login_required
@admin_required
def user_manage(id):
    user = User.query.get_or_404(id)
    form = ProfileAdminForm(user)
    if form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        user.role = Role.query.get_or_404(form.role.data)
        user.confirm = form.confirmed.data
        user.name = form.name.data
        user.location = form.location.data
        user.main_language = Language.query.get(form.main_language.data)
        user.main_function = form.main_function.data
        user.about_me = form.about_me.data
        flash('update successfully')
        return redirect(url_for('main.index'))
    else:
        form.username.data = user.username
        form.email.data = user.email
        form.role.data = user.role_id
        form.confirmed.data = user.confirm
        form.name.data = user.name
        form.location.data = user.location
        form.main_language.data = user.main_language_id
        form.main_function.data = user.main_function
        form.about_me.data = user.about_me
        return render_template('user_manage.html', form=form, user=user)

@main.route('/manage/article/<int:id>/', methods=['GET', 'POST'])
@login_required
@admin_required
def article_manage(id):
    post = Post.query.get_or_404(id)
    form = PostAdminForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.author = User.query.filter_by(id=form.author.data).first()
        post.body = form.body.data
        db.session.add(post)
        flash('update successfully')
        return redirect(url_for('main.manage'))
    else:
        form.title.data = post.title
        form.author.data = post.author_id
        form.body.data = post.body
        return render_template('article_manage.html', form=form)


# 1. Napisz program zmieniający skalę w stopniach Fahrenheita na naszą w Celcjuszach.
# Program powinen wykonać się w pętli od 0 do 200 stopni Fahrenheit, co 20 stopni.
temp_F = 0
while temp_F < 201:
    temp_C = (5.0/9.0) * (temp_F - 32)
    print('Temperatura w F =', temp_F, 'na C to:', round(temp_C, 2))
    temp_F = temp_F + 20

# 2. Napisz prostą grę, w której użytkownik musi zgadnąć liczbę od 0 - 20 ukrytą w programie (np. secret_num = 5).
# Pytaj użytkownika o podanie liczby tak długo, aż nie zgadnie.
shoot = int(input('Podaj liczbę od 0 do 20: '))
secretnb = 5
while not int(input("Pudło! Podaj inną liczbę od 0 do 20: ")) == secretnb:
    print('Pudło!')

print('Szczał w dziesiątkę!')


# -*- coding: utf-8 -*-
# Eddt is a directory browsing plugin written in Python for the Gnome text
# editor, gedit.
#
# Copyright (C) 2006 Michael Diolosa <michael@mbrio.org>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
# USA.

"""Settings manager for Eddt."""

import os.path

import gconf
import gnomevfs

import files

class Settings(object):
    """Settings manager for Eddt."""

    def __init__(self):
        """Constructor."""
        super(Settings, self).__init__()

        self.base = u'/apps/gedit-2/plugins/eddt'
        self.client = gconf.client_get_default()
        self.client.add_dir(self.base, gconf.CLIENT_PRELOAD_NONE)

    def get_terminal_arguments(self):
        """Gets the options to pass to the terminal application."""
        path = os.path.join(self.base, u'terminal_arguments')

        val = self.client.get(path)

        if val is not None:
            return val.get_string()

        return self.set_terminal_arguments()

    def set_terminal_arguments(self, arguments=None):
        """Sets the arguments to pass to the terminal.

        @param arguments: The arguments to pass to the terminal
        @type arguments: a string

        """
        path = os.path.join(self.base, u'terminal_arguments')
        args = u'--working-directory=%s'

        if arguments is not None:
            args = arguments

        self.client.set_string(path, args)

        return args

    def get_browser_arguments(self):
        """Gets the options to pass to the browser application."""
        path = os.path.join(self.base, u'browser_arguments')

        val = self.client.get(path)

        if val is not None:
            return val.get_string()

        return self.set_browser_arguments()

    def set_browser_arguments(self, arguments=None):
        """Sets the arguments to pass to the browser.

        @param arguments: The arguments to pass to the browser
        @type arguments: a string

        """
        path = os.path.join(self.base, u'browser_arguments')
        args = u'%s'

        if arguments is not None:
            args = arguments

        self.client.set_string(path, args)

        return args

    def get_file_filter(self):
        """Gets the file filter used when displaying files."""
        path = os.path.join(self.base, u'file_filter')

        val = self.client.get(path)

        if val is not None:
            return val.get_string()

        return self.set_file_filter()

    def set_file_filter(self, file_filter=None):
        """Sets the default file filter.

        @param file_filter: The file filter to use when listing files
        @type file_filter: a string

        """
        path = os.path.join(self.base, u'file_filter')
        filt = u''

        if file_filter is not None:
            filt = file_filter

        self.client.set_string(path, filt)

        return filt

    def get_file_browser(self):
        """Gets the default file browser."""
        path = os.path.join(self.base, u'file_browser')

        val = self.client.get(path)

        if val is not None:
            return val.get_string()

        return self.set_file_browser()

    def set_file_browser(self, default=None):
        """Sets the default file browser.

        @param path: The default browser
        @type path: a string

        """
        path = os.path.join(self.base, u'file_browser')
        app = u'file:///usr/bin/nautilus'

        if default is not None:
            app = default

        self.client.set_string(path, str(app))

        return app

    def get_terminal(self):
        """Gets the default terminal application."""
        path = os.path.join(self.base, u'terminal')

        val = self.client.get(path)

        if val is not None:
            return val.get_string()

        return self.set_terminal()

    def set_terminal(self, default=None):
        """Sets the default terminal application.

        @param path: The default terminal
        @type path: a string

        """
        path = os.path.join(self.base, u'terminal')
        app = u'file:///usr/bin/gnome-terminal'

        if default is not None:
            app = default

        self.client.set_string(path, str(app))

        return app

    def get_repository(self):
        """Gets the default repository from GConf."""
        path = os.path.join(self.base, u'repository')

        val = self.client.get(path)

        if val is not None:
            try:
                uri = gnomevfs.URI(val.get_string())
                file_info = gnomevfs.get_file_info(uri)

                if files.is_dir(file_info):
                    return uri
            except:
                pass

        return self.set_repository()

    def set_repository(self, uri=None):
        """Sets the default repository in GConf.

        @param uri: The URI to set the default repository to
        @type uri: a gnomevfs.URI

        """
        path = os.path.join(self.base, u'repository')
        file_uri = files.get_user_home_uri()

        # Check to see if uri was specified and if it is an actual directory
        if uri is not None:
            try:
                file_info = gnomevfs.get_file_info(uri)

                if files.is_dir(file_info):
                    file_uri = uri
            except:
                pass

        self.client.set_string(path, str(file_uri))

        return file_uri


from abc import ABC, abstractmethod

class Tuition(ABC):
  @abstractmethod
  def GetValue(self, credit):
    pass

class UTuition(Tuition):
  def GetValue(self, credit):
    return (credit - 1) * 500

class GTuition(Tuition):
  def GetValue(self, credit):
    return credit * 700

class Student():
  def __init__(self, na):
    self.name = na

  def Setter(self, tuiObj):
    self.tc = tuiObj

  def ComputeTuition(self, credit):
    if credit > 6:
      credit = 6

    return self.tc.GetValue(credit) + 5000

if __name__ == '__main__':
  Lily = Student("Lily Wang")
  under_tui = UTuition()
  Lily.Setter(under_tui)
  t1 = Lily.ComputeTuition(5)
  print("Lily:", t1)

  Peter = Student("Peter Sung")
  grad_tui = GTuition()
  Peter.Setter(grad_tui)
  t2 = Peter.ComputeTuition(7)
  print("Peter:", t2)


#!/usr/bin/env python3
# coding: utf-8
###################################################################
# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #
#                                                                 #
# This work is licensed under the terms of the MIT license.       #
# For further information, see https://github.com/mretegan/crispy #
###################################################################
"""This module provides a command line interface for generating the parameters of atomic configurations."""

__authors__ = ["Marius Retegan"]
__license__ = "MIT"
__date__ = "11/05/2019"

import argparse
import logging
import os

import h5py

from crispy.modules.quanty.utils import Calculations, Cowan, Element

def generate_parameters(elements):
    """Generate the atomic parameters of the elements and store them in an HDF5 container."""

    config = h5py.get_config()
    config.track_order = True

    root = os.path.dirname(os.path.abspath(__file__))

    calculations = Calculations(os.path.join(root, "calculations.json"))

    if elements == "all":
        elements = calculations.get_all_elements()

    for element in elements:
        element = Element(element)
        confs = calculations.unique_configurations(element)

        filename = "{:s}.h5".format(element.symbol)
        path = os.path.join(root, "atomic_parameters", filename)

        with h5py.File(path, "w") as h5:
            for conf in confs:
                cowan = Cowan(element, conf)
                conf.energy, conf.atomic_parameters = cowan.get_parameters()
                cowan.remove_calculation_files()

                # Write the parameters to the HDF5 file.
                root = "/{:s}".format(conf.name)
                h5[root + "/energy"] = conf.energy
                for parameter, value in conf.atomic_parameters.items():
                    path = root + "/parameters/{:s}".format(parameter)
                    h5[path] = value

                logging.info("%-2s %-8s", element.symbol, conf)
                logging.info("E = %-.4f eV", conf.energy)
                for parameter, value in conf.atomic_parameters.items():
                    logging.debug("%-s = %-.4f eV", parameter, value)
                logging.info("")

def main():
    parser = argparse.ArgumentParser(
        description="Generate the data needed to run the Quanty calculations.",
    )
    parser.add_argument("-l", "--loglevel", default="info")

    subparsers = parser.add_subparsers(dest="command")

    parameters = subparsers.add_parser("parameters")
    parameters.add_argument(
        "-e",
        "--elements",
        default="all",
        nargs="+",
        help="list of elements for which to generate the parameters",
    )

    args = parser.parse_args()

    logging.basicConfig(format="%(message)s", level=args.loglevel.upper())

    if args.command == "parameters":
        generate_parameters(args.elements)

if __name__ == "__main__":
    main()


import os
import re
import glob
import shutil
from tkinter import *
from tkinter import dialog
cwd = os.getcwd()
files = os.listdir(cwd)

def filelister():

    tempfileStorage = []
    for file in files:
        if file.lower().endswith(('.avi','.mp4','.mkv')):
            tempfileStorage.append(file)
        else:
            continue
    if len(tempfileStorage) == 0:
        print("No suitable files found!")
        return("No suitable files found!")
    if not len(tempfileStorage) == 0:
            for filey in tempfileStorage:
                print( filey )
                return tempfileStorage

def extensionremover(filename):
    registry = '\.(avi|mp4|mkv)|([-])+([ ])+([0-9])+'
    new_name = re.sub(registry,r'',filename)
    return new_name
def crc16(data: bytes, poly=0x8408):
    data = bytearray(data)
    crc = 0xFFFF
    for b in data:
        cur_byte = 0xFF & b
        for _ in range(0, 8):
            if (crc & 0x0001) ^ (cur_byte & 0x0001):
                crc = (crc >> 1) ^ poly
            else:
                crc >>= 1
            cur_byte >>= 1
    crc = (~crc & 0xFFFF)
    crc = (crc << 8) | ((crc >> 8) & 0xFF)
    return crc & 0xFFFF

def move():
        for _ in files:
            if _.lower().endswith(('.avi', '.mp4', '.mkv')):
                print("Attempting to copy: ",_)
            if _ == '.ipynb_checkpoints':
                continue
            if extensionremover(_) == _:
                continue
            else:
                if _.lower().endswith(('.avi', '.mp4', '.mkv')):
                    if not os.path.exists(extensionremover(_)):
                        os.mkdir(extensionremover(_))
                        shutil.copy(os.path.join(cwd,_),os.path.join(cwd,extensionremover(_)))
                        print("Copy complete, verifying")
                        if crc16(open(os.path.join(cwd,_))) == crc16(open(os.path.join(cwd,extensionremover(_),_))):
                            os.remove(os.path.join(cwd,_))
                            print("File",_,"is verified")
                        else:
                            os.remove(os.path.join(cwd,extensionremover(_),_))
                            print("Copying Failed for: ",_)
                    else:
                        shutil.copy(os.path.join(cwd,_),os.path.join(cwd,extensionremover(_)))
                        print("Copy complete,verifying")
                        if crc16(open(os.path.join(cwd,_))) == crc16(open(os.path.join(cwd,extensionremover(_),_))):
                            os.remove(os.path.join(cwd,_))
                            print("File",_,"is verified")
                        else:
                            os.remove(os.path.join(cwd,extensionremover(_),_))
                            print("Copying Failed for: ",_)


from  collections import defaultdict
a_group = defaultdict(list)
n_val, m_val =(int(x) for x in input().split(' '))
for i in range(n_val):
    a_group[input()].append(i + 1)
for _ in range(m_val):
    lst = a_group[input()]
    if len(lst) > 0:
        for el in lst:
            print(el, end=' ')
        print()
    else:
        print(-1)


r = float(input("Ведите радиус круга: "))
a = float(input("Введите длину стороны квадрата: "))
print("------------")
#Вычисления площадей
s1 = r**2*3.14
s2 = a**2
#Завершающие вычесления и ответ
if s1<s2:
    print("Площадь квадрата больше")
else:
    print("Площадь круга больше")


from selenium import webdriver
import time
import csv

ETFS = []
#open the csv file and record column[0] in a dictionary
with open('Materials Equity ETF List (62).csv', newline='') as csvfile:
	rows = csv.reader(csvfile)
	for row in rows:
		ETFS.append(row[0])

#timestamp now
Now = int(time.time())

for i in range(1, len(ETFS)):
	print(ETFS[i])
	#目標網頁的網址
	url1 = "https://finance.yahoo.com/quote/"
	etf = ETFS[i]
	print(etf)
	url2 = "/history?period1=1451491200&period2="
	now = str(Now)
	url3 = "&interval=1d&filter=history&frequency=1d"
	url = url1+etf+url2+now+url3

	#用chromedriver開啟Chrome
	driver = webdriver.Chrome()
	driver.get(url)

	#在網頁中找尋"Download Data並點擊"
	driver.find_element_by_link_text("Download Data").click()

driver.close()


import time
from random import randint

def log(func):
    def wrapper(*args, **kwargs):
        my_arg = ''
        if func.__name__ == 'start_machine':
            my_arg = 'Start Machine\t'
        elif func.__name__ == 'boil_water':
            my_arg = 'Boil Water\t\t'
        elif func.__name__ == 'make_coffee':
            my_arg = 'Make Coffee\t\t'
        elif func.__name__ == 'add_water':
            my_arg = 'Add Water\t\t'
        user_log = '(bcarlier)Running:'
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        with open('machine.log', 'a+') as f:
            f.write(f'{user_log} {my_arg} [ exec-time =  {end_time - start_time:.3f} ms ]\n')
        return result
    return wrapper

class CoffeeMachine:
    water_level = 100

    @log
    def start_machine(self):
        if self.water_level > 20:
            return True
        else:
            print("Please add water!")
            return False

    @log
    def boil_water(self):
        return "boiling..."

    @log
    def make_coffee(self):
        if self.start_machine():
            for _ in range(20):
                time.sleep(0.1)
                self.water_level -= 1
            print(self.boil_water())
            print("Coffee is ready!")

    @log
    def add_water(self, water_level):
        time.sleep(randint(1, 5))
        self.water_level += water_level
        print("Blub blub blub...")

if __name__ == "__main__":
    machine = CoffeeMachine()
    for i in range(0, 5):
        machine.make_coffee()
    machine.make_coffee()
    machine.add_water(70)


# -*- coding: utf-8 -*-
from logging import getLogger
from pkg_resources import get_distribution, iter_entry_points
from pyramid.interfaces import IRequest

from openprocurement.contracting.core.utils import (
    isContract,
    register_contract_contractType
)
from openprocurement.api.interfaces import IContentConfigurator
from openprocurement.contracting.core.models import IContract
from openprocurement.contracting.core.adapters import ContractConfigurator

PKG = get_distribution(__package__)

LOGGER = getLogger(PKG.project_name)

def includeme(config):
    LOGGER.info('Init contracting.core plugin.')
    # contractType plugins support
    config.registry.contract_contractTypes = {}
    config.add_route_predicate('contractType', isContract)
    config.add_directive('add_contract_contractType',
                         register_contract_contractType)
    config.scan("openprocurement.contracting.core.views")
    config.registry.registerAdapter(ContractConfigurator, (IContract, IRequest),
                                    IContentConfigurator)

    # search for plugins
    settings = config.get_settings()
    plugins = settings.get('plugins') and settings['plugins'].split(',')
    for entry_point in iter_entry_points(
            'openprocurement.contracting.core.plugins'):
        if not plugins or entry_point.name in plugins:
            plugin = entry_point.load()
            plugin(config)


from http.server import BaseHTTPRequestHandler, HTTPServer

# HTTPRequestHandler sınıfı
class HTTPServer_RequestHandler(BaseHTTPRequestHandler):

    # GET fonksiyonu
    def do_GET(self):
        # status kodunu gönder
        self.send_response(200)

        # header'ları gönder
        self.send_header('Content-type','text/html')
        self.end_headers()

        # istemciye gönderilecek mesajı belirle
        if self.path == "/":
            message = "Hello, world!"
        else:
            name = self.path[1:]
            message = "Hello, {}!".format(name)

        # mesajı yaz
        self.wfile.write(bytes(message, "utf8"))
        return

def run():
  print('starting server...')

  # set up server
  port = 8080
  server_address = ('0.0.0.0', port)
  httpd = HTTPServer(server_address, HTTPServer_RequestHandler)

  # run server
  print('running server on port {}...'.format(port))
  httpd.serve_forever()

run()


from mycontext import Surface

import math
import cmath
import numpy as np

import mycolors

class Mandelbrot:

    def linearBijection(x,ensemble_entree,ensemble_sortie):
        """Renvoie la valeur de f(x) par la bijection de l'ensemble_entree et l'ensemble_sortie."""
        min1,max1=ensemble_entree
        min2,max2=ensemble_sortie
        return (x-min1)/(max1-min1)*(max2-min2)+min2

    def __init__(self,iterations=5,digits=5):
        """Create a mandelbrot set."""
        self.iterations=iterations
        self.digits=digits

    def getColor(self,number,borns):
        """Return a color using a result of the """
        minimum,maximum=borns
        k=255-int(Mandelbrot.linearBijection(number,borns,[0,255]))
        return (k,0,0)

    def evaluate(self,x,y):
        """Evaluate position using the x and y."""
        zn=complex(0,0)
        c=complex(x,y)
        for i in range(self.iterations):
            zn=zn**2+c
        n=math.sqrt(zn.real**2+zn.imag**2)
        return n

    def surevaluate(x,y):
        """Surevaluate the position using the x and y components."""
        return int(n>2)

    def smooth(self,number):
        """Smooth a number using log and round functions. This process speeds up calculation."""
        return round(math.log(number+1),self.digits)

    def smoothSupport(self,support):
        """Smooth a support using round functions. This process speeds up calculation."""
        return [round(e,self.digits) for e in support]

    def show(self,surface,precision=[10,10]):
        """Show the mandelbrot set on the surface."""
        wsx,wsy=surface.draw.window.size
        corners=surface.draw.plane.getCorners(surface.draw.window)
        mx,my,Mx,My=corners
        px,py=precision
        ux,uy=surface.draw.plane.units
        print(ux,uy)
        px/=ux
        py/=uy
        x_support=np.arange(mx,Mx,px)
        y_support=np.arange(my,My,py)
        x_support=self.smoothSupport(x_support)
        y_support=self.smoothSupport(y_support)
        lx=len(x_support)
        ly=len(y_support)
        m=np.zeros((lx,ly))

        for iy in range(ly):
            for ix in range(lx):
                x=x_support[ix]
                y=y_support[iy]
                result=self.evaluate(x,y)
                result=self.smooth(result)
                m[ix][iy]=result

        maximum=np.max(m)
        minimum=np.min(m)
        borns=[minimum,maximum]

        for iy in range(ly):
            for ix in range(lx):
                x=x_support[ix]
                y=y_support[iy]
                value=m[ix][iy]
                color=self.getColor(value,borns)
                rect=[x,y,px,py]
                surface.draw.rect(surface.draw.window.screen,color,rect,1)

    def oldShow(self,surface,precision=[0.1,0.1]):
        """Show the mandelbrot set on the surface."""

        #Convert all the coordonnates to show on screen and for calculus
        window=surface.draw.window
        wsx,wsy=window.size
        ux,uy=surface.draw.plane.units #Units of the plane (how many pixels for 1 unit to display on screen in x and y components)
        plx,ply=1/ux,1/uy
        mx,my=surface.draw.plane.getFromScreen([0,0],surface.draw.window) #Top left corner
        Mx,My=surface.draw.plane.getFromScreen(window.size,surface.draw.window) #Top right corner

        plx,ply=abs(plx),abs(ply)
        prx,pry=precision
        prx,pry=abs(prx),abs(pry)

        #Store all evaluations in a matrix m
        itx=int(abs((Mx-mx)/prx))+1
        ity=int(abs((My-my)/pry))+1
        m=np.zeros((itx,ity))
        for iy in range(0,ity):
            for ix in range(0,itx):
                x=mx+ix*prx
                y=my+iy*pry
                result=self.evaluate(x,y) #Apply real calculation for mandelbrot set
                m[ix][iy]=self.smooth(result) #Apply a log function for simplicity

        maximum=np.max(m)
        minimum=np.min(m)
        borns=[minimum,maximum]

        #Show all the evaluations using colors adapted to the matrix
        for iy in range(0,ity):
            for ix in range(0,itx):
                x=mx+ix*prx
                y=my+iy*pry
                rect=[x,y,prx,pry]
                color=self.getColor(m[ix][iy],borns)
                surface.draw.rect(surface.draw.window.screen,color,rect,1)

if __name__=="__main__":
    surface=Surface()
    mandelbrot=Mandelbrot()
    result=mandelbrot.evaluate(100,50)
    while surface.open:
        surface.check()
        surface.control()
        surface.clear()
        surface.show()
        #surface.draw.rect(surface.screen,mycolors.ORANGE,(1,1,2,3),0)
        mandelbrot.show(surface)
        surface.flip()


# coding:utf-8
#export PYTHONPATH=/usr/local/lib/python3.6/dist-packages
#毎回これを実行
#インタープリタはpython3.7.4のbase condaのやつを使う
import numpy as np

import torch
import torch.nn as nn
import torch.optim as optim

import os

#同ディレクトリ内の別のファイルからのクラスの読み込み
from model import AlexNet
from dataloader import Dataloaders
from trainer import MyTrainer

def main():
    IMAGE_PATH = "/home/gonken2019/Desktop/subProject/images"#
    LABELS_PATH = "/home/gonken2019/Desktop/subProject/labels/"#
    BATCH_SIZE = 512
    #BATCH_SIZE = 10
    #RuntimeError: size mismatch, m1: [10 x 12544], m2: [9216 x 4096] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:197
    #9216×4096=37748736
    #37748736÷12544=3009.306122449
    #4096=2**12

    #BATCH_SIZE = 8
    #RuntimeError: size mismatch, m1: [8 x 12544], m2: [9216 x 4096] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:197

    NUM_EPOCH = 50 #多くて20~30

    if torch.cuda.is_available():
        device = "cuda";
        print("[Info] Use CUDA")
    else:
        device = "cpu"
    model = AlexNet()
    dataloaders = Dataloaders(IMAGE_PATH, LABELS_PATH, BATCH_SIZE)

    # optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=5e-4)
    #lossがnanになるのはよくあるので、こういうときはoptimizerを変えるか学習率変えるかするといい

    trainer = MyTrainer(model, dataloaders, optimizer, device)

    trainer.run(NUM_EPOCH)#

main()#

###########################################################################################

"""
# coding:utf-8
#export PYTHONPATH=/usr/local/lib/python2.7/dist-packages
#毎回これを実行
import numpy as np

import torch
import torch.nn as nn
import torch.optim as optim

import os

#同ディレクトリ内の別のファイルからのクラスの読み込み
from model import AlexNet
from dataloader import Dataloaders
from trainer import MyTrainer

def main():
    IMAGE_PATH = ""
    LABELS_PATH = ""
    BATCH_SIZE = 8
    NUM_EPOCH = 25 #多くて20~30

    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    model = AlexNet()
    dataloaders = Dataloaders(IMAGE_PATH, LABELS_PATH, BATCH_SIZE)

    criterion = nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)

    trainer = MyTrainer(model, dataloaders, optimizer, criterion, device)

    trainer.run()

if __name__ is "__main__":
    main()

    """"""__name__はPythonプリンタでPythonスクリプトを読み込むと自動的に作成される。

        Pythonスクリプトを直接実行した時には、そのスクリプトファイルは「__main__」という名前のモジュールとして認識される
        そのため、スクリプトファイルを直接実行すると__name__変数の中に自動で'__main__'という値が代入される

        要するに
        「if __name__ == '__main__':」の意味は、「直接実行された場合のみ実行し、それ以外の場合は実行しない」"""


# creating partitions
import time

def divide(size,no_parts):

    f_in = open("data.csv", "r")

    for i in range(no_parts):
        txt = "data_" + str(i) + ".csv"
        f = open(txt,"w")
        cnt = 0

        while True:
            line = f_in.readline()
            f.write(line)
            cnt = cnt+1
            if (cnt == size):
                break
        f.close()

    f_in.close()


def read_int_list():
    return list(map(int, input().split()))

def read_ints():
    return map(int, input().split())

def main():
    N = int(input())
    dp = [[0, 0, 0] for _ in range(N)]
    A = []
    for _ in range(N):
        A.append(read_int_list())

    dp[0][0] = A[0][0]
    dp[0][1] = A[0][1]
    dp[0][2] = A[0][2]

    for i in range(1, N):
        for j in range(3):
            happy = A[i][j]
            act1 = (j + 1) % 3
            act2 = (j + 2) % 3
            dp[i][j] = max(dp[i - 1][act1], dp[i - 1][act2]) + happy
    print(max(dp[N - 1]))

main()


''' This module provides functionality for user subscription to topic threads in flaskr, and for subsequent notification
    of new posts in subscribed threads. It is imported to the main module, flaskr.py, where its functions are called
    at corresponding trigger events. Subscriptions are stored in the subs table of the database, which is created during
    database initialization. This table contains a primary key ID for each subscription, as well as a userID, topicID,
    and a notified integer value (1 or 0) indicating if the latest version of a subscribed thread has been viewed by the
    user or not.'''

def unfoldToList(tpl):
    ''' Helper function that receives values from the sqLite3 database as tuples, and converts them to list format.

    Arguments:
    tpl - A tuple of values

    Returns:
    toReturnList - A list of values '''

    toReturnList = []
    for element in tpl:
        toReturnList.append(element[0])
    return toReturnList

def isSubscribed(user):
    ''' Identify all topic threads to which a user has subscribed. This function is used to determine whether the
    Subscribe or Unsubscribe button should be displayed on each topic.

    Arguments:
    user - The ID of a user (integer)

    Returns:
    subsList - A list of topicIDs (integers) for threads that the user has subscribed to '''

    db = get_db()
    cur = db.execute('select topicId from subs where userId = (?)', [user])
    subsTuples = cur.fetchall()
    subsList = unfoldToList(subsTuples)
    return subsList

def create_subscription(user, topic):
    ''' Create a new subscription in the database. Called whenever the Subscribe button is clicked.

    Arguments:
    user - The ID of a user (integer)
    topic - The ID of the topic to which the user is subscribing (integer)

    Returns:
    Nothing -- the function adds a row to the subs table and flashes a success message. '''

    db = get_db()
    db.execute('insert into subs (userId, topicId, notified) values (?, ?, ?)',
               [user, topic, 1])
    db.commit()
    flash('Subscribed!')

def unsubscribe(user, topic):
    ''' Delete a subscription from the database. Called whenever the Unsubscribe button is clicked.

    Arguments:
    user - The ID of a user (integer)
    topic - The ID of the topic from which the user is unsubscribing (integer)

    Returns:
    Nothing -- the function deletes a row from the subs table and flashes a success message. '''

    db = get_db()
    db.execute('delete from subs where userId = ? and topicId = ?', [user, topic])
    db.commit()
    flash('Unsubscribed!')

def show_notifications(user):
    ''' Show a notification on each thread which a user has subscribed to, and has not viewed since it was last
    updated. Called whenever the Show Topics page is loaded.

    Arguments:
    user - The ID of a user (integer)

    Returns:
    ssList - A list of topicIDs (integers) for threads that should have a notification displayed. '''

    db = get_db()
    cur = db.execute('select topicId from subs where userId =? and notified =?', [user, 0])
    sslist = unfoldToList(cur.fetchall())
    return sslist

def view_notification(user, topic):
    ''' Mark a notification as viewed, turning it off until the next time the associated topic thread is updated.
    Called when a user navigates to the page of a topic that was displaying a notification.

    Arguments:
    user - The ID of a user (integer)
    topic - The ID of the topic displaying the notification (integer)

    Returns:
    Nothing -- the function switches the value of notified from 0 to 1 in the corresponding row of the subs table. '''

    db = get_db()
    db.execute('update subs set notified = (?) where userId = (?) and topicId = (?)', [1, user, topic])
    db.commit()

def update_subscription(topic):
    ''' Update all subscriptions when a new post (or edit) is made within a topic thread. This topic thread will subsequently
    display a notification to all subscribed users.

    Arguments:
    topic - The ID of a topic (integer)

    Returns:
    Nothing -- the function switches the value of notified to 0 for all rows of the subs table containing the given
               topicID. '''

    db = get_db()
    db.execute('update subs set notified = (?) where topicId = (?)', [0, topic])
    db.commit()

from .flaskr import *


from .models import Info
from django.forms import ModelForm, DateField, Textarea, CharField

class InfoForm(ModelForm):
    name = CharField()
    surname = CharField()
    story = Textarea()
    date = DateField()
    class Meta:
        model = Info
        fields = ['name', 'surname', 'story', 'date']


import pickle
import os
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request

##This file's purpose is to create a token via authenticating to google's api client.

def Create_Service(client_secret_file, api_name, api_version, *scopes):
##    Searching for a pre existing token,if not found in the current folder it creates it.
##
##       Args:
##            client_secret_file :Numbers of emails that will be displayed.
##            api_version : The version of the api currently the version is 1.
##            api_name : The name of the api.
##            scopes : The privileges provided from google to us.

##  print(client_secret_file, api_name, api_version, scopes, sep='-')

    scopes = [scope for scope in scopes[0]]

    cred = None

    pickle_file = f'token_{api_name}_{api_version}.pickle'
    #Creates a searchable name

    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as token:
            cred = pickle.load(token)
    #Searches if the credentials file exists

    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())
            #if the token is not valid it refreshes the existing one
        else:
            flow = InstalledAppFlow.from_client_secrets_file(client_secret_file, scopes)
            cred = flow.run_local_server(port=0)
            #if the creds does not exist it creates new

        with open(pickle_file, 'wb') as token:
            pickle.dump(cred, token)
            #open the pickle_file
    try:
        service = build(api_name, api_version, credentials=cred)
        print(api_name, 'service created successfully')
        #Creates a survice and returns it to read or send scripts
        return service

    except scopes:
        return 2

    except ConnectionError:
        return 10

    except Exception as e:
        return 1


my_name = 'Zed'
my_age = 35 # not a lie
my_height = 74 # in inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'While'
my_hair = 'Brown'

print(f"Let's talk about {my_name}")
print(f"He is {my_height} inches tall.")
# format 输出 比较好用一点


from pb_creator import base
from pb_creator.types import pb_type

DocType = pb_type.Type

class Field(base.Base):
    def __init__(self, field_name: str, field_type: pb_type.Type, number: int = 0, is_repeated: bool = False):
        super(Field, self).__init__(field_name)
        self.is_repeated: bool = is_repeated
        self.number: int = number
        self.type: DocType = field_type

    def to_text(self) -> str:
        result = ""
        if self.is_repeated:
            result += "repeated "
        result += self.type.name + " "
        result += self.name + " = "
        result += str(self.number) + ";"
        return result


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 12:31:14 2019

@author: Paul Scheibal
#
#  Predicts Career OPS
#
#  This program runs a series of regression machine learning algorithms using the
#  predictive model for baseball player performance prediction.  The models used are from
#  sklearn machine learning library and are
#
#           Non-Linear Regression
#           Ridge Regression
#           XGBoost
#           Random Forests
#           SVM
#           Lasso for viewing features and redundencies
#
#  There are two parts to the program.  One is the execution of all six algorithms against
#  the model in sequence.  The second part is a comparison of the regression to the mean (rtm)
#  features and the non-rtm features to see if rtm made a postive difference.  Only XGBoost and
#  Ridge Regression were used for this part of the excersize.
#
#
"""

import pandas as pd
import numpy as np
from datetime import datetime
import os.path
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib as mpl
import pylab as plb
import matplotlib.mlab as mlab
import math
from numpy.random import seed
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.svm import SVR
from statsmodels.graphics.regressionplots import *
from scipy.stats import probplot
import xgboost as xgb
from xgboost import XGBRegressor
import seaborn as sns
from IPython.core.pylabtools import figsize
import random
import warnings
warnings.filterwarnings("ignore")

figsize(14,10)
#sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white'})
sns.set_style('white')

# standard global constants
MIN_AT_BATS = 0
START_YEAR = 1960
END_YEAR = 2018
FSHZ = 17
START_DATE = datetime.strptime(str(START_YEAR)+'-01-01','%Y-%m-%d')
END_DATE = datetime.strptime(str(END_YEAR)+'-12-31','%Y-%m-%d')
LEGEND_PROPERTIES = {'weight':'bold'}

# general save file function
def save_stats_file(path, fn, df):
    stf = path + fn
    df.to_csv(stf, index=None, header=True)
    return True

# custom split into training and test sets where a player will belong to one and only one set (training or testing).
def split_players(df,pct):
    random.seed(70)
    players = np.array(df.playerID.drop_duplicates())
    plen = len(players)
    indlst = random.sample(range(0,plen), round(pct*plen))
    print('Number of Testing Players ' + str(round(plen*pct)))
    test_players = np.array(players[indlst])
    train_players = np.setdiff1d(players,test_players)
    return train_players, test_players

# custom split into training and test sets
def split_df(df,pct):
    train_p, test_p = split_players(df,pct)
    df_train = df[df.playerID.isin(train_p)]
    df_test = df[df.playerID.isin(test_p)]
    return df_train, df_test

# normalize numeric values if zeromean then use zero mean calc, otherwise use min/max calc
def normalize_values(X,cols,cn,type):
    if type == 'zeromean' :
        X[cn] = (X.loc[:,cols] - np.mean(X.loc[:,cols]))/ np.std(X.loc[:,cols])
    else :
        X[cn] = (X.loc[:,cols] - np.min(X.loc[:,cols])) / ((np.max(X.loc[:,cols]))- np.min(X.loc[:,cols]))
    return X

# normalize categories (like Position)
def normalize_categories(X,cols,prefx):
    X_temp = X[cols]
    X = pd.get_dummies(X,columns=cols,prefix=prefx)
    X[cols] = X_temp
    return X

# custom calculation for R Squared, Adj R Squared, MSE, RMSE, FStatistic and others.  Same as what is supplied in python.
# I wanted to understand the calculations
def calc_regression_stats(X,y,yp):
    y = np.array(y)
    yp = np.array(yp)
    n = len(y)
    k = len(X.columns)
    yavg = sum(y)/n
    TSS = sum((y - yavg) ** 2)
    RSS = sum((y - yp) ** 2)
    Rsquared = 1 - (RSS/TSS)
    AdjRsquared = Rsquared - ((1-Rsquared) * ( k / ( n - k - 1 ) ) )
    MSE = RSS / n
    RMSE = np.sqrt(MSE)
    Fstatistic = ( Rsquared / (1 - Rsquared) ) * ( (n - k - 1 ) / k )
    error = ( (y - yp) / y ) * 100
    AbsErrorSum = sum(abs(error))
    MeanOfError = np.mean(error)
    StdOfError = np.std(error)
    return Rsquared, AdjRsquared, MSE, RMSE, Fstatistic, MeanOfError, StdOfError, AbsErrorSum

# various plots for assessing each machine learning run for each algorithm
def lr_results(df,X_test,y_test,y_pred,path,fn,stats_list,mdlinst):
    df_results = df.loc[y_test.index, :]
    df_results['predcOPS'] = y_pred
    df_results['error'] = 100 * ( ( df_results['cOPS'] - df_results['predcOPS'] ) / df_results['cOPS'])
    df_results['abserror'] = np.abs(100 * ( ( df_results['cOPS'] - df_results['predcOPS'] ) / df_results['cOPS']))
    #
    df_results['predcOPS'] = df_results['predcOPS']
    df_results['cOPS'] = df_results['cOPS']
    df_results['error'] = df_results['error']
    df_out = df_results[stats_list]
    save_stats_file(path,fn, df_out)
    #  calculate Rsquared, Adj Rsquared, MSE, RMSE and Fstatistic using my routine
    Rsquared, AdjRsquared, MSE, RMSE, Fstatistic, MeanOfError, StdOfError, AbsErrorSum = calc_regression_stats(X_test,y_test,y_pred)
    # print statistics
    print('R Squared: %1.4f' % Rsquared)
    print('Adjusted R Squared: %1.4f' % AdjRsquared)
    print('F Statistic: %1.4f' % Fstatistic)
    print('MSE: %1.4f' % MSE)
    print('RMSE: %1.4f' % RMSE)
    print('Test Observations:',format(len(y_test)))
    print('Sum of Abs Pct Error: %5.1f' % AbsErrorSum)
    print('Pct Mean Error: %1.4f' % MeanOfError)
    print('Pct Std Dev Error: %1.4f' % StdOfError)
    # print plots
    fig, ax = plt.subplots()
    ax.grid()
    acc = df_results.error
    ptile = np.percentile(acc,[15,85,2.5,97.5])
    sns.regplot(x=df_out['cOPS'], y=df_out['predcOPS'],
                line_kws={"color":"r","alpha":0.7,"lw":5},
                scatter_kws={"color":"b","s":8}
               )
    plt.title('Actual cOPS vs. Predicted cOPS')
    plt.xlabel('Actual cOPS')
    plt.ylabel('Predicted cOPS')
    plt.show()
    fig, ax = plt.subplots()
    ax.grid()
    plt.hist(acc,bins=25)
    plt.title('Error : Actual cOPS - Predicted cOPS')
    plt.xlabel('Error')
    plt.ylabel('Frequency')
    lab = 'Sampling Mean: %1.2f' % round(np.mean(df_out.error),2)
    lab1 = 'Conf Interval 15 ( %1.3f' % ptile[0] + ' )'
    lab2 = 'Conf Interval 85 ( %1.3f' % ptile[1] + ' )'
    lab3 = 'Conf Interval 2.5 ( %1.3f' % ptile[2] + ' )'
    lab4 = 'Conf Interval 97.5 ( %1.3f' % ptile[3] + ' )'
    plb.axvline(round(np.mean(df_out.error),2),label=lab, color='brown')
    plb.axvline(round(ptile[0],3), label=lab1, color='red')
    plb.axvline(round(ptile[1],3), label=lab2, color='red')
    plb.axvline(round(ptile[2],3), label=lab3, color='green')
    plb.axvline(round(ptile[3],3), label=lab4, color='green')
    leg=plt.legend()
    plt.show()
    fig, ax = plt.subplots()
    ax.grid()
    # plot QQ Plot to see if normal
    probplot(acc,dist="norm",plot=plb)
    _ = plt.title('QQ Plot of OPS Data\n',weight='bold', size=16)
    _ = plt.ylabel('Ordered Values', labelpad=10, size=14)
    _ = plt.xlabel('Theoritical Quantiles', labelpad=10, size = 14)
    ax = plt.gca()
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:1.3f}'))
    plt.xticks(np.arange(-4,5,1))
    plb.show()
    fig, ax = plt.subplots()
    ax.grid()
    plt.plot(y_pred, (y_pred-y_test), marker='.',linestyle='none',color='b')
    plt.title('Predicted cOPS vs. Residuals')
    plt.xlabel('Predicted cOPS')
    plt.ylabel('Residuals')
    plt.show()
    return True

def machine_learning_runs(df_train, df_test ,feature_list, stats_list,txt,fileending):

    print('**************** ' + txt + '*******************')
    # setup training and testing sets
    X_train = df_train[feature_list]
    y_train = df_train.cOPS
    X_test = df_test[feature_list]
    y_test = df_test.cOPS
    ################################################### Lasso ###################################################################
    print('\n')
    print('Linear Regression - Lasso')
    print('\n')
    #
    #  just want features and which ones provide value
    #
    lasso = Lasso(alpha=0.001, random_state=61)
    lasso_coef = lasso.fit(X_train, y_train).coef_
    cols = feature_list
    fig, ax = plt.subplots()
    ax.grid()
    plt.plot(range(len(cols)), lasso_coef)
    plt.xticks(range(len(cols)), cols, rotation=45)
    plt.title('Feature Value Plot',weight='bold', size=16 )
    plt.xlabel('Features',weight='bold', size=14)
    plt.ylabel('Coefficients',weight='bold', size=14)
    plt.show()

    ##################################################### XGBoost ###############################################################
    ###   learning_rate: step size shrinkage used to prevent overfitting. Range is [0,1]
    ###   max_depth: determines how deeply each tree is allowed to grow during any boosting round.
    ###   subsample: percentage of samples used per tree. Low value can lead to underfitting.
    ###   colsample_bytree: percentage of features used per tree. High value can lead to overfitting.
    ###   n_estimators: number of trees you want to build.
    ###   objective: determines the loss function to be used like reg:linear for regression problems,
    ###              reg:logistic for classification problems with only decision, binary:logistic for
    ###              classification problems with probability.
    ###
    ###   XGBoost also supports regularization parameters to penalize models as they become more complex and reduce them to simple (
    ###   parsimonious) models.
    ###
    ###   gamma: controls whether a given node will split based on the expected reduction in loss after the split.
    ###          A higher value leads to fewer splits. Supported only for tree-based learners.
    ###   alpha: L1 regularization on leaf weights. A large value leads to more regularization.
    ###   lambda: L2 regularization on leaf weights and is smoother than L1 regularization.
    ###
    ################################################### XGBoost ##############################################################

    print('\n')
    print('XGBoost GridSearchCV')
    print('\n')
    params = {
                'colsample_bytree': [0.6],
                'learning_rate':[0.1],
                'n_estimators': [100,120],
                'max_depth':[3,4],
                'alpha':[0.01],
                'gamma':[0.001],
                'subsamples':[0.6]
            }
    reg_xgb = XGBRegressor(objective = 'reg:squarederror')
    gs = GridSearchCV(estimator=reg_xgb,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)
    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsXGBc' + fileending,stats_list,gs)
    print(gs.best_params_)
    ####################################################### Ridge ##############################################################
    print('\n')
    print('Linear Regression - Ridge')
    print('\n')
    params = {
                'alpha':[0.0001,0.001,0.1,0.1]
            }
    ridge = Ridge(normalize=True,random_state=61)
    gs = GridSearchCV(estimator=ridge,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)
    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsRidgec' + fileending,stats_list,ridge)
    print(gs.best_params_)
    return True

def machine_learning_runs_all(df_train, df_test ,feature_list, stats_list):
    # setup training and testing sets
    X_train = df_train[feature_list]
    y_train = df_train.cOPS
    X_test = df_test[feature_list]
    y_test = df_test.cOPS
    ################################################### Lasso ###################################################################
    print('\n')
    print('Linear Regression - Lasso')
    print('\n')
    #
    #  just want features and which ones provide value
    #
    fig, ax = plt.subplots()
    ax.grid()
    lasso = Lasso(alpha=0.001, random_state=61)
    lasso_coef = lasso.fit(X_train, y_train).coef_
    cols = feature_list
    plt.plot(range(len(cols)), lasso_coef)
    plt.xticks(range(len(cols)), cols, rotation=45)
    plt.title('Feature Value Plot',weight='bold', size=16 )
    plt.xlabel('Features',weight='bold', size=14)
    plt.ylabel('Coefficients',weight='bold', size=14)
    plt.show()
    ####################################################### XGBoost ##############################################################
    print('\n')
    print('XGBoost GridSearchCV')
    print('\n')
    params = {
                'colsample_bytree': [0.6],
                'learning_rate':[0.1],
                'n_estimators': [100,120],
                'max_depth':[3,4],
                'alpha':[0.01],
                'gamma':[0.001],
                'subsamples':[0.6]
            }
    reg_xgb = XGBRegressor(objective = 'reg:squarederror')
    gs = GridSearchCV(estimator=reg_xgb,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)
    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsXGB_GSc.csv',stats_list,gs)
    print(gs.best_params_)
    ####################################################### Ridge ##############################################################
    print('\n')
    print('Linear Regression - Ridge')
    print('\n')
    params = {
                'alpha':[0.0001,0.001,0.1,0.1]
            }
    ridge = Ridge(normalize=True,random_state=61)
    gs = GridSearchCV(estimator=ridge,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)
    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsRidge_GSc.csv',stats_list,ridge)
    print(gs.best_params_)
    ###################################################### Random Forests #########################################################
    print('\n')
    print('Random Forest Regressor')
    print('\n')
    # Create the parameter grid based on the results of random search
    params = {
        'max_depth': [300],
        'max_features': [3],
        'min_samples_leaf': [5],
        'min_samples_split': [12],
        'n_estimators': [1000]
    }
    # Create a based model
    rf = RandomForestRegressor(random_state=61,bootstrap=True)
    # Instantiate the grid search model
    gs = GridSearchCV(estimator=rf,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)

    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsRF_GSc.csv',stats_list,gs)

    print(gs.best_params_)
    #################################################### SVM ###################################################################
    print('\n')
    print('SVM with GridSearchCV')
    print('\n')

    params = {
        'C': [0.1,1],
        'gamma': [0.001, 0.01, 0.1]
    }

    svm = SVR(kernel='rbf')

    gs = GridSearchCV(estimator=svm,param_grid=params,cv=10,n_jobs = -1,verbose = 2)
    gs.fit(X_train, y_train)
    y_pred2 = gs.predict(X_train)
    v_Rsquared, v_AdjRsquared, v_MSE, v_RMSE, v_Fstatistic, v_MeanOfError, v_StdOfError, v_AbsErrorSum = calc_regression_stats(X_train,y_train,y_pred2)
    print('\n')
    print('Training Statistics: ')
    print('\n')
    print('R Squared (training): %1.3f' % v_Rsquared)
    print('Adjusted R Squared (training): %1.3f'  % v_AdjRsquared)
    print('Mean Squared Error (training): %1.3f' % v_MSE)
    print('Root Mean Squared Error (training): %1.3f' % v_RMSE)
    print('F Statistic (training): %1.3f' % v_Fstatistic)
    print('\n')

    print('\n')
    print('Testing Statistics: ')
    print('\n')
    y_pred = gs.predict(X_test)

    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsSVM_GSc.csv',stats_list,gs)

    print(gs.best_params_)
    ###################################################### poly ################################################################
    print('\n')
    print('Linear Regression - Polynomial')
    print('\n')

    degree = 2

    poly = PolynomialFeatures(degree=degree)
    X_train_ = poly.fit_transform(X_train)
    X_test_ = poly.fit_transform(X_test)

    lg = LinearRegression()

    params = {
                'normalize':[True,False]
             }

    gs = GridSearchCV(estimator=lg,param_grid=params,cv=10,n_jobs = -1,verbose = 2)

    gs.fit(X_train_,y_train)

    y_pred = gs.predict(X_test_)

    lr_results(df,X_test,y_test,y_pred,path,'OPSpredictionsPolyc.csv',stats_list,gs)

    print(gs.best_params_)

    return True

# set path for reading Lahman baseball statistics and read data from rttm dataset
path = 'C:\\Users\\User\\Documents\\PAUL\\Springboard\\core\\'

battingf = path + 'dfbatting_player_stats_rttm_OPS.csv'
dfbatting_player_stats = pd.read_csv(battingf,parse_dates=['debut','finalGame','birthdate'])

dfbatting_player_stats = dfbatting_player_stats[(dfbatting_player_stats['debut'] >= START_DATE) &
                                                (dfbatting_player_stats['finalGame'] <= END_DATE)]
df = dfbatting_player_stats
df = df.reset_index(drop=True)
df = df[df['AB'] >= 300]

# add decade
df['decade'] = (df['yearID'] // 10)*10

df = normalize_categories(df,['POS'],['POS'])
df = normalize_values(df,['years_played','lag1_rtm_cAVG',  'lag1_rtm_AVG',  'lag1_cAVG',  'lag1_AVG', 'lag1_HR', 'lag1_cHR', 'lag1_rtm_HR', 'lag1_rtm_cHR', 'lag1_H', 'lag1_rtm_H', 'lag1_cH', 'lag1_rtm_cH', 'lag1_TB',  'lag1_cTB',  'lag1_AB',  'lag1_cAB', 'lag1_rtm_SLGTB', 'lag1_rtm_cSLGTB',  'lag1_rtm_SLGAB',  'lag1_rtm_cSLGAB', 'lag1_rtm_AB', 'lag1_rtm_cAB', 'decade',  'lag1_OPS', 'lag1_cOPS', 'lag1_OB', 'lag1_PA', 'lag1_OBP', 'lag1_cOBP', 'lag1_SLG', 'lag1_cSLG' ,'lag1_cOB',  'lag1_cPA', 'lag1_rtm_OB', 'lag1_rtm_PA', 'lag1_rtm_OPS', 'lag1_rtm_cOB', 'lag1_rtm_cPA', 'lag1_rtm_cOPS',  'age', 'height', 'weight', 'lag1_rtm_c1B', 'lag1_rtm_c2B', 'lag1_rtm_c3B', 'lag1_rtm_1B', 'lag1_rtm_2B', 'lag1_rtm_3B', 'lag1_c1B', 'lag1_c2B', 'lag1_c3B', 'lag1_1B', 'lag1_2B', 'lag1_3B', 'lag1_rtm_OBP', 'lag1_rtm_cOBP', 'lag1_rtm_SLG',  'lag1_rtm_cSLG'],
                         ['nyears_played','lag1_rtm_ncAVG', 'lag1_rtm_nAVG', 'lag1_ncAVG', 'lag1_nAVG','lag1_nHR','lag1_ncHR','lag1_rtm_nHR','lag1_rtm_ncHR','lag1_nH','lag1_rtm_nH','lag1_ncH','lag1_rtm_ncH','lag1_nTB', 'lag1_ncTB', 'lag1_nAB', 'lag1_ncAB','lag1_rtm_nSLGTB','lag1_rtm_ncSLGTB', 'lag1_rtm_nSLGAB', 'lag1_rtm_ncSLGAB','lag1_rtm_nAB','lag1_rtm_ncAB','ndecade', 'lag1_nOPS','lag1_ncOPS','lag1_nOB','lag1_nPA','lag1_nOBP','lag1_ncOBP','lag1_nSLG','lag1_ncSLG','lag1_ncOB', 'lag1_ncPA','lag1_rtm_nOB','lag1_rtm_nPA','lag1_rtm_nOPS','lag1_rtm_ncOB','lag1_rtm_ncPA','lag1_rtm_ncOPS', 'nage','nheight','nweight','lag1_rtm_nc1B','lag1_rtm_nc2B','lag1_rtm_nc3B','lag1_rtm_n1B','lag1_rtm_n2B','lag1_rtm_n3B','lag1_nc1B','lag1_nc2B','lag1_nc3B','lag1_n1B','lag1_n2B','lag1_n3B','lag1_rtm_nOBP','lag1_rtm_ncOBP','lag1_rtm_nSLG', 'lag1_rtm_ncSLG'],'zeromean')

# read team mapping and create a mapping function from string to integer
teamsf = path + 'teams_list.csv'
dfteams = pd.read_csv(teamsf)
teams_map = pd.Series(dfteams.index,index=dfteams.teamID).to_dict()
df.teamID = df.teamID.map(teams_map)

pct = 0.20

# custom train / test split on player boundaries.  IE, a player will belong to one and only one set (training or test)
# for a given run
df_train, df_test = split_df(df,pct)

print('Number of Training Records:',len(df_train))
df_test = df_test[ (df_test['OPS'] > .3) & (df_test['OPS'] < 1.2) & (df['AB'] >= 300) & (df['age'] >= 20) & (df['age'] <= 37)  ]
print('Number of Testing Records:',len(df_test))
# list of columns to output to file once run is completed.
stats_list = ['yearID','playerID','playername','cOPS','predcOPS','error','AB','H','AVG','HR','3B','2B','1B','POS','age','height','lag1_rtm_OPS']
feature_list = ['lag1_ncHR','lag1_nHR','nage','nheight','ndecade','POS_1B','POS_2B','POS_3B','POS_SS','POS_OF','lag1_nSLG','lag1_ncSLG','lag1_nOBP','lag1_ncOBP','lag1_nOPS','lag1_ncOPS']

feature_list_rttm = ['lag1_rtm_ncHR','lag1_rtm_nHR','nage','nheight','POS_1B','POS_2B','POS_3B','POS_SS','POS_OF','ndecade','lag1_rtm_nSLG','lag1_rtm_ncSLG','lag1_rtm_nOBP','lag1_rtm_ncOBP','lag1_rtm_nOPS','lag1_rtm_ncOPS']

ml_comparison = True
if ml_comparison == True :
    # make run with out regression to the mean lag statistics
    machine_learning_runs(df_train, df_test ,feature_list, stats_list,'With Out RTTM','_woRTM.csv')

    # make run with regression to the mean lag statistics
    machine_learning_runs(df_train, df_test ,feature_list_rttm, stats_list, 'RTTM','_wRTM.csv')
else:
    machine_learning_runs_all(df_train, df_test ,feature_list_rttm, stats_list)


#!/usr/bin/env python
# import sys because we need to read and write data to STDIN and STDOUT
import sys
import re

current_node_key = None
source_node_id = 0
node_key = None
node_adjacency_list = []

for line in sys.stdin:

    # filtering lines
    if "#" in line:
        continue
    else:
        line = line.strip()
        node_key = line.split("\t")[0]
        node_value = line.split("\t")[1]
        node_dist_curr = line.split("\t")[2]

    # assigning initial distances
    if int(node_key) == 0:
        node_dist = 0
    else:
        node_dist = 200000

    node_tuple = ("{}:{}".format(node_value, node_dist_curr))

    if current_node_key == node_key:
        current_node_dist = node_dist
        node_adjacency_list.append(node_tuple)
        # print(node_tuple)

    else:
        if current_node_key:
            print('{}\t{}\t{}'.format(current_node_key, current_node_dist, str(node_adjacency_list)[1:-1]))
        node_adjacency_list[:] = []
        current_node_dist = node_dist
        current_node_key = node_key
        node_adjacency_list.append(node_tuple)
        # print(node_tuple)

if current_node_key:
    # print(node_tuple)
    print('{}\t{}\t{}'.format(current_node_key, node_dist, str(node_adjacency_list)[1:-1]))


#!/usr/bin/env python
import argparse

from keras import utils
from keras.datasets import mnist, cifar10

from biometrics_face import model_builder

defaults = {
    'num_classes': 10,
    'epochs': 100,
    'batch_size': 128,
    'use_cnn': True,
}

def main(args):
    # (this_is_here_only_so, you_can_download_the_dataset), (
    # at_home_and_dont_try_to,
    # do_it_on_faculty_network) = cifar10.load_data()
    (train_images, train_labels), (test_images,
                                   test_labels) = mnist.load_data()

    if args.use_cnn:
        train_images = train_images.reshape(60000, 28, 28, 1)
        test_images = test_images.reshape(10000, 28, 28, 1)
    else:
        train_images = train_images.reshape(60000, 784)
        test_images = test_images.reshape(10000, 784)

    train_labels = utils.to_categorical(train_labels, args.num_classes)
    test_labels = utils.to_categorical(test_labels, args.num_classes)

    if args.use_cnn:
        model = model_builder.build_cnn(input_shape=(28, 28, 1))
    else:
        model = model_builder.build_mlp(input_shape=(784, ))

    model.compile(
        optimizer='adam',
        loss='categorical_crossentropy',
        metrics=['accuracy'])

    model.fit(
        train_images,
        train_labels,
        epochs=args.epochs,
        batch_size=args.batch_size,
        validation_data=(test_images, test_labels),
    )

    print('If you see this text, everything is probably okay.')

def parse_arguments():
    parser = argparse.ArgumentParser(
        description='Trains either MLP or CNN model on MNIST dataset')
    parser.add_argument(
        '--num-classes',
        help='Number of classes in the classification problem.',
        type=int,
        default=defaults['num_classes'])
    parser.add_argument(
        '--epochs',
        help='Number of epochs to train.',
        type=int,
        default=defaults['epochs'])
    parser.add_argument(
        '--batch-size',
        help='Batch size',
        type=int,
        default=defaults['batch_size'])
    parser.add_argument(
        '--use-cnn',
        help='True if CNN should be used, False for MLP',
        type=bool,
        default=defaults['use_cnn'])

    return parser.parse_args()

if __name__ == '__main__':
    main(parse_arguments())


def age_allowed_to_date(my_age):
    girl_age = my_age/2 + 7
    return girl_age

input_age = age_allowed_to_date(21)
print(input_age)

def get_gender(sex):
    if sex is "m":
        print("herigo you got dick ^^")
    elif sex is "f":
        print("you are female -_-")
    else:
        print("r you comin from moon ?")

get_gender("m")
get_gender("f")
get_gender("hello")


# Juan Carlos Ramirez
# Port Scanner for remote hosts
import argparse
import socket
import struct
import sys
import threading
import queue
from datetime import datetime

parser = argparse.ArgumentParser( description="Scan's the ports on a specific target")
parser.add_argument("-t", default="",  help="Name of the target")
parser.add_argument("-i", default="",  help="IP of the target")
parser.add_argument("-minPort", default=1, type=int, help="Name of the target")
parser.add_argument("-maxPort", default=65535,
                    type=int,  help="IP of the target")
parser.add_argument("-c", action='store_true',  help="Show Closed Ports")
args = parser.parse_args()

if(args.t == "" and args.i == ""):
    sys.exit(parser.print_help())

if(args.i == ""):
    remoteServer = socket.gethostbyname(args.t)
else:
    remoteServer = socket.gethostbyname(args.i)

def tcpScan(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                        struct.pack("ii", 1, 0))
        sock.settimeout(timeout)

        result = sock.connect_ex((host, port))
        if result == 0:
            print("Port {}:     Open".format(port))
        else:
            if args.c:
                print("Port {}:     Closed/Blocked".format(port))
        sock.close()

    except socket.gaierror:
        sys.exit(host, " could not be resolved. Exiting now")

    except socket.error:
        sys.exit("Couldn't connect to ", host)

timeout = .1

print("~" * 80)
print("Scanning ", remoteServer, " please hold on")
print("~" * 80)

startTime = datetime.now()

def multi_threader_tcp():
    while True:
        host_port = q.get()
        host = host_port[0]
        port = host_port[1]
        tcpScan(host,port)
        q.task_done()

q = queue.Queue()

for x in range(30):
    t = threading.Thread(target=multi_threader_tcp)
    t.daemon = True
    t.start()

for port in range(args.minPort, args.maxPort):
    q.put((remoteServer,port))

q.join()

stopTime = datetime.now()

elapsedTime = stopTime - startTime

print("Scanning competed in: ", elapsedTime)


'''
By:
Xinran Lian, Andrew Ferguson

'''

from __future__ import division
import numpy as np
import pandas as pd
import os
import pickle
from numba import jit
import time

from scipy.special import kl_div
from scipy.spatial import distance

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.axes_grid1 import make_axes_locatable

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable

from sklearn.model_selection import train_test_split
from Bio import SeqIO

##################### Pretreatment #####################

# Read the fasta file
def get_seq(filename, get_header = False):
    assert filename.endswith('.fasta'), 'Not a fasta file.'

    records = list(SeqIO.parse(filename, "fasta"))
    records_seq = [i.seq for i in records]
    headers = [i.description for i in records]
    if get_header == True:
        return records_seq, headers
    else:
        return records_seq

# Output indices of AAs at each position
def potts_index(sequence): # Output all possible AAs on all positions
    for i in range(len(sequence)):
        assert len(sequence[i]) == len(sequence[0])

        aa_at_pos = []
        for i in range(len(sequence[0])):
            tmp_list = []
            for j in range(len(sequence)):
                if (sequence[j][i] in tmp_list) == False:
                    tmp_list.append(sequence[j][i])
            aa_at_pos.append(tmp_list)
        return [''.join(i) for i in aa_at_pos]

# Convert alphabet sequences to one-hot Potts representation.
def convert_potts(sequence, aa_at_pos):
    N = len(sequence) # samples
    n = len(aa_at_pos) # positions
    q_n = np.array([len(i) for i in aa_at_pos]).astype(int)
    length = sum(q_n)

    v_traj_onehot = np.zeros((N,length)).astype(int)
    for j in range(n):
        sumq = sum(q_n[:j])
        for i in range(N):
            pos_to_1 = sumq + aa_at_pos[j].find(sequence[i][j])
            v_traj_onehot[i,pos_to_1] = 1 # set a position as 1
    return v_traj_onehot, q_n

##################### Treatments after training the model #####################
'''
Warning:
convert_nohot and aa2int: Both functions convert alphabet representation of AAs to int representation.
aa2int is only used for plmDCA energy. In other cases we use convert_nohot.

Difference between the two functions is they use different dictionary:
*aa2int* uses *plm_dict.dict_int2aa*, where all 21 AAs (including gap) is correspond to an int number from 0 to 20.
*convert_nohot* uses *aa_at_pos*. This index is based on possibilities of AAs at each position.  AAs not appearing at a position in the whole MSA will not be in the index. This index is designed for the VAE model, to avoid all-zero features.
'''

# Convert alphabet MSA to int representation:
def convert_nohot(sequence_list, q_n):
    sequence_list = sequence_list.reshape([-1,sum(q_n)])
    length = np.size(sequence_list,axis=0)
    real_nothot = np.zeros([length,len(q_n)])

    for i in range(length):
        tmp_seq = sequence_list[i]
        for j in range(len(q_n)):
            start = np.sum(q_n[:j])
            end = np.sum(q_n[:j+1])
            real_nothot[i,j] = np.argmax(tmp_seq[start:end])
    return real_nothot

# Convert int sequences to alphabet.
def convert_alphabet(int_seq, aaindex, q_n):
    seqs_alp=[]
    int_seq = int_seq.reshape([-1,len(q_n)])
    for i in range(len(int_seq)):
        tmpseq=''
        for pos in range(len(int_seq[0])):
            num=int(int_seq[i][pos])
            tmpseq+=aaindex[pos][num]
        #tmpseq=np.array(tmpseq)
        seqs_alp.append(tmpseq)
    return(seqs_alp)

# Make an m × n matrix (arXiv:1712.03346)
# m is the number of amino-acids, n the number of positions considered in the protein alignment.
@jit(nopython=True)
def make_matrix(sequence, n, q_n): # a sequence of interest
    matrix = np.zeros((21,n),np.float64)
    for j in range(n):
        start = np.sum(q_n[:j])
        end = np.sum(q_n[:j+1])
        matrix[:q_n[j],j] = sequence[start:end]
    return matrix

def make_logP(new_potts, p_weight,q_n):
    n = len(q_n)
    return [np.log(np.trace(make_matrix(new_potts[i],n,q_n).T @ make_matrix(p_weight[i],n,q_n))) for i in range(len(new_potts))] - np.log(n)

##################### Generate and analyze new sequences #####################
class plm_dict:
    dict_int2aa = {0:"A",1:"C",2:"D",3:"E",4:"F",5:"G",6:"H",7:"I",8:"K",9:"L",10:"M",11:"N",12:"P",13:"Q",14:"R",15:"S",16:"T",17:"V",18:"W",19:"Y",20:"X"}
    dict_aa2int = {b:a for a, b in dict_int2aa.items()}
    dict_aa2int.update({'-':20})

# Calculate minimum Hamming discance of a sequence from MSA.

# Use this function only when computing plmDCA energy
def aa2int(seq,dict_aa2int):
    '''
    translate seq to seq_int

    **Arguments**
    - seq = sequence string of aa residue one-letter codes
    - dict_aa2int = dictionary of aa one-letter codes to integers
    '''
    seq_int = []
    for i in list(seq):
        seq_int.append(dict_aa2int.get(i))
    seq_int = np.array(seq_int)

    return seq_int

def int2aa(seq_int,dict_int2aa):
    '''
    translate seq_int to seq

    **Arguments**
    - seq_int = sequence string of integers as numpy vector
    - dict_int2aa = dictionary of integers to aa one-letter codes
    '''
    seq = ''.join(dict_int2aa.get(i) for i in seq_int)
    return seq

'''
@jit(nopython=True)
def computeP(seq_int,h,J,M):

    compute the probability associated with a particular integer sequence seq_int

    **arguments**
    - seq_int = sequence string of integers as numpy vector
    - h[ri,i] = KxM vector of external fields
    - J[ri,rj,i,j] = KxKxMxM matrix of pairwise couplings
    - M = no. positions in sequence

    assert len(seq_int) == M

    P=0
    for i in range(M):
        P+=h[seq_int[i],i]
        for j in range(i+1,M):
            P+=J[seq_int[i],seq_int[j],i,j]
    return P #exp(-P)

def record(records, H, J, M):
    records_toreturn = []
    for n in range(len(records)):
        # error checking
        assert len(records[n]) == M

        # translating aa -> int
        seq_int = aa2int(records[n], plm_dict.dict_aa2int)

        # computing probability from DCA Hamiltonian
        P=computeP(seq_int,H,J,M)
        records_toreturn.append(P)
    return np.array(records_toreturn)
'''
def minHamming(seq,ref_list):
    return min(np.count_nonzero(ref_list - seq,axis = 1))

def Hamming_list(seq_list,ref_list):
    return [minHamming(i, ref_list) for i in seq_list]

@jit(nopython=True)
def sample_seq(seed, q, n, q_n, i, v_gen):
    v_samp = np.zeros(q)
    v_samp_nothot = np.zeros(n)
    for j in range(n):
        start = np.sum(q_n[:j])
        end = np.sum(q_n[:j+1])
        np.random.seed(seed) # Change random seed in each iteration.
        v_samp[start:end] = np.random.multinomial(1, v_gen[i,start:end]/np.sum(v_gen[i,start:end]))
        # only throw dice once. Get the AA which was selected.

        v_samp_nothot[j] = np.nonzero(v_samp[start:end])[0][0]
    return v_samp_nothot

# This function is currently unavailable.
def generate(model, seed, q, q_n, n, d, device, n_gen, n_samp, thresh):
    np.random.seed(seed)
    z_gen = np.random.normal(0., 1., (n_gen, d)) #generate normal distribution of random numbers
    data = torch.FloatTensor(z_gen).to(device)
    data = model.decode(data) # Use the decoding layer to generate new sequences.
    v_gen = data.cpu().detach().numpy()
    sample_list = []
    for i in range(n_gen):
        for k in range(n_samp):
            v_samp_nothot = sample_seq(seed+k, q, n, q_n, i, v_gen)
            sample_list.append(v_samp_nothot)
    return sample_list


#Code to simulate Amberlyst RXR
import numpy as np
#import matplotlib.pyplot as plt
from scipy.integrate import odeint
import math
from scipy.optimize import minimize
#from openpyxl import Workbook, load_workbook
import pandas as pd
import scipy.stats as stats
import os
import openpyxl
import time
import pyDOE

#This code has been validated for PE of three parameters against gPROMs
os.chdir('C:/Users/User/Documents/LabVIEW Data/2015 Projects/Combined')
#os.chdir('C:\Users\Conor\OneDrive - University College London\Closed Loop System\Conor Python')

def PE_N_paramFive(filename, DiameterUsed, CatMassUsed, ObjectiveCriteria):
    start=time.time()
    #load data
    exp_data = pd.read_excel(filename)
    performed_exp = exp_data[['Temperature', 'Flowrate', 'Concentration', 'dsphere', 'cat mass']].values   # experimental conditions
    y_m = exp_data[['BAC', 'EBC']].values   # experiment measurements

    #We use a function to make a matrix of experimental conditions
    def Matrix_conditions(performed_exp):
        data = np.zeros([len(performed_exp),len(performed_exp[0,:])])
        for i in range(len(performed_exp)):
            data[i,0] = performed_exp[i,0]
            data[i,1] = performed_exp[i,1]
            data[i,2] = performed_exp[i,2]
            data[i,3] = performed_exp[i,3]
            data[i,4] = performed_exp[i,4]
        return data
    exp_conditions = Matrix_conditions(performed_exp)

    #This code only works for two measurments per experiment
    sigma_BAC = 0.03 # estimate of variance
    sigma_EBC = 0.0165
    sigma = [sigma_BAC, sigma_EBC]

    R = 8.314 # gas constant
    n_theta = 3                            # number of unknown model parameters
    n_y = 2                                # number of measured responses
    n_phi = 3                              # number of design variables
    #ParametersGuess = [14, 6]  #for 1st order model rate=k*CBA
    ParametersGuess = [16, 6, 0.5] # for LH model rate=k*CBA*CetOH/(1+Kw*Cw)^2

    def kinetic_model(c,W,u,theta):
        CBA = c[0] #mol/L
        CEtOH = c[1]
        CEB = c[2] #mol/L
        CW = c[3]

        tempC = u[0] #oC
        flowuLmin = u[1] #uL/min
        InletC = u[2] #mol/L
        dSphere = u[3]*10**(-6) #um

        KP1 = theta[0]
        KP2 = theta[1]
        KW  = theta[2]
        R = 8.314
        pi = math.pi
        Tort = 3.745

        flowLs = flowuLmin*10**(-6)/60 #L/s
        TK=tempC+273.15 #K
        TM=((140+70)/2)+273.15 #K
        rSphere = dSphere/2 #m

        TubeDiameter = 1000*10**(-6) #m
        TubeArea = pi*(TubeDiameter/2)**(2) #m2
        SuperVelocity = (flowLs/1000)/TubeArea #m/s

        kpermass = math.exp(-KP1-KP2*10000*(1/TK-1/TM)/R) #L/g s
        rhocat = 770 #kg/m3
        porosity = 0.32
        kc = 9.7*10**(-5)*SuperVelocity**0.0125 #m/s
        SAsphere = 4*pi*rSphere**2 #m2
        Voloftube1sphere = TubeArea*dSphere #m3
        ac = SAsphere/Voloftube1sphere #m2/m3
        visEtOH = math.exp(-7.3714+2770/(74.6787+TK)) #mPa s
        D = (7.4*10**(-8)*TK*(46.07)**0.5)/(100*100*visEtOH*92.5**0.6) #m2/s
        De = D*porosity/Tort #m2/s
        Thiele = rSphere*math.sqrt(kpermass*rhocat/De)
        eta = (3/(Thiele**2))*(Thiele/math.tanh(Thiele)-1)
        Omega = eta/(1+eta*kpermass*rhocat/(kc*ac))

        rate=1*(kpermass*CBA*CEtOH)/((1+KW*CW)**2)
        #rate=Omega*kpermass*CBA

        dCBAdW = -rate/flowLs
        dCEtOHdW = -rate/flowLs
        dCEBdW = rate/flowLs
        dCWdW = rate/flowLs

        return [dCBAdW, dCEtOHdW, dCEBdW, dCWdW]

    #Function to create model predicted outlet concentrations for a given set of experimental conditions and a given set of Kinetic parameters
    def generatepredictions(ExpCond, theta):
        ConcPredicted=np.zeros([len(ExpCond),2])
        for i in range (0, len(ExpCond)):
            soln = odeint(kinetic_model,[ExpCond[i,2],17.09-1.6824*ExpCond[i,2],0,0],[0,ExpCond[i,4]], mxstep = 3000, args=(ExpCond[i,:],theta))
            CBA = soln[1, 0]
            CEB = soln[1, 2]
            ConcPredicted[i,:] = [CBA, CEB]
        return ConcPredicted
    #CheckGen=generatepredictions(exp_conditions, ParametersGuess)

     #Function to evaluate the objective function (sum of the residuals divided by st dev for a given set of conducted experiments and a given set of kinetic parameters
    def loglikelihood(theta, Measurments, ExpCond):
        ModelPredictions=generatepredictions(ExpCond, theta)
        BAPredict=ModelPredictions[:,0]
        EBPredict=ModelPredictions[:,1]
        BAmeasured=y_m[:,0]
        EBmeasured=y_m[:,1]
        rho_1 = BAmeasured - BAPredict
        rho_2 = EBmeasured - EBPredict
        rho = (rho_1/sigma[0])**2+(rho_2/sigma[1])**2
        residuals = np.sum(rho)
        neg_loglikelihood = math.log(2*math.pi) + 0.5 * (math.log(sigma[0]**2) + math.log(sigma[1]**2)) + 0.5 * residuals
        obj_fun = 0.5 * residuals
        return obj_fun
    #CheckLog=loglikelihood(ParametersGuess, y_m, exp_conditions)

        #Function to get parameter estimate
    def parameter_estimation(thetaguess, measureddata, inputconditions):
        new_estimate = minimize(loglikelihood, thetaguess, method = 'Nelder-Mead', options = {'maxiter':2000}, args=(measureddata, inputconditions,))
        #print "preformed minimisation of log liklihood"
        return new_estimate
    minimisedlog = parameter_estimation(ParametersGuess, y_m, exp_conditions)
    params = minimisedlog.x
    wt_residuals = 2*minimisedlog.fun

        ## Adequacy test/chisquare #
    alpha = 0.05
    confidence_level = 1 - alpha
    dofreedom = (((len(performed_exp)) * n_y) - len(ParametersGuess))
    def chisquare_test(conf_level, dof):
        ref_chisquare = stats.chi2.ppf((conf_level),dof)
        return ref_chisquare
    chisq_ref = chisquare_test(confidence_level, dofreedom)

     ##Create matrix of perturbed parameters to be used later for making information matrix
    Disturbance = 0.01
    def perturbation(epsilon,TrueParams):
        perturbated_matrix = np.zeros([len(TrueParams)+1,len(TrueParams)])
        for j in range(len(TrueParams)):
            for k in range(len(TrueParams)):
                if j==k:
                    perturbated_matrix[j,k] = TrueParams[j] * (1 + epsilon)
                else:
                    perturbated_matrix[j,k] = TrueParams[k]
        for j in range(len(TrueParams)):
            perturbated_matrix[-1,j] = TrueParams[j]
        return perturbated_matrix
    #PerturbedParameterMatrix=perturbation(Disturbance,estimate)

    #Here you need to decide where in the experimental design space to do the sensitivity analysis
    #Examplexp=np.zeros(7)
    #Examplexp[0]=120
    #Examplexp[1]=20
    #Examplexp[2]=1.5
    #Examplexp[3]=825
    #Examplexp[4]=0.0982
    def sensitivity(OneExp, epsilon, TrueParams):
        KPMatrix=perturbation(epsilon,TrueParams)
        PredictedValues= np.zeros([len(KPMatrix),4])
        PredictedMeasurable= np.zeros([len(KPMatrix),2])
        for i in range(len(KPMatrix)):
            Solution = odeint(kinetic_model,[OneExp[2], 17.09-1.6824*OneExp[2], 0, 0], [0,OneExp[4]], mxstep = 3000, args=(OneExp, KPMatrix[i,:]))
            PredictedValues[i,:] = Solution[1,:]
            PredictedMeasurable[i,0]=Solution[1,0]
            PredictedMeasurable[i,1]=Solution[1,2]
        sensitivity_matrix = np.zeros([len(TrueParams),n_y])
        for j in range(len(TrueParams)):
            for k in range(n_y):
                sensitivity_matrix[j,k] = ((PredictedMeasurable[j,k] - PredictedMeasurable[-1,k])/(epsilon*TrueParams[j]))  #divide by eepslion*theta?
        return sensitivity_matrix
    #testsens=sensitivity(Examplexp, Disturbance, params)

    #Make information matrix for a single experiment
    def information(OneExp,TrueParams, epsilon):
        Fisher=np.zeros([len(TrueParams),len(TrueParams)])
        for j in range(n_y):
            sens=sensitivity(OneExp, epsilon, TrueParams)[:,j]
            Fisher = Fisher + (1/(sigma[j]**2)) * np.outer(sens,sens)
        return Fisher
    #testFisher=information(Examplexp, params, Disturbance)    #Why do I have negative information here!!!

    #Here we get Fisher for all N Experiments
    def obs_Fisher(ExpCond,epsilon,TrueParams):
        obs_information = np.zeros([len(ExpCond),len(TrueParams),len(TrueParams)])
        for j in range(len(ExpCond)):
            obs_information[j,:,:] = information(ExpCond[j,:], TrueParams, epsilon)
        overall_obs_Fisher = np.zeros([len(TrueParams),len(TrueParams)])
        for j in range(len(ExpCond)):
            overall_obs_Fisher = overall_obs_Fisher + obs_information[j,:,:]
        return overall_obs_Fisher
    #testobsFisher=obs_Fisher(performed_exp,Disturbance,params)   #Why do I have negative information here!!!

    def obs_covariance(ExpCond,epsilon,TrueParams):
        obs_variance_matrix = np.linalg.inv(obs_Fisher(ExpCond,epsilon,TrueParams))
        return obs_variance_matrix
    Cov=obs_covariance(performed_exp,Disturbance,params)

    def correlation(Covariance):
        correlationmatrix = np.zeros([len(Covariance),len(Covariance)])
        for i in range(len(Covariance)):
            for j in range(len(Covariance)):
                correlationmatrix[i,j] = Covariance[i,j]/(np.sqrt(Covariance[i,i] * Covariance[j,j]))
        return correlationmatrix
    Corr=correlation(Cov)

    def t_test(Covariance, TrueParams, conf_level, dof):
        t_values = np.zeros(len(TrueParams))
        conf_interval = np.zeros(len(TrueParams))
        for j in range(len(TrueParams)):
            conf_interval[j] = np.sqrt(Covariance[j,j]) * stats.t.ppf((1 - ((1-conf_level)/2)), dof)
            t_values[j] = TrueParams[j]/(conf_interval[j])
        t_ref = stats.t.ppf((1-(1-conf_level)),dof)
        return conf_interval,t_values,t_ref
    ConfInt, tvalues, tref=t_test(Cov, params,confidence_level,dofreedom)

    #Here we start MBDoE
    #Note that we only want to design the variables T, C and F. We want to fix cat mass and dsperhe at the same values as previously conducted

    #expected Fisher with 1 new experiment
    def ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon):
        PastFisher=np.linalg.inv(PastCovariance)
        FisherofDesign=information(NewExp, TrueParams, epsilon)
        TotalExpectedFisher=PastFisher+FisherofDesign
        ExpectedCov=np.linalg.inv(TotalExpectedFisher)
        return ExpectedCov
    #TestExpCov=ExpectedCovFunction(Cov, InitialGuessDesign, params, Disturbance)

    def ObjFunction(NewExp, PastCovariance, TrueParams, epsilon, Criteria):
        if Criteria == "A":
            Obj=np.trace(ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon))
        elif Criteria =="D":
            Obj=np.log(np.linalg.det(ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon))) #we take log of determinant
        elif Criteria ==1:
            Obj=ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon)[0,0]
        elif Criteria ==2:
            Obj=ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon)[1,1]
        elif Criteria ==3:
            Obj=ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon)[2,2]
        else:
            e,v=np.linalg.eig(ExpectedCovFunction(PastCovariance, NewExp, TrueParams, epsilon))
            Obj=np.max(e)
        return Obj
    #MarcosExp=[140, 7.954527, 1.55]
    #MarcosObFunctionValue=ObjFunction(MarcosExp, Cov, params, Disturbance, ObjectiveCriteria)

    Variableranges=np.zeros([n_phi,2])
    Variableranges[0,:]=[80, 120]
    Variableranges[1,:]=[15, 60]
    Variableranges[2,:]=[0.9, 1.55]

    #need to set a seed so I get the same results everytime so the work is reproducible
    def LatinGenerator(N_variables, N_sample, VarRanges, dia, cat):
        np.random.seed(1) #This sets the seed for my random functions like the latin generator to make them give the same results everytime.
        sampling=pyDOE.lhs(N_variables, N_sample)
        Designs=np.zeros([N_sample,5])
        Designs[:,3]=dia
        Designs[:,4]=cat
        for i in range (0, N_variables):
            Designs[:,i]=VarRanges[i,0]+sampling[:,i]*(VarRanges[i,1]-VarRanges[i,0])
        return Designs
    NumberofExpInScreen = 10000
    Screening=LatinGenerator(n_phi,NumberofExpInScreen,Variableranges, DiameterUsed, CatMassUsed)

    def FindBestGuess(Designs, PastCovariance, TrueParams, epsilon, Criteria):
        BestObjective=100
        BestDesign=0
        for i in range (0, len(Designs)):
            CriteriaValue=ObjFunction(Designs[i,:], PastCovariance, TrueParams, epsilon, Criteria)
            if CriteriaValue < BestObjective:
                #print "We found a better guess"
                BestObjective = CriteriaValue
                BestDesign = i
        BestGuessDesign=Designs[BestDesign,:]
        return BestGuessDesign
    BestDesignFromScreening=FindBestGuess(Screening, Cov, params, Disturbance, ObjectiveCriteria)

    def MBDoE(NewExp, PastCovariance, TrueParams, epsilon, Criteria, dia, cat):
        new_design=minimize(ObjFunction, NewExp, method = 'SLSQP', bounds = ([Variableranges[0,0],Variableranges[0,1]],[Variableranges[1,0],Variableranges[1,1]],[Variableranges[2,0],Variableranges[2,1]],[dia,dia],[cat,cat]), options = {'maxiter':10000, 'ftol':1e-20}, args = (PastCovariance, TrueParams, epsilon, Criteria,))
        return new_design
    MinimisedMBDoE=MBDoE(BestDesignFromScreening, Cov, params, Disturbance, ObjectiveCriteria, DiameterUsed, CatMassUsed)
    NewDesign=MinimisedMBDoE.x
    Objvalue=MinimisedMBDoE.fun

    #########################################################################################################
    #########################################################################################################

    #Saving to Excel File

    #########################################################################################################
    #########################################################################################################

    #loading files
    wbwrite=openpyxl.load_workbook(filename)
    #print (wb.sheetnames)
    wswrite=wbwrite.active #opens the first sheet in the wb

    row_count = wswrite.max_row
    wswrite['H'+str(row_count)]=params[0] #using the excel numbering system
    wswrite['I'+str(row_count)]=params[1] #using the excel numbering system
    wswrite['J'+str(row_count)]=params[2] #using the excel numbering system
    wswrite['K'+str(row_count)]=wt_residuals #using the excel numbering system
    wswrite['L'+str(row_count)]=chisq_ref #using the excel numbering system
    wswrite['M'+str(row_count)]=tvalues[0] #using the excel numbering system
    wswrite['N'+str(row_count)]=tvalues[1] #using the excel numbering system
    wswrite['O'+str(row_count)]=tvalues[2] #using the excel numbering system
    wswrite['P'+str(row_count)]=tref #using the excel numbering system
    wswrite['Q'+str(row_count)]=ConfInt[0] #using the excel numbering system
    wswrite['R'+str(row_count)]=ConfInt[1] #using the excel numbering system
    wswrite['S'+str(row_count)]=ConfInt[2] #using the excel numbering system

    wswrite['A'+str(row_count+1)]=NewDesign[0] #using the excel numbering system
    wswrite['B'+str(row_count+1)]=NewDesign[1] #using the excel numbering system
    wswrite['C'+str(row_count+1)]=NewDesign[2] #using the excel numbering system
    wswrite['D'+str(row_count+1)]=NewDesign[3] #using the excel numbering system
    wswrite['E'+str(row_count+1)]=NewDesign[4] #using the excel numbering system

    #Saving File
    wbwrite.save(filename)# overwrites without warning. So be careful

    end=time.time()
    runtime=end-start
    #print(runtime)
    return NewDesign[0], NewDesign[1], NewDesign[2], tvalues[0], tvalues[1], tvalues[2], tref


import sqlite3
from csv import reader

#open the correct file
conn = sqlite3.connect('BibleReader.db')

#setting up the cursor
c = conn.cursor()
def create_db():

	#creating a Bible table
	def create_Bible_table():
		create_Bible = '''
		CREATE TABLE IF NOT EXISTS Bible (
		B_id	INTEGER	AUTO INCREMENT,
		tran	CHAR(3)	NOT NULL,
		book	INTEGER	NOT NULL,
		chapter	INTEGER	NOT NULL,
		verse	INTEGER	NOT NULL,
		text	TEXT	NOT NULL,
		PRIMARY KEY (B_id)
		)'''
		c.execute(create_Bible) #remember to make tran relate to code in the metadata table
		conn.commit
	def create_Metadata_table():
		create_Metadata = '''
		CREATE TABLE IF NOT EXISTS Metadata(
		m_id	INTEGER	AUTO INCREMENT,
		code	TEXT NOT NULL,
		PRIMARY KEY (m_id)
		)'''
		c.execute(create_Metadata)
		conn.commit

	#execute inner functions
	create_Bible_table()
	#create_Metadata_table()

create_db()
print("DB created.")

'''
def delete_all_rows():
	print("may or may not delete")

delete_all_rows()
'''

#inserting rows into the Bible table using a csv file
def open_csv(which_tran):
	opened_file = open(which_tran + '.csv')
	read_file = reader(opened_file)
	Bible_table = list(read_file)
	print(Bible_table[0])
	Bible_table = Bible_table[1:]
	return Bible_table

current_tran = 'kjv'
current_dict = open_csv(current_tran)
print("The " + current_tran + ".csv file is open.")

#insert data one line at a time
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 1, 'first')")
'''
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 2, 'second')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 3, 'third')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 4, 'fourth')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 5, 'fifth')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 6, 'sixth')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 7, 'seventh')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 8, 'eighth')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 9, 'ninth')")
c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('kjv', 1, 1, 10, 'tenth')")
'''

'''
#sample data just for something quick to work with
def insert_trash():
	book = 1
	chapter = 1
	verse = 1
	text = ['not', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'ninteenth', 'twentieth']
	try:
		while x < 20:
			c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('" + tran + "', " + book + ", " + chapter + ", " + verse + ", '" + text[verse] + "')") #This causes an error.
			verse += 1
	except sqlite3.OperationalError:
		print("OPERATIONAL ERROR: Row could not inserted.")
	except:
		print("ERROR: Function doesn't work.")

	conn.commit

insert_trash()
'''

'''
#now the data goes into the table in the database file
def insert_Bible_rows(which_dict):
	for row in which_dict:
		tran = current_tran
		book = str(row[1])
		chapter = str(row[2])
		verse = str(row[3])
		text = str(row[4])
		print(text)
		try:
			c.execute("INSERT INTO (tran, book, chapter, verse, text) Bible VALUES ('" + tran + "', " + book + ", " + chapter + ", " + verse + ", '" + text + "')") #This causes an error.
		except sqlite3.OperationalError:
			print("OPERATIONAL ERROR: Row could not inserted.")
		except:
			print("ERROR: Function doesn't work.")
	conn.commit
insert_Bible_rows(current_dict)
'''

'''
#Select text with sql commands
c.execute("SELECT (text) FROM Bible WHERE (book='1', chapter='1', verse='1')")
print(c.fetchall())
print("Here.")
'''

#close everything
print("END")
c.close()
conn.close()