import json

def genera_sottoalbero(fnome,x,fout):
    ''' Funzione che legge file, controlla se e' presente albero con nodo x
        scrive in fout il sottoalbero, se x non c'e' restituisce []
    '''
    alb = leggiFile(fnome)              # leggo flie

    ris = {}                            # dizionario risultato
    # controllo se nodo x e' presente
    if x not in alb:
        salvaFile(ris, fout)            # scrivo su file
        return None                     # interrompo

    ris[x]=alb[x]                   # primo elemento di dizionario
    ls = alb[x].copy()              # creo una copia per non modificare diz
    calcola(alb, ls, ris)           # elementi da inserire
    salvaFile(ris, fout)

def cancella_sottoalbero(fnome,x,fout):
    ''' Funzione che controlla se nodo x e' presente in albero in caso elimina
        tutti x e i suoi figli altrimenti non fa modifiche
    '''
    alb = leggiFile(fnome)              # leggo file

    # se nodo e' presente
    if x in alb:
        ris = {}                        # dizionario nodi da eliminare
        ris[x]=alb[x]                   # primo elemento di dizionario
        ls = alb[x].copy()              # creo una copia per non modificare diz
        calcola(alb, ls, ris)           # elementi da inserire

        # per ogni nodo da eliminare
        for n in ris:
            del alb[n]                  # elimino nodo
        # per ongi chiave in albero
        for k in list(alb.keys()):
            # se x contenuta in nodo
            if alb[k].count(x) > 0:
                alb[k].remove(x)        # elimono figlio x da nodo
                break
    salvaFile(alb, fout)

def dizionario_livelli(fnome,fout):
    ''' Funzione che associa livello dell'albero a tutti i nodi che contiene '''
    alb = leggiFile(fnome)
    ris = {}
    # inzializzo livelli
    for n in range(0, 50):
        ris[n]=[]
    c = 0               # contatore
    rad = radice(alb)   # ricavo radice
    livello(alb, ris, rad.pop(), c)

    elimina = []
    # per ogni livello
    for liv in ris:
        # se e' vuoto
        if ris[liv] == []:
            elimina.append(liv)         # aggiungo a lista da eliminare
        ris[liv].sort()                 # riordino valori
    # per ogni chiave da eliminare
    for liv in elimina:
        del ris[liv]                    # la elimino

    salvaFile(ris, fout)

def dizionario_gradi_antenati(fnome,y,fout):
    ''' Funzione che associa nodo a numero di antenati di grado y '''
    alb = leggiFile(fnome)
    grado = {}
    ris = {}

    # per ogni chiave
    for k in alb:
        grado[k]=len(alb[k])            # associo grado a chiave

    c = 0               # contatore
    rad = radice(alb)   # ricavo radice
    antenati(alb, grado, ris, y, rad.pop(), c)

    salvaFile(ris, fout)

def radice(alb):
    ''' metodo che trova radice dell'albero '''
    figli = set()
    for nodo in alb:
        for f in alb[nodo]:
            figli.add(f)
    return set(alb) - figli

def antenati(alb, grado, ris, y, nodo, c):
    ''' funzione che associa ad ogni chiave il numero di antenati di grado y '''
    ris[nodo]=c         # associo nodo a numero di antenati di grado y
    # se nodo ha figli
    if alb[nodo] != []:
        # per ogni figlio
        for n in alb[nodo]:
            # se e' di grado y
            if grado[nodo] == y:
                antenati(alb, grado, ris, y, n, c+1)
            else:
                antenati(alb, grado, ris, y, n, c)

def livello(alb, ris, nodo, c):
    ''' funzione che associa nodi a livello rispettivo '''
    # associo nodo a livello
    ris[c].append(nodo)

    # se nodo ha figli
    if alb[nodo] != []:
        # ricorsione
        for nodo in alb[nodo]:
            livello(alb, ris, nodo, c+1)

def calcola(alb, ls, ris):
    ''' funzione che inserisce nel dizionario ris nodo x e i suoi figli '''
    if ls == []:                    # nel caso la lista fosse vuota
        return None
    # se nodo non ha figli
    if alb[ls[0]] == []:
        ris[ls[0]]=[]               # salvo nodo con lista vuota
    else:
        ris[ls[0]]=alb[ls[0]]       # salvo nodo con figli
        # per ogni figlio
        for n in alb[ls[0]]:
            ls.append(n)            # aggiungo nodo da visionare a lista
    ls.remove(ls[0])                # elimino nodo visto
    # finche' lista non e' vuota
    if ls != []:
        calcola(alb, ls, ris)

def salvaFile(ris, file):
    ''' Funzione che salva dizionario in formato json '''
    with open(file, 'w') as f:
        json.dump(ris, f)

def leggiFile(file):
    ''' Funzine che legge file e ritorna la sua rappresentazione '''
    with open(file) as j:
        f = json.load(j)
    return f


from xai.brain.wordbase.verbs._ferret import _FERRET

#calss header
class _FERRETS(_FERRET, ):
	def __init__(self,):
		_FERRET.__init__(self)
		self.name = "FERRETS"
		self.specie = 'verbs'
		self.basic = "ferret"
		self.jsondata = {}


from django.contrib.auth.mixins import AccessMixin
from django.shortcuts import redirect

class OwnerAndLoginMixin(AccessMixin):

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_owner:
            return redirect("leads:condor")
        return super().dispatch(request, *args, **kwargs)


import io
import random
from flask import Flask, Response
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
app = Flask(__name__)

@app.route('/plot.png')
def plot_png():
    fig = create_figure()
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')

def moving_average(x, w):
    return np.convolve(x, np.ones(w), 'valid') / w

def create_figure():
    fig = Figure()
    ax = fig.add_subplot(1, 1, 1)
    xs = range(31)
    ys = [random.randint(-5, 5) for x in xs]
    ys = moving_average(ys, 4)
    ax.plot(xs[:28], ys)
    ax.set_title('Mood Tracker Feburary 2021')
    ax.set_xlabel('Day')
    ax.set_ylabel('overall mood (pos/neg thinking)')
    ax.set_xticks(np.arange(28))
    ax.set_xticklabels(np.arange(1,29))
    ax.grid(True)
    return fig

app.run()


from flask import Flask, request, render_template

import base64
import numpy
# import cv2
import os

UPLOAD_FOLDER = "media"

app = Flask(__name__)
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config["imgdir"] = UPLOAD_FOLDER

def load_model():
    class tmp:
        def predict(x):
            print('Predicting for', x)

    return tmp()

MODEL = load_model()

def predict(image):
    return MODEL.predict(image)

@app.route('/upload', methods=["POST"])
def process_image():
    data = request.get_data().decode()
    image_b64 = data["image"]
    image = base64.decodebytes(image_b64)
    result = predict(image)
    return {"result": result}

@app.route('/', methods=["GET", "POST"])
def upload_image():
    if request.method == "GET":
        return render_template("home.html")
    elif request.method == "POST":
        data = request.files['file']
        # filename = secure_filename(file.filename) # save file
        filename = data.filename
        filepath = os.path.join(app.config['imgdir'], filename)
        data.save(filepath)
        # img = cv2.imread(filepath)
        result = 'non-cataract' # predict(img)
        return render_template("result.html", **{"result": result})

@app.route('/home',methods=["GET","POST"])
def homepage():
    if request.method == "GET":
        return render_template("home.html")
    elif request.method == "POST":
        data = request.files['file']
        # filename = secure_filename(file.filename) # save file
        filename = data.filename
        filepath = os.path.join(app.config['imgdir'], filename)
        data.save(filepath)
        # img = cv2.imread(filepath)
        result = 'non-cataract' # predict(img)
        return render_template("result.html", **{"result": result})


import sys
sys.stdin = open("17822_input.txt")

from collections import deque

# 원판 회전 함수
def rotate_plate(X, D, K):
    global N, M, A
    for x in range(X-1, N, X):  # 회전하는 원판 X의 배수
        if D:  # 시계방향
            A[x].rotate(-K)
        else:  # 반시계방향
            A[x].rotate(K)
    return

# flag가 0일 때 호출됨
def control(A):
    global N, M
    plus = 0
    cnt = 0
    for i in range(N):
        for j in range(M):
            if A[i][j]:
                plus += A[i][j]
                cnt += 1
    if cnt:
        avg = plus / cnt
    else:
        avg = 0
    # 이걸로 써도 무관함!
    # try:
    #     avg = plus / cnt
    # except:
    #     avg = 0
    for i in range(N):
        for j in range(M):
            if A[i][j] and avg != 0:
                if A[i][j] > avg:
                    A[i][j] -= 1
                elif A[i][j] < avg:
                    A[i][j] += 1
    return

# 인접한 같은 수 지우기(dfs로 구현)
dr = (-1, 1, 0, 0)
dc = (0, 0, -1, 1)

def remove(sr, sc):
    global A, flag
    flag2 = 0
    S = [(sr, sc)]
    key = A[sr][sc]
    A[sr][sc] = 0
    pr, pc = sr, sc
    while S:
        r, c = S.pop()
        for i in range(4):
            nr = r + dr[i]
            nc = (c + dc[i]) % M
            if not (0 <= nr < N):
                continue
            if not A[nr][nc]:
                continue
            if A[nr][nc] != key:
                continue
            flag = 1
            flag2 = 1
            A[nr][nc] = 0
            pr, pc = nr, nc
            S.append((nr, nc))
    if flag2 == 0:
        A[pr][pc] = key
    return

N, M, T = map(int, input().split())
A = [deque(map(int, input().split())) for _ in range(N)]
# print(A)
for _ in range(T):
    x, d, k = map(int, input().split())
    rotate_plate(x, d, k)
    flag = 0
    for i in range(N):
        for j in range(M):
            if A[i][j]:
                remove(i, j)
    # 인접하면서 수가 같은 것이 없다.
    if flag == 0:
        control(A)

# print(A)
# 최종 배열 A의 모든 원소 합
total = 0
for i in range(N):
    for j in range(M):
        if A[i][j]:
            total += A[i][j]
print(total)


# This is a Golly Python script for generating the initial rows
# when extending a partial result using zfind, qfind, or gfind.
# Instructions:
# 1. Orient the partial result so that it is traveling upwards.
# 2. Select the row that you wish to extend from (for symmetric
#    searches, only select the left half of the row). The search
#    will essentially use that row and the row below it as the
#    initial rows for the search.
# 3. Run the script and input the period and translation.
# 4. The rows will be saved to "initrows.txt", which can be used
#    directly in a zfind or qfind search.
# 5. To extend with gfind, the rows need to be converted into
#    binary numbers (replace "o" with "1" and "." with "0") and
#    entered into the code according to these instructions:
#    http://www.conwaylife.com/forums/viewtopic.php?f=9&t=925#p6776
#    Note: many compilers allow you to use the "0b" prefix for
#    writing numbers in binary.

from glife import rect, validint
import golly as g

def getrow(x, y, width):
    s = ""
    for i in range(width):
        if g.getcell(x + i, y): s += "o"
        else: s += "."
    return s

firstrow = rect(g.getselrect())
if len(firstrow) == 0: g.exit("There is no selection.")
if firstrow.height != 1: g.exit("Incorrect selection dimensions (height must be 1)")
width = firstrow.width

period = g.getstring("Enter the period.")
if not validint(period): g.exit("Period should be a positive integer.")
period = int(period)
if period <= 0: g.exit("Period should be a positive integer.")

offset = g.getstring("Enter the offset (translation).")
if not validint(offset): g.exit("Offset should be a positive integer.")
offset = int(offset)
if offset <= 0: g.exit("Offset should be a positive integer.")
if period <= offset: g.exit("Period must be greater than offset.")

backOff = [-1 for i in range(period)]

i = 0
while True:
    j = offset
    while ((backOff[(i+j)%period] >= 0) and (j < period)): j += 1
    if j == period:
        backOff[i] = period - i
        break
    backOff[i] = j
    i = (i+j)%period

rows = ["" for i in range(2*period)]
k = 0
mp = 0
x = firstrow.x
y = firstrow.y
for i in range(period):
    rows[k] = getrow(x,y - mp,width)
    rows[k + period] = getrow(x,y + 1 - mp,width)
    k += backOff[k]
    if k >= period:
        k -= period
        mp += 1
    g.run(1)

try:
    f = open('initrows.txt', 'w')
    for i in range(2 * period): f.write(rows[i] + "\n")
    f.close()
except:
    g.warn("Unable to save file.")


# Copyright 2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

import astakos.oa2.models as oa2_models

from astakos.oa2.backends import base as oa2base
from astakos.oa2.backends import base as errors

from django import http
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.core.urlresolvers import reverse
from django.conf.urls.defaults import patterns, url
from django.http import HttpResponseNotAllowed
from django.utils.encoding import smart_str, iri_to_uri
from django.views.decorators.csrf import csrf_exempt

from synnefo.lib import join_urls
from synnefo.util import urltools

import urllib

import logging
logger = logging.getLogger(__name__)

class DjangoViewsMixin(object):

    def auth_view(self, request):
        oa2request = self.build_request(request)
        oa2response = self.authorize(oa2request, accept=False)
        return self._build_response(oa2response)

    @csrf_exempt
    def token_view(self, request):
        if request.method != 'POST':
            return HttpResponseNotAllowed(['POST'])

        oa2request = self.build_request(request)
        oa2response = self.grant_token(oa2request)
        return self._build_response(oa2response)

class DjangoBackendORMMixin(object):

    def get_client_by_credentials(self, username, password):
        try:
            return oa2_models.Client.objects.get(identifier=username,
                                                 secret=password)
        except oa2_models.Client.DoesNotExist:
            raise errors.InvalidClientID("No such client found")

    def get_client_by_id(self, clientid):
        try:
            return oa2_models.Client.objects.get(identifier=clientid)
        except oa2_models.Client.DoesNotExist:
            raise errors.InvalidClientID("No such client found")

    def get_authorization_code(self, code):
        try:
            return oa2_models.AuthorizationCode.objects.get(code=code)
        except oa2_models.AuthorizationCode.DoesNotExist:
            raise errors.OA2Error("No such authorization code")

    def get_token(self, token):
        try:
            return oa2_models.Token.objects.get(code=token)
        except oa2_models.Token.DoesNotExist:
            raise errors.OA2Error("No such token")

    def delete_authorization_code(self, code):
        code.delete()
        logger.info(u'%r deleted' % code)

    def delete_token(self, token):
        token.delete()
        logger.info(u'%r deleted' % token)

    def check_credentials(self, client, username, secret):
        if not (username == client.get_id() and secret == client.secret):
            raise errors.InvalidAuthorizationRequest("Invalid credentials")

class DjangoBackend(DjangoBackendORMMixin, oa2base.SimpleBackend,
                    DjangoViewsMixin):

    code_model = oa2_models.AuthorizationCode.objects
    token_model = oa2_models.Token.objects
    client_model = oa2_models.Client.objects

    def _build_response(self, oa2response):
        response = http.HttpResponse()
        response.status_code = oa2response.status
        response.content = oa2response.body
        for key, value in oa2response.headers.iteritems():
            response[smart_str(key)] = smart_str(value)
        return response

    def build_request(self, django_request):
        params = {
            'method': django_request.method,
            'path': django_request.path,
            'GET': django_request.GET,
            'POST': django_request.POST,
            'META': django_request.META,
            'secure': settings.DEBUG or django_request.is_secure(),
            #'secure': django_request.is_secure(),
        }
        # TODO: check for valid astakos user
        if django_request.user.is_authenticated():
            params['user'] = django_request.user
        return oa2base.Request(**params)

    def get_url_patterns(self):
        _patterns = patterns(
            '',
            url(r'^%s/?$' % join_urls(self.endpoints_prefix,
                                      self.authorization_endpoint.rstrip('/')),
                self.auth_view,
                name='%s_authenticate' % self.id),
            url(r'^%s/?$' % join_urls(self.endpoints_prefix,
                                      self.token_endpoint.rstrip('/')),
                self.token_view,
                name='%s_token' % self.id),
        )
        return _patterns

    def is_uri(self, string):
        validator = URLValidator()
        try:
            validator(string)
        except ValidationError:
            return False
        else:
            return True

    def get_login_uri(self):
        return reverse('login')

    @staticmethod
    def urlencode(params):
        if hasattr(params, 'urlencode') and \
                callable(getattr(params, 'urlencode')):
            return params.urlencode()
        for k in params:
            params[smart_str(k)] = smart_str(params.pop(k))
        return urllib.urlencode(params)

    @staticmethod
    def normalize(url):
        return urltools.normalize(iri_to_uri(url))

class AstakosBackend(DjangoBackend):
    pass


# -*- encoding: ascii -*-
# Python 2 and 3 compatible
from __future__ import division, absolute_import, print_function
from prga.compatible import *

from prga.util import enable_stdout_logging, uno
from prga.flow.context import ArchitectureContext
from prga.exception import PRGAAPIError

from prga_tools.util import find_verilog_top, parse_io_bindings, parse_parameters
from prga_tools.iobind import iobind
from prga_tools.ysgen import generate_yosys_script
from prga_tools.bitchain.simproj.tbgen import generate_testbench_wrapper
from prga_tools.bitchain.simproj.mkgen import generate_makefile

import argparse
import logging
import jinja2 as jj
import os

_logger = logging.getLogger(__name__)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
            description="Simulation project wizard for bitchain-style configuration circuitry")

    parser.add_argument('context', type=str, help="Pickled architecture context object")

    parser.add_argument('-c', '--compiler', type=str, choices=['vcs', 'iverilog'], dest='compiler', default="vcs",
            help="Verilog compiler used to build the simulator")
    parser.add_argument('--fix_io', type=str, dest="io",
            help="Partial or full assignments of IO pads")

    parser.add_argument('-t', '--testbench', type=str, nargs='+', dest="testbench",
            help="Testbench file(s) for behavioral model")
    parser.add_argument('--testbench_top', type=str,
            help="Top-level module name of the testbench. Required if the testbench comprises multiple files/modules")
    parser.add_argument('--testbench_includes', type=str, nargs="+", default=[],
            help="Include directories for the testbench")
    parser.add_argument('--testbench_defines', type=str, nargs="+", default=[],
            help="Macros for the testbench. Use MACRO for valueless macro, and MACRO=VALUE for macros with value")
    parser.add_argument('--testbench_parameters', type=str, nargs="+", default=[],
            help="Parameters for the testbench: PARAMETER0=VALUE0 PARAMETER1=VALUE1 ...")
    parser.add_argument('--testbench_plus_args', type=str, nargs="+", default=[],
            help="Plus arguments to run the testbench. Use ARG for valueless args, and ARG=VALUE for args with value")

    parser.add_argument('-m', '--model', type=str, nargs='+', dest="model",
            help="Source file(s) for the target design")
    parser.add_argument('--model_top', type=str,
            help="Top-level module name of the target design. Required if the design comprises multiple files/modules")
    parser.add_argument('--model_includes', type=str, nargs="+", default=[],
            help="Include directories for the target design")
    parser.add_argument('--model_defines', type=str, nargs="+", default=[],
            help="Macros for the target design. Use MACRO for valueless macro, and MACRO=VALUE for macros with value")
    parser.add_argument('--model_parameters', type=str, nargs="+", default=[],
            help="Parameters for the behavioral model: PARAMETER0=VALUE0 PARAMETER1=VALUE1 ...")

    parser.add_argument('--makefile', type=str,
            help="Name of the generated Makefile. 'Makefile' by default")
    parser.add_argument('--wrapper', type=str,
            help="Name of the generated testbench wrapper. 'TESTBENCH_wrapper.v' by default")
    parser.add_argument('--yosys_script', type=str,
            help="Name of the generated design-specific synthesis script. 'synth.ys' by default")

    args = parser.parse_args()
    enable_stdout_logging(__name__, logging.INFO)

    # get verilog template
    env = jj.Environment(loader=jj.FileSystemLoader(
        os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates'), ))

    _logger.info("Unpickling architecture context: {}".format(args.context))
    context = ArchitectureContext.unpickle(args.context)
    channel_width = 2 * sum(sgmt.width * sgmt.length for sgmt in itervalues(context.segments))

    _logger.info("Reading target design ...")
    if args.model is None:
        raise PRGAAPIError("Source file(s) for target design not given")
    model_top = find_verilog_top(args.model, args.model_top)
    model_top.parameters = parse_parameters(args.model_parameters)

    _logger.info("Reading testbench ...")
    if args.testbench is None:
        raise PRGAAPIError("Source file(s) for testbench not given")
    testbench_top = find_verilog_top(args.testbench, args.testbench_top)
    testbench_top.parameters = parse_parameters(args.testbench_parameters)

    _logger.info("Assigning IO ...")
    io_assignments = iobind(context, model_top,
            parse_io_bindings(args.io) if args.io is not None else {})
    ostream = open('io.pads', 'w')
    for name, (x, y, subblock) in iteritems(io_assignments):
        ostream.write("{} {} {} {}\n".format(name, x, y, subblock))

    _logger.info("Generating testbench wrapper ...")
    wrapper = uno(args.wrapper, '{}_wrapper.v'.format(testbench_top.name))
    generate_testbench_wrapper(context, env.get_template('tb.tmpl.v'), wrapper, testbench_top, model_top, io_assignments)

    _logger.info("Generating design-specific synthesis script ...")
    script = uno(args.yosys_script, 'synth.ys')
    generate_yosys_script(open(script, 'w'), args.model, model_top, context._yosys_script)

    _logger.info("Generating Makefile ...")
    makefile = uno(args.makefile, 'Makefile')
    ostream = open(makefile, 'w')
    generate_makefile(args.context, env.get_template('tmpl.Makefile'), ostream,
            testbench_top, args.testbench, model_top, args.model, script,
            channel_width, context._vpr_archdef, context._vpr_rrgraph,
            'io.pads', context._verilog_sources, wrapper, args.compiler, args.testbench_plus_args,
            args.testbench_includes, args.testbench_defines, args.model_includes, args.model_defines)

    _logger.info("Simulation project generated. Bye")


#!/usr/bin/python3.5
import os
import csv
import datetime
import time
import json

print("""
-----------------------------
Starting automated-speedtests
-----------------------------
""")

ping = False
down = False
up = False
img = False
tests = 0

with open('/home/pi/automated-speedtests/config.json', 'r') as f:
    config = json.load(f)

def pingTest():
    hostname = config['hostname']
    response = os.system("ping -c 1 " + hostname)
    if response == 0:
        pingResult = True
    else:
        pingResult = False

    return pingResult

def speedTest(ping, down, up, img, tests):
    print("\nConducting speed test...")
    speedTestOutput = os.popen("python " + config['speedtestPath'] + " --simple --share").read()
    print("Speed test complete")

    lines = speedTestOutput.split("\n")
    ts = time.time()
    date = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")

    print("\n------------------------------------------------------")
    print(date + "\n" + speedTestOutput + "------------------------------------------------------\n")
    #Set speeds to 0 if speedtest-cli couldn't connect
    if "Cannot" in speedTestOutput:
        ping = 100
        down = 0
        up = 0
        img = "noimg"

    #Extract values for ping, download and upload
    else:
        ping = lines[0].split(' ')[1]
        down = lines[1].split(' ')[1]
        up = lines[2].split(' ')[1]
        img = lines[3].split(' ')[2]

    #Save the data to file for local network plotting
    fileSpeedResults = open(config['webserverPath'] + "/speedresults.csv", 'a')
    writer = csv.writer(fileSpeedResults)
    writer.writerow((date, ping, down, up))
    fileSpeedResults.close()

    #save just latest value for status display
    with open('/home/pi/automated-speedtests/latest.csv', 'w') as latest:
        latest.write(date + ',' + ping + ',' + down + ',' + up)

    ping = float(ping)
    down = float(down)
    up = float(up)

    tests += 1

    return(ping, down, up, img, tests)

downtime = 0
start_time = time.time()
pingResult = pingTest()

while pingResult == False:
    downtime = time.time() - start_time
    print("No network connection detected")
    pingResult = pingTest()

if pingResult == True:
    if downtime > 0:
        print("Network connection re-established. Downtime: ", downtime)
    else:
        print("Network connection detected")
        ping, down, up, img, tests = speedTest(ping, down, up, img, tests)


# coding: utf-8

# In[73]:

import pandas as pd
import numpy as np
from collections import defaultdict
from scipy.stats import hmean
from scipy.spatial.distance import cdist
from scipy import stats
import numbers
from sklearn.linear_model import LinearRegression

# In[74]:

def drop_na(df, axis = 'row'):
        row = set([])
        cols = set([])
        for col in df.columns:
            for i in range(len(df[col])):
                if pd.isnull(df.loc[i, col]):
                    row.add(i)
                    cols.add(col)
        if axis == 'row':
            df = df.drop(row, axis = 0)
        else:
            df = df.drop(cols, axis = 1)
        df.index = list(range(df.shape[0]))
        return df

# In[75]:

def fill_na(data, fill = 'mean'):
        data = pd.DataFrame(data)
        for col in data.columns:
            if fill == 'mean':
                tmp = data[col].mean()
            if fill =='median':
                tmp = data[col].median()
            if fill == 'mode':
                tmp = data[col].mode()[0]
            for i in range(len(data[col])):
                if pd.isnull(data.loc[i, col]):
                    data.loc[i, col] = tmp
        return data

# In[8]:

def normal(data):
    data = pd.DataFrame(data)
    for col in data.columns:
        data[col] = (data[col] - data[col].mean())/data[col].std()
    return data

# In[9]:

def scal(data):

    data = pd.DataFrame(data)
    for col in data.columns:
        data[col] = (data[col] - data[col].min())/(data[col].max() - data[col].min())
    return data


# Script by Carla Silva and Inês Dutra 2020 :: Graph Coloring Classical Version

""" Graph Coloring Problem

    Formulation of the problem for a graph G=(V,E) with a number of colors n.

"""

from pyqubo import Array, solve_qubo, Constraint
import matplotlib.pyplot as plt
import networkx as nx
import time
import sys
import random
import numpy as np
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import neal
import pandas as pd

def alpha(n,h):
  return(n+h)

def beta(n,alfa,h):
  return(((n**3+n**2+1)*alfa)+h)

def exp1(n, vc, B):
    exp = 0.0
    for i in range(n):
        for k in range(n):
            for kl in range(n):
                if (k != kl):
                    exp += Constraint(vc[i,k]*vc[i,kl], label="exp")
    exp = B*exp
    return(exp)

def exp2(n, vc, A):
    exp = 0.0
    for i in range(n):
      for k in range(n):
          exp += Constraint(1-vc[i,k], label="exp")
    exp = A*exp
    return(exp)

def exp3(n, vc, neigh, A):
    exp = 0.0
    for i in range(n):
        for il in range(n):
            if (i != il):
                for k in range(n):
                   exp += Constraint(vc[i,k]*vc[il,k]*neigh[i,il], label="exp")
    exp = A*exp
    return(exp)

def exp4(n, vc, c, A):
    exp = 0.0
    for i in range(n):
      for k in range(n):
        exp += Constraint(vc[i,k]*(1-c[k]), label="exp")
    exp = A*exp
    return(exp)

def exp5(n, c):
    exp = 0.0
    for k in range(n):
        exp += c[k]
    return(exp)

def col(n, decoded_solution):
    # Obtain colors of each vertex
    colors = [0 for i in range(n)]
    for i in range(n):
        for k in range(n):
          if decoded_solution['vc'][i][k] == 1:
            colors[i] = k
            break
    return(colors)

def graph(G, colors, n, A, B):
    # Plot graph after coloring
    f = plt.figure()
    colorlist = random.sample(list(sns.color_palette('hls')), n)
    nx.draw_networkx(G, node_color=[colorlist[colors[node]] for node in G.nodes], node_size=400, font_weight='bold', font_color='w')
    plt.axis("off")
    f.savefig('fig-n'+str(n)+'A'+str(A)+'B'+str(B)+'.pdf', bbox_inches='tight')
    dictionaryColors = dict(zip(list(G.nodes), [colorlist[colors[node]] for node in G.nodes]))
    return dictionaryColors

if __name__ == "__main__":

    n = int(sys.argv[1]) # Colors
    A = int(sys.argv[2]) # Alpha
    B = int(sys.argv[3]) # Beta

    h = 0.0000005 #small number

    #Test A and B equals alpha and beta
    #A = alpha(n,h)
    #B = beta(n,A,h)

    orig_stdout = sys.stdout

    f = open('graphColoringClassicalResults-n'+str(n)+'A'+str(A)+'B'+str(B)+'.txt', 'w')
    sys.stdout = f

    print("--------------------------------------------------------------------")
    print("\n# GRAPH COLORInG PROBLEM WITH n COLOURS On CLASSICAL SOLVER #\n")
    print("--------------------------------------------------------------------")

    G = nx.erdos_renyi_graph(n=n, p=0.5, seed=123, directed=False)

    print("Is graph connected?",nx.is_connected(G))

    E = G.edges

    neigh = nx.adjacency_matrix(G).todense()

    # Prepare a binary vector

    vc = Array.create('vc', (n, n), 'BINARY')

    c = Array.create('c', (n), 'BINARY')

    print("--------------------------------------------------------------------")
    print("1st expression:")
    print("--------------------------------------------------------------------")
    print(exp1(n, vc, B))

    print("--------------------------------------------------------------------")
    print("2nd expression:")
    print("--------------------------------------------------------------------")
    print(exp2(n, vc, A))

    print("--------------------------------------------------------------------")
    print("3rd expression:")
    print("--------------------------------------------------------------------")
    print(exp3(n, vc, neigh, A))

    print("--------------------------------------------------------------------")
    print("4th expression:")
    print("--------------------------------------------------------------------")
    print(exp4(n, vc, c, A))

    print("--------------------------------------------------------------------")
    print("5th expression:")
    print("--------------------------------------------------------------------")
    print(exp5(n, c))

    # Define hamiltonian H
    H = exp1(n, vc, B) + exp2(n, vc, A) + exp3(n, vc, neigh, A) + exp4(n, vc, c, A) + exp5(n, c)

    # Compile model
    model = H.compile()

    # Create QUBO
    qubo, offset = model.to_qubo()

    print("--------------------------------------------------------------------")
    print("\nQUBO:\n")
    print("--------------------------------------------------------------------")

    print(qubo)

    start_time = time.time()

    nr = 10000
    c = max(qubo.values())
    max_abs_value = float(max(abs(v) for v in qubo.values()))
    scale_qubo = {k: float(v) / max_abs_value for k, v in qubo.items()}
    sa = neal.SimulatedAnnealingSampler()
    sa_computation = sa.sample_qubo(scale_qubo, num_reads=nr, beta_range=(0.01,1), offset=offset, num_sweeps=5000, seed=123, chain_strength=c)

    elapsed_time = time.time() - start_time

    print("--------------------------------------------------------------------")
    print("\nCLASSICAL RESULTS:\n")
    print("--------------------------------------------------------------------")

    df = []
    for a,b,c in sa_computation.record:
        decoded_solution, broken, energy = model.decode_solution(a, vartype='BINARY')
        if not broken:
            d = 0
        else:
            d = broken["exp"]["penalty"]
        for key in range(0,n):
            decoded_solution['c']['c'+str(key)] = decoded_solution['c'].pop(key)
        for i in range(0,n):
            decoded_solution['vc']['vc'+str(i)] = decoded_solution['vc'].pop(i)
        for i in range(0,n):
            for j in range(0,n):
                decoded_solution['vc'].update( {'vc'+str(i)+str(j) : decoded_solution['vc']['vc'+str(i)][j]} )
            decoded_solution['vc'].pop('vc'+str(i))
        decoded_solution['c'].update(decoded_solution['vc'])
        df.append({"Sample": decoded_solution['c'], "Energy": energy, "Occurrences": c, "Broken chains": d})

    df = pd.DataFrame(df)
    df.to_csv('GC'+str(n)+'A'+str(A)+'B'+str(B)+'.csv',index=False)
    pd.set_option('display.float_format', lambda x: '%.20f' % x)
    pd.options.display.max_colwidth = 10000
    print(df.to_string(index=False))

    print("--------------------------------------------------------------------")
    print("\nSAMPLE WITH MINIMUM ENERGY:\n")
    print("--------------------------------------------------------------------")

    best = np.argmin(sa_computation.record.energy)
    best_solution = list(sa_computation.record.sample[best])

    print(dict(zip(sa_computation.variables, best_solution)))

    decoded_solution, broken, energy = model.decode_solution(best_solution, vartype="BINARY")
    print("number of broken constraint = {}".format(len(broken)))
    print(broken)
    print("energy = {}".format(energy))

    e = 99999
    for a,b,c in sa_computation.record:
        decoded_solution, broken, energy = model.decode_solution(a, vartype='BINARY')
        if energy < e:
            decoded_solution1 = decoded_solution
            e = energy

    # Match colors with each node
    colors = col(n, decoded_solution1)

    # Plot the colored graph
    nodesColor = graph(G, colors, n, A, B)

    print("--------------------------------------------------------------------")
    print("\nTIME (sec):\n")
    print("--------------------------------------------------------------------")
    print(elapsed_time,"All results",elapsed_time/nr,"One result")

    print("--------------------------------------------------------------------")
    print("\nList of graph colors:\n")
    print("--------------------------------------------------------------------")
    print(nodesColor)

    print("--------------------------------------------------------------------")
    print("\nNumber of nodes and number of colors:\n")
    print("--------------------------------------------------------------------")
    print(len(nodesColor)," nodes and ",len(set(list(nodesColor.values())))," colors")

    sys.stdout = orig_stdout
    f.close()


#from flask import Blueprint
import pandas as pd
import numpy as np
#import json
#app = Flask(__name__)
#cm = Blueprint('cm', __name__)
#@cm.route("/",methods=['GET']) # 'http::/www.google.com/'
def calculatecm():
    n=50
    df = pd.read_csv("train.csv")
    X = df['X']
    Y = df['Y']
    xm = np.mean(X)
    ym = np.mean(Y)
    ssxy = np.sum(X*Y) - n*xm*ym
    ssxx = np.sum(X**2) - n*(xm**2)

    m = ssxy/ssxx
    c = ym - m*xm

    return c, m


'''
Loads the help frame for the users login
'''
# for logging events
import logging
# For the GUI
import tkinter
# For opening the wiki
import webbrowser

# To take the user back to the login screen
from scr.menus.login_menu import main_login
# For title creation
from scr.menus.title import Title

class Help(tkinter.Frame):  # pylint: disable=too-many-ancestors
    '''
    Loads all of the help screens methods
    '''

    def __init__(self, settings_path, colour_data, parent, *args, **kwargs):
        '''
        Loads the help frame of the GUI
        '''
        logging.info("Loading help frame")
        # The the relevant frame methods
        tkinter.Frame.__init__(self, parent, *args, **kwargs)

        self.settings_path = settings_path

        self.colour_data = colour_data

        self.parent = parent

        self.config(bg=self.colour_data["background"])

        Title("Help:", self.colour_data, self).pack(fill=tkinter.X, expand=True,
                                                    side=tkinter.TOP, padx=5, pady=1)

        # The main help text container
        help_message = (
            "Welcome to Login Access Help, if you have forgeten your "
            "password please press the password rest button below. "
            "If you need help with loging in, creating an account or anything else "
            "please take a look at the wiki by pressing the button below. "
            "Thank you\n"
        )
        message = tkinter.Message(
            self,
            text=help_message,
            bg=self.colour_data["background"],
            fg=self.colour_data["foreground"],
            font=self.colour_data["font"],
            anchor=tkinter.W
        )
        message.pack(fill=tkinter.BOTH, expand=True,
                     side=tkinter.TOP, padx=5, pady=3)
        message.bind(
            "<Configure>", lambda e: message.config(width=e.width-10))

        Buttons(self.settings_path, self.parent, self.colour_data, self).pack(
            fill=tkinter.X, expand=True, side=tkinter.TOP, padx=5, pady=1)

class Buttons(tkinter.Frame):  # pylint: disable=too-many-ancestors
    '''
    Loads all of the help screens buttons
    '''

    def __init__(self, settings_path, top_parent, colour_data, parent, *args, **kwargs):
        '''
        Loads the button frame of the GUI
        '''
        logging.info("Loading help buttons")
        # The the relevant frame methods
        tkinter.Frame.__init__(self, parent, *args, **kwargs)

        self.colour_data = colour_data

        self.settings_path = settings_path

        self.top_parent = top_parent
        self.parent = parent

        self.config(bg=self.colour_data["background"])

        # Back button
        tkinter.Button(
            self,
            text="Back",
            bg=self.colour_data["btn_background"],
            activebackground=self.colour_data["btn_active"],
            fg=self.colour_data["foreground"],
            font=self.colour_data["font"],
            command=lambda: self.back()  # pylint: disable=unnecessary-lambda
        ).pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=True, padx=2, pady=2)

        # Wiki butten to load the full github wiki
        tkinter.Button(
            self,
            text="Wiki",
            bg=self.colour_data["btn_background"],
            activebackground=self.colour_data["btn_active"],
            fg=self.colour_data["foreground"],
            font=self.colour_data["font"],
            command=lambda: self.load_wiki()  # pylint: disable=unnecessary-lambda
        ).pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=True, padx=2, pady=3)

        # Password reset button
        tkinter.Button(
            self,
            text="Reset Password",
            bg=self.colour_data["btn_background"],
            activebackground=self.colour_data["btn_active"],
            fg=self.colour_data["foreground"],
            font=self.colour_data["font"],
            command=lambda: self.reset_password()  # pylint: disable=unnecessary-lambda
        ).pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=True, padx=2, pady=3)

    def back(self):
        '''
        Takes the user back to the login screen
        '''
        logging.info("Exiting the help menu")
        self.parent.destroy()
        main_login.LoginMenu(self.settings_path, self.top_parent).pack(
            fill=tkinter.BOTH,
            expand=True
        )

        return

    def load_wiki(self):  # pylint: disable=no-self-use
        '''
        Opens the github wiki page
        https://github.com/Elephant34/Login-Access/wiki
        '''
        logging.info("Loading the wiki page")

        webbrowser.open(
            "https://github.com/Elephant34/Login-Access/wiki/")

        return

    def reset_password(self):
        '''
        Loads the settings for reseting a users password
        '''

        # BUG- Work in progress

        return


# -*- coding: utf-8 -*-

# (The MIT License)
#
# Copyright (c) 2015 Kura
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import re
from setuptools import (find_packages, setup)
import sys

desc = "Scrape a website"
long_desc = open('README.rst').read() + "\n\n" + open('CHANGES.rst').read()
long_desc = re.sub(r":[a-z]*:`", "`", long_desc)

entry_points = {
    'console_scripts': [
        'orbweaver = orbweaver:crawl',
    ]
}

setup(name='orbweaver',
      version='0.0.0',
      url='',
      author='Kura',
      author_email='kura@kura.io',
      maintainer='Kura',
      maintainer_email='kura@kura.io',
      description=desc,
      long_description=long_desc,
      license='MIT',
      platforms=['linux'],
      packages=find_packages(exclude=["*.tests"]),
      install_requires=['requests', 'blessings', 'beautifulsoup4', ],
      requires=['requests', 'blessings', 'beautifulsoup4', ],
      provides=['orbweaver', ],
      keywords=['spider', ],
      entry_points=entry_points,
      classifiers=[
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
      ],
      zip_safe=True,
      )


class Solution(object):
    def isPalindrome(self, x):
        if x < 0: return False
        if 0<= x <= 9: return True
        if x % 10 == 0: return False
        val = 0
        tmp = x
        while tmp:
            val *= 10
            val += int(tmp % 10)
            tmp = tmp // 10
        return val == x
'''
转字符串解法：
1. 双指针
2. a[::-1] = a

不转字符串：
1. 我的解法， 转换成一个翻过来的 这样的话复杂度为O(n)
但是我的解法要处理溢出
2. 只翻转一半然后就判断  复杂度变为 O(n//2)

'''
class Solution(object):
    def isPalindrome(self, x):
        if x < 0: return False
        if 0<= x <= 9: return True
        if x % 10 == 0: return False
        rx = 0
        while x > rx:
            rx *= 10
            rx += int(x % 10)
            x = x // 10
        return rx == x or rx // 10 == x
a = Solution()
print(a.isPalindrome(10))


from unittest import TestCase

from Client import Client
from sys import getsizeof

class ClientTestCase(TestCase):

    def test_var(self):
        client = Client(167,5578342726791879)
        client._id = 157
        self.assertEqual(client._id,157)

    def test_change_private_argument_not_properly(self):
        client=Client(167,5578342726791879)
        client.change_private_argument_not_properly(5578323212125656)
        self.assertRaises(AttributeError,client.change_private_argument_not_properly(5578323212125656))

    def test_change_private_argument(self):
        client = Client(167, 5578342726791879)
        client.change_private_argument(5578342726791877)
        self.assertEqual(client._Client__card_number, 5578342726791877)

    def test_memory_optimizaion(self):
        client = Client(167, 5578342726791879)
        a = getsizeof(client.__slots__)
        b = getsizeof(client.__dict__)
        self.assertTrue(a<b)

    def test_different_arguments_in_memory(self):
        client = Client(167, 5578342726791879)
        dict_keys = client.__dict__.keys()
        first_arg_in_dict = list(dict_keys)[0]
        self.assertNotIn(first_arg_in_dict, client.__slots__)


import numpy as np
import cv2
from skimage import exposure
from sklearn.utils import shuffle as shuffle_data

class BatchIterator(object):
    def __init__(self, batch_size, shuffle):
        self.batch_size = batch_size
        self.shuffle = shuffle

    def __call__(self, X, y=None):
        n_obs = X.shape[0]

        if y is not None:
            assert n_obs == y.shape[0], 'Different number of labels and images.'
            if self.shuffle: X, y = shuffle_data(X, y)

            for batch in range(0, n_obs, self.batch_size):
                batch_x = X[batch:min(batch + self.batch_size, n_obs), ...]
                batch_y = y[batch:min(batch + self.batch_size, n_obs), ...]
                yield batch_x, batch_y
        else:
            for batch in range(0, n_obs, self.batch_size):
                yield X[batch:min(batch + self.batch_size, n_obs), ...]

def preprocess_data(X, y=None):
    # Convert to grayscale, e.g. single Y channel
    X = 0.299 * X[:, :, :, 0] + 0.587 * X[:, :, :, 1] + 0.114 * X[:, :, :, 2]
    # Scale features to be in [0, 1]
    X = (X / 255.)

    # Apply localized histogram localization
    for i in range(X.shape[0]):
        X[i] = exposure.equalize_adapthist(X[i])

    if y is not None:
        # Convert to one-hot encoding. Convert back with `y = y.nonzero()[1]`
        y = np.eye(43)[y]
        # Shuffle the data
        X, y = shuffle_data(X, y)

    # Add a single grayscale channel
    X = X.reshape(X.shape + (1,))
    return X, y

def _transform_image(image, angle, shear, translation):
    rows, cols, color_channels = image.shape
    rotation_matrix = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)

    trans_x = translation * np.random.uniform() - translation / 2
    trans_y = translation * np.random.uniform() - translation / 2
    translation_matrix = np.array([[1, 0, trans_x], [0, 1, trans_y]]).astype('float32')

    pts1 = np.array([[5, 5], [20, 5], [5, 20]]).astype('float32')

    pt1 = 5 + shear * np.random.uniform() - shear / 2
    pt2 = 20 + shear * np.random.uniform() - shear / 2

    pts2 = np.float32([[pt1, 5], [pt2, pt1], [5, pt2]])

    shear_matrix = cv2.getAffineTransform(pts1, pts2)

    image = cv2.warpAffine(image, rotation_matrix, (cols, rows))
    image = cv2.warpAffine(image, translation_matrix, (cols, rows))
    image = cv2.warpAffine(image, shear_matrix, (cols, rows))

    return image

def _expand_class(images, n_obs):
    images_to_create = n_obs - images.shape[0]
    transformed_images = [_transform_image(images[i, ...], 20, 10, 5)
                          for i in np.random.randint(low=0, high=images.shape[0], size=images_to_create).tolist()]

    transformed_images = np.array(transformed_images)
    transformed_images = transformed_images[..., np.newaxis]
    expanded_class = np.concatenate((images, transformed_images), axis=0)
    return expanded_class, expanded_class.shape[0]

def dense_labels(one_hot):
    return one_hot.nonzero()[1]

def split_and_expand(X, y, class_size=(20000, 5000)):
    segregated_data = []

    for class_ in range(43):
        segregated_class = X[dense_labels(y) == class_, ...]
        segregated_data.append(segregated_class)

    X_train, X_val = None, None
    y_train, y_val = None, None

    for class_, images in enumerate(segregated_data):
        if X_train is None:
            X_train, obs = _expand_class(images, class_size[0])
            y_train = np.full(obs, class_, dtype='int64')
            X_val, obs = _expand_class(images, class_size[1])
            y_val = np.full(obs, class_, dtype='int64')
        else:
            tmp, obs = _expand_class(images, class_size[0])
            X_train = np.concatenate((X_train, tmp), axis=0)
            y_train = np.concatenate((y_train, np.full(obs, class_, dtype='int64')), axis=0)

            tmp, obs = _expand_class(images, class_size[1])
            X_train = np.concatenate((X_train, tmp), axis=0)
            y_train = np.concatenate((y_train, np.full(obs, class_, dtype='int64')), axis=0)
    return X_train, y_train, X_val, y_val


# In Python using slash before special character is deprecated
# solution this problem is using raw string
# r'\n' is different from "\n".
# r'\n' treated as two characters '\' and 'n' respectively.
# whereas "\n" is treated as new line character.
import re
pattern1 = r'\n'
pattern2 = "\n"
txt = "hello this\n is to de\nmonstrate re\ngular expressions\n"
print(re.findall(pattern1, txt))
print(re.findall(pattern2, txt))


from flask import render_template, redirect, url_for, flash, Response
from app import app, db
import forms
from models import DATABASE_URL
# from datetime import datetime

import io
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import seaborn as sns
sns.set()
@app.route('/')

@app.route("/Good_Standing")
def Good_Standing():
    return render_template("Good_Standing.html")

@app.route("/about_us")
def about_us():
    return render_template("about_us.html")

@app.route("/hours")
def hours():
    return render_template("hours.html")

@app.route("/View_Hours")
def View_hours():
    return render_template("View_Hours.html")

@app.route("/User_View")
def User_View():
    return render_template("User_View.html")

@app.route('/sign_up', methods=['GET','POST'])
def index():
    form = forms.VolunteerForm()

    if form.validate_on_submit():
        # update session object
        print('Validated')
        student_name = form.student_name.data
        student_ID = form.student_ID.data
        hours = form.hours.data
        event = form.event.data
        Date = form.Date.data

        v = DATABASE_URL(name=student_name, stud_ID=student_ID, hours=hours, event=event, Date=Date)

        db.session.add(v)
        db.session.commit()
        flash('Data Submitted')
        form = forms.VolunteerForm()
        database_url = DATABASE_URL.query.filter_by(stud_ID=form.student_ID.data)
        return render_template('volunteer_found.html', DATABASE_URL=database_url)

    return render_template('sign_up.html', form=form)

@app.route('/specific_volunteers', methods=['GET', 'POST'])
def indx():
    form = forms.SpecificUser()

    if form.validate_on_submit():
        # update session object
        print('Validated')

        return redirect(url_for('volunteer_found'))

    return render_template('specific_volunteers.html', forms=form)

@app.route('/volunteer_found', methods=['GET', 'POST'])
def volunteer_found():
        form = forms.SpecificUser()
        if (form.student_ID.data=='84362345'):
            stud_eventregist = DATABASE_URL.query.all()
        else :
            stud_eventregist = DATABASE_URL.query.filter_by(stud_ID=form.student_ID.data)

        total_hours = 0
        event, hours = [], []

        for data in stud_eventregist:
            # add up all hours volunteered
            total_hours += data.hours

            # save to list elements
            event.append(data.event)
            hours.append(data.hours)

        # convert to pandas dataframe
        df = pd.DataFrame({"Event": event, "Hours": hours})
        print(df)
        #
        gb = df.groupby('Event').sum().reset_index()
        print(gb)

        # remove image if it exits
        if os.path.exists("plot.png"):
            os.remove("plot.png")

        fig = plt.figure()
        axis = fig.add_subplot(1,1,1)

        # documentation
        # https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.bar.html
        axis.bar(gb.Event, gb.Hours, color='blue')
        axis.set_title("Total Hours Volunteered", fontsize=16)
        axis.set_ylabel("Hours", fontsize=14)
        axis.set_xlabel("Event", fontsize=14)

        plt.savefig('plot.png')

        return render_template('volunteer_found.html', studregist=stud_eventregist, url='plot.png', hours=total_hours)

# @app.route('/volunteer_found', methods=['GET', 'POST'])
# def volunteer_fnd():
@app.route('/plot.png')
def plot_png():
    # grab data
    form = forms.SpecificUser()
    eventregist = DATABASE_URL.query.filter_by(stud_ID=form.student_ID.data)

    total_hours = 0
    event, hours = [], []

    for data in eventregist:
        # add up all hours volunteered
        total_hours += data.hours

        # save to list elements
        event.append(data.event)
        hours.append(data.hours)

    # convert to pandas dataframe
    df = pd.DataFrame({"Event": event, "Hours": hours})

    #
    gb = df.groupby('Event').sum().reset_index()
    print(gb)

    # remove image if it exits
    if os.path.exists("plot.png"):
        os.remove("plot.png")

    fig = plt.figure()
    axis = fig.add_subplot(1,1,1)

    # documentation
    # https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.bar.html
    axis.bar(gb.Event, gb.Hours, color='blue')
    axis.set_title("Total Hours Volunteered", fontsize=16)
    axis.set_ylabel("Hours", fontsize=14)
    axis.set_xlabel("Event", fontsize=14)

    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)

    return Response(output.getvalue(), mimetype='image/png')


from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response

from app.models import Deck, User, Card, Game, CardValue, Rule, CardEffect
from app.serializers import DeckSerializer, UserSerializer, CardSerializer, \
    GameSerializer, CardValueSerializer, RuleSerializer, CardEffectSerializer

class CustomObtainAuthToken(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        response = super(CustomObtainAuthToken, self) \
            .post(request, *args, **kwargs)

        token = Token.objects.get(key=response.data['token'])

        return Response({
            'token': token.key,
            'user': UserSerializer(token.user).data
        })

class DeckViewSet(viewsets.ModelViewSet):
    queryset = Deck.objects.all()
    serializer_class = DeckSerializer
    filter_fields = [
        'id',
        'name',
        'cards',
        'user',
    ]

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_fields = [
        'id',
        'username',
    ]

class CardViewSet(viewsets.ModelViewSet):
    queryset = Card.objects.all()
    serializer_class = CardSerializer
    filter_fields = [
        'id',
        'name',
        'cost',
        'type',
        'health',
        'strength',
        'effect',
    ]

class GameViewSet(viewsets.ModelViewSet):
    queryset = Game.objects.all()
    serializer_class = GameSerializer
    filter_fields = [
        'id',
        'owner',
        'owner_deck',
        'opponent',
        'opponent_deck'
    ]

class CardEffectViewSet(viewsets.ModelViewSet):
    queryset = CardEffect.objects.all()
    serializer_class = CardEffectSerializer
    filter_fields = [
        'id',
        'name',
        'description',
        'player_affected',
        'type',
        'quantity',
    ]

class CardValueViewSet(viewsets.ModelViewSet):
    queryset = CardValue.objects.all()
    serializer_class = CardValueSerializer
    filter_fields = [
        'id',
        'user',
        'card',
        'health',
        'strength',
    ]

class RuleViewSet(viewsets.ModelViewSet):
    queryset = Rule.objects.all()
    serializer_class = RuleSerializer
    filter_fields = [
        'id',
        'name',
        'players_health',
        'cards_in_deck',
        'cards_to_begin',
        'cards_to_draw',
    ]


# Copyright (c) 2015,Vienna University of Technology,
# Department of Geodesy and Geoinformation
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of the Vienna University of Technology,
#      Department of Geodesy and Geoinformation nor the
#      names of its contributors may be used to endorse or promote products
#      derived from this software without specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL VIENNA UNIVERSITY OF TECHNOLOGY,
# DEPARTMENT OF GEODESY AND GEOINFORMATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'''

Created on Tue Nov  3 14:56:50 2015

@author: christoph.paulik@geo.tuwien.ac.at
'''

from pytesmo.utils import ml_percentile
from pytesmo.utils import interp_uniq
from pytesmo.utils import ensure_iterable
import numpy as np
import numpy.testing as nptest

def test_ml_percentile():
    """
    Test the percentile implementation that is used in Matlab.
    """

    arr1 = np.array([1, 1, 1, 2, 2, 2, 5, 5, 6, 10, 10, 10, 10])
    percentiles = [0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]
    perc_should = [1.0, 1.0, 1.0, 1.1, 2.0, 2.0, 5.0, 5.3, 8.4, 10., 10., 10.,
                   10.]
    perc = ml_percentile(arr1, percentiles)
    nptest.assert_almost_equal(perc, perc_should)

def test_interp_unique():
    """
    test iterative filling of array
    """

    arr1 = np.array([1, 1, 1, 2, 2, 2, 5, 5, 6, 10, 10, 10, 10])
    percentiles = [0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]
    p = ml_percentile(arr1, percentiles)
    src_perc = interp_uniq(p)
    assert len(p) == len(src_perc)

    nptest.assert_almost_equal(src_perc, [1., 1.025, 1.05, 1.1, 1.55, 3.275,
                                          5., 5.3, 8.4, 9.2, 9.6, 9.8, 10.])

def test_ensure_iterable():
    el = 1
    new_el = ensure_iterable(el)
    assert new_el == [el]


#http://symfoware.blog68.fc2.com/blog-entry-885.html
#https://docs.python.jp/3/library/http.server.html
import http.server
#from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
class PostHandler(http.server.BaseHTTPRequestHandler):

    def do_POST(self):
        # POST されたフォームデータを解析する
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        # レスポンス開始
        self.send_response(200)
        self.end_headers()
        # フォームに POST されたデータを表示する
        for field in form.keys():
            field_item = form[field]
            print('%s=%s' % (field, form[field].value))

if __name__ == '__main__':
#    from BaseHTTPServer import HTTPServer
    server = http.server.HTTPServer(('localhost', 8080), PostHandler)
    server.serve_forever()


#!/usr/bin/env python3
"""Saper napisany w Pythonie i GTK+ 3 za pomocą bibliotek PyGObject i NumPy.
Użycie: ./minesweeper_gtk.py lub python3 minesweeper_gtk.py"""

#Importy
import time
import numpy
from gi.repository import Gtk, GObject

#Inicjalizacja
GRID_LABELS = {-2:"*", -1:"", 0:"", 1:"1", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8"}

MAIN_WINDOW = Gtk.Window(title="Saper", default_width=640)
MAIN_WINDOW.connect("destroy", Gtk.main_quit)
CANVAS = Gtk.Box(orientation=0, spacing=10)
SIDEBAR = Gtk.Box(orientation=1)

#Definicje funkcji i klas
def mine_button_press_handler(button, event):
    """Ta funkcja obsługuje kliknięcia przycisków min wszystkimi przyciskami\
    oraz powiązane z nimi funkcje rozszerzonego odkrywania i zaznaczania."""
    check_x, check_y = button.pos_x, button.pos_y

    #Obsługa lewego kliknięcia
    if event.button == 1:
        #Jeżeli zaczynamy grę, to generujemy planszę
        if MAIN_FIELD.fields_left == 0:
            MAIN_FIELD.populate(check_x, check_y)

        #Jeżeli pole jest niezaznaczone, to odkrywamy je
        if MAIN_FIELD.view_grid[button.pos_x][button.pos_y] == -1:
            MAIN_FIELD.step(check_x, check_y)
            MAIN_FIELD.discover()

    #Obsługa środkowego kliknięcia, jeżeli wokół pola jest mina
    elif event.button == 2 and MAIN_FIELD.view_grid[button.pos_x][button.pos_y] > 0:
        #Nie wychodząc poza granice siatki odkrywamy niezaznaczone pola wokół
        for border_x in range(max(0, button.pos_x-1), min(button.pos_x+2, MAIN_FIELD.size_x)):
            for border_y in range(max(0, button.pos_y-1), min(button.pos_y+2, MAIN_FIELD.size_y)):
                if MAIN_FIELD.view_grid[border_x][border_y] == -1:
                    MAIN_FIELD.step(border_x, border_y)
                    MAIN_FIELD.discover()

    #Obsługa prawego kliknięcia
    elif event.button == 3:
        #Zamieniamy pole nieodkryte na zaznaczone lub na odwrót
        if MAIN_FIELD.view_grid[button.pos_x][button.pos_y] == -1:
            MAIN_FIELD.view_grid[button.pos_x][button.pos_y] = -2
            button.set_label(GRID_LABELS[-2])
            MAIN_FIELD.markers_placed += 1
        elif MAIN_FIELD.view_grid[button.pos_x][button.pos_y] == -2:
            MAIN_FIELD.view_grid[button.pos_x][button.pos_y] = -1
            button.set_label(GRID_LABELS[-1])
            MAIN_FIELD.markers_placed -= 1

        #Odpowiednio zmieniamy tekst ze stanem
        MAIN_FIELD.fields_label.set_label(
            "{}/{}".format(MAIN_FIELD.markers_placed, MAIN_FIELD.mines))

def spin_button_change_handler(button):
    """Ta funkcja obsługuje zmianę maksymalnej ilości min w zależności\
    od wartości pola szerokości i wysokości."""
    max_mines = (SETTINGS_DIALOG.height_spinbutton.get_value_as_int()
                 * SETTINGS_DIALOG.width_spinbutton.get_value_as_int() - 1)
    SETTINGS_DIALOG.mines_spinbutton.set_range(10, max_mines)

def settings_button_handler(button):
    """Ta funkcja obsługuje wyświetlanie okna ustawień."""
    SETTINGS_DIALOG.settings_window.show_all()

def timer_update():
    """Ta funkcja aktualizuje stoper, gdy gra się toczy."""
    #Gdy gra się nie toczy, zwrócenie False zatrzymuje licznik
    if MAIN_FIELD.fields_left == 0:
        return False

    time_delta = time.time() - MAIN_FIELD.timer_start

    #Obliczamy ilość sekund i minut, które upłynęły
    minutes_delta = int(time_delta) // 60
    seconds_delta = int(time_delta) % 60

    #Aktualizujemy tekst stopera
    MAIN_FIELD.time_label.set_label("{:0=2d}:{:0=2d}".format(minutes_delta, seconds_delta))

    #Aby licznik znów zadziałał, funkcja zwraca True
    return True

def win():
    """Ta funkcja wyswietla okno wygranej."""
    #Ustawiamy przyciski min na nieklikalne
    for item in MAIN_FIELD.grid_buttons:
        item.set_sensitive(False)

    #Wyświetlamy okno dialogowe
    dialog = Gtk.MessageDialog(MAIN_WINDOW, 0, Gtk.MessageType.INFO,
                               Gtk.ButtonsType.OK, "Wygrałeś!")
    dialog.format_secondary_text(
        "Twój czas to {}\nKliknij OK aby zmienić typ planszy lub zacząć od nowa."
        .format(MAIN_FIELD.time_label.get_label()))
    dialog.run()
    dialog.destroy()

def lose():
    """Ta funkcja wyświetla okno przegranej."""
    #Ustawiamy przyciski min na nieklikalne
    for item in MAIN_FIELD.grid_buttons:
        item.set_sensitive(False)

    #Ustawiamy ilość pozostałych pól na 0, aby stoper się zatrzymał
    MAIN_FIELD.fields_left = 0

    #Wyświetlamy okno dialogowe
    dialog = Gtk.MessageDialog(MAIN_WINDOW, 0, Gtk.MessageType.INFO,
                               Gtk.ButtonsType.OK, "Przegrałeś.")
    dialog.format_secondary_text(
        "Twój czas to {}\nKliknij OK aby zmienić typ planszy lub zacząć od nowa."
        .format(MAIN_FIELD.time_label.get_label()))
    dialog.run()
    dialog.destroy()

class BombButton(Gtk.Button):
    """Ta klasa jest rozszerzeniem klasy Gtk.Button o zmienne położenia na siatce\
    równomierne skalowanie i automatyczne dołączanie do siatki.
    (self.pos_x i self.pos_y)"""

    def __init__(self, parent, pos_x, pos_y):
        self.parent, self.pos_x, self.pos_y = parent, pos_x, pos_y

        #Stworzenie przycisku wraz z odpowiednim opisem i skalowaniem w obu kierunkach
        Gtk.Button.__init__(self, label=GRID_LABELS[-1], hexpand=True, vexpand=True)

        #Przypisanie funkcji i dopięcie przycisku do siatki
        self.connect("button-press-event", mine_button_press_handler)
        parent.button_grid.attach(self, pos_x, pos_y, 1, 1)

class MineField():
    """Ta klasa zawiera tablice określające planszę, elementy interfejsu,\
    i metody, które je zmieniają."""

    def populate(self, step_x, step_y):
        """Ta metoda generuje planszę z uwzględnieniem pierwszego kroku i uruchamia stoper."""
        self.fields_left = self.size_x * self.size_y - self.mines
        mines_to_create = self.mines

        while mines_to_create > 0:
            #Losujemy pozycję miny
            fill_x = numpy.random.randint(0, self.size_x)
            fill_y = numpy.random.randint(0, self.size_y)

            #Sprawdzamy czy nie zapełniamy pierwszego kroku lub istniejącej miny
            if self.mine_grid[fill_x][fill_y] != 1 and (fill_x, fill_y) != (step_x, step_y):
                self.mine_grid[fill_x][fill_y] = 1
                mines_to_create -= 1

        #Uruchamiamy stoper
        self.timer_start = time.time()
        GObject.timeout_add_seconds(1, timer_update)

    def step(self, step_x, step_y):
        """Ta metoda służy do odkrywania pól, zmiany opisów przycisków\
        i zaznaczania sąsiednich pól do odkrycia."""
        mines_around = 0

        #Jeśli trafiamy na minę, to przegrywamy
        if self.mine_grid[step_x][step_y] == 1:
            lose()

        #Sprawdzamy ile jest min wokół kroku, nie wychodzimy poza granice siatki
        for border_x in range(max(0, step_x-1), min(step_x+2, self.size_x)):
            for border_y in range(max(0, step_y-1), min(step_y+2, self.size_y)):
                if (border_x, border_y) != (step_x, step_y):
                    #Obliczamy ilość min wokół kroku
                    mines_around += self.mine_grid[border_x][border_y]

        #Przypisujemy ilość min do widoku
        if self.view_grid[step_x][step_y] == -1:
            self.fields_left -= 1
            self.view_grid[step_x][step_y] = mines_around
            self.grid_buttons[step_x+step_y*self.size_x].set_label(GRID_LABELS[mines_around])

        #Jeśli wokół kroku nie ma min, zaznaczamy pola do odkrycia
        if mines_around == 0:
            for border_x in range(max(0, step_x-1), min(step_x+2, self.size_x)):
                for border_y in range(max(0, step_y-1), min(step_y+2, self.size_y)):
                    if self.view_grid[border_x][border_y] == -1:
                        #Dodajemy do kolejki
                        self.queue.add((border_x, border_y))

            #Pola puste są nieklikalne
            self.grid_buttons[step_x+step_y*self.size_x].set_sensitive(False)

    def discover(self):
        """Ta metoda służy do odkrywania pól znajdujących się wokół pustych pól\
        zaznaczonych przez funkcję step."""

        #Odkrywamy kolejne pola aż kolejka się skończy
        while self.queue:
            (discover_x, discover_y) = self.queue.pop()
            self.step(discover_x, discover_y)

        #Jeśli nie ma pól do odkrycia, to wygrywamy
        if self.fields_left == 0:
            win()

    def grids_setup(self):
        """Ta metoda służy do ustawiania pustych tablic podczas inicjalizacji."""
        self.mine_grid = numpy.zeros((self.size_x, self.size_y), dtype=bool)
        self.view_grid = numpy.full((self.size_x, self.size_y), -1, dtype=int)

    def restart(self, button):
        """Ta metoda służy do restartowania gry, w tym zmiany opisów przycisków\
        i zawartości tablic."""
        self.grids_setup()
        self.markers_placed = 0
        self.fields_left = 0
        self.timer_start = 0
        self.queue.clear()

        #Ustawiamy opisy przycisków
        for item in self.grid_buttons:
            item.set_label(GRID_LABELS[-1])
            item.set_sensitive(True)

        #Ustawiamy opisy stanu gry
        self.fields_label.set_label("{}/{}".format(self.markers_placed, self.mines))
        self.time_label.set_label("00:00")

    def change_size(self, button):
        """Ta metoda służy do zmiany właściwości pola gry, w tym siatki, przycisków\
        i tablic."""
        self.size_x, self.size_y, self.mines = (
            SETTINGS_DIALOG.width_spinbutton.get_value_as_int(),
            SETTINGS_DIALOG.height_spinbutton.get_value_as_int(),
            SETTINGS_DIALOG.mines_spinbutton.get_value_as_int())
        self.grids_setup()
        self.markers_placed = 0
        self.fields_left = 0
        self.timer_start = 0
        self.queue.clear()

        #Usuwamy przyciski i referencje do nich
        for item in self.grid_buttons:
            item.destroy()
        self.grid_buttons.clear()

        #Tworzymy nowe przyciski i dołączamy je do siatki
        for pos_y in range(self.size_y):
            for pos_x in range(self.size_x):
                self.grid_buttons.append(BombButton(self, pos_x, pos_y))

        #Ustawiamy opisy stanu gry
        self.fields_label.set_label("{}/{}".format(self.markers_placed, self.mines))
        self.time_label.set_label("00:00")

        #Aktualizujemy główne okno i zamykamy okno ustawień
        MAIN_WINDOW.show_all()
        SETTINGS_DIALOG.settings_window.hide()

    def __init__(self, size_x, size_y, mines):
        self.size_x, self.size_y, self.mines = size_x, size_y, mines
        self.grids_setup()
        self.markers_placed = 0
        self.fields_left = 0
        self.timer_start = 0
        self.grid_buttons = []
        self.queue = set()

        #Ustawiamy równe wymiary kolumn i wierszy
        self.button_grid = Gtk.Grid(column_homogeneous=True, row_homogeneous=True)

        #Tworzymy przyciski
        for pos_y in range(size_y):
            for pos_x in range(size_x):
                self.grid_buttons.append(BombButton(self, pos_x, pos_y))

        #Dołączamy siatkę do głównego okna
        CANVAS.pack_start(self.button_grid, True, True, 10)

        #Tworzymy napisy
        state_labels = Gtk.Box(orientation=1, spacing=10)
        info_label = Gtk.Label(label="Stan gry:")

        #Ustawiamy opisy stanu gry
        self.fields_label = Gtk.Label(label='{}/{}'.format(self.markers_placed, self.mines))
        self.time_label = Gtk.Label(label="00:00")

        #Dołączamy przyciski do paska bocznego
        state_labels.pack_start(info_label, False, False, 0)
        state_labels.pack_start(self.fields_label, False, False, 0)
        state_labels.pack_start(self.time_label, False, False, 0)
        SIDEBAR.pack_start(state_labels, False, False, 10)

class SettingsDialog():
    """Ta klasa obsługuje okno ustawień."""

    def __init__(self):
        #Tworzymy nowe modalne okno do ustawiania właściwości planszy
        self.settings_window = Gtk.Window(title="Ustawienia", default_width=250,
                                          modal=True, transient_for=MAIN_WINDOW)
        height_spinbutton_label = Gtk.Label(label="Wysokość:")
        self.height_spinbutton = Gtk.SpinButton.new_with_range(8, 32, 1)
        width_spinbutton_label = Gtk.Label(label="Szerokość:")
        self.width_spinbutton = Gtk.SpinButton.new_with_range(8, 32, 1)
        mines_spinbutton_label = Gtk.Label(label="Ilość min:")
        self.mines_spinbutton = Gtk.SpinButton.new_with_range(10, 63, 1)
        accept_button = Gtk.Button(label="OK")

        button_container = Gtk.Box(orientation=1, spacing=4)
        button_container.pack_start(height_spinbutton_label, False, False, 4)
        button_container.pack_start(self.height_spinbutton, False, False, 4)
        button_container.pack_start(width_spinbutton_label, False, False, 4)
        button_container.pack_start(self.width_spinbutton, False, False, 4)
        button_container.pack_start(mines_spinbutton_label, False, False, 4)
        button_container.pack_start(self.mines_spinbutton, False, False, 4)
        button_container.pack_start(accept_button, False, False, 4)

        #Podpinamy funkcje do przycisków
        self.height_spinbutton.connect("value-changed", spin_button_change_handler)
        self.width_spinbutton.connect("value-changed", spin_button_change_handler)
        accept_button.connect("clicked", MAIN_FIELD.change_size)
        self.settings_window.add(button_container)

#Konstruujemy obiekty
MAIN_FIELD = MineField(16, 16, 10)
SETTINGS_DIALOG = SettingsDialog()

#Tworzymy przyciski
CONTROL_BUTTONS = Gtk.Box(orientation=1, spacing=10)
SETTINGS_BUTTON = Gtk.Button(label="Zmień ustawienia planszy")
RESTART_BUTTON = Gtk.Button(label="Zacznij od nowa")

#Dołączamy przyciski do paska bocznego
CONTROL_BUTTONS.pack_start(SETTINGS_BUTTON, False, False, 0)
CONTROL_BUTTONS.pack_start(RESTART_BUTTON, False, False, 0)
SIDEBAR.pack_end(CONTROL_BUTTONS, False, False, 10)

#Łączymy przyciski na pasku bocznym do ich funkcji
RESTART_BUTTON.connect("clicked", MAIN_FIELD.restart)
SETTINGS_BUTTON.connect("clicked", settings_button_handler)
CANVAS.pack_end(SIDEBAR, False, False, 10)

#Pokazujemy okno
MAIN_WINDOW.add(CANVAS)
MAIN_WINDOW.show_all()

Gtk.main()


# -*- coding: utf-8 -*-
import scrapy
import json
from cp_plan.items import CpPlanItem, Wait_Item
from scrapy.http import Request
import time

class CpPlansSpider(scrapy.Spider):
    name = 'ffc_all'
    allowed_domains = ['http://56070.la/']
    start_urls = ['http://56070.la/json/ffc.json', 'http://56070.la/json/ffc_h2zx.json',
                  'http://56070.la/json/ffc_h3zx.json', 'http://56070.la/json/ffc_h3z6.json']
    sign_num = 4418

    def parse(self, response):
        html = json.loads(response.body)
        # 最新一条等开计划信息
        endlist = html.get('EndList')
        item = CpPlanItem()
        item['title'] = html.get('NewGame')['WaitGame']
        if response.url == 'http://56070.la/json/ffc.json':
            item['type'] = 51
        elif response.url == 'http://56070.la/json/ffc_h2zx.json':
            item['type'] = 52
        elif response.url == 'http://56070.la/json/ffc_h3zx.json':
            item['type'] = 53
        else:
            item['type'] = 54
        item['gameId'] = 5
        yield item
        # 其余的计划信息
        for each in endlist:
            item = CpPlanItem()
            # print(each)
            item['title'] = each['Ruestl']
            if response.url == 'http://56070.la/json/ffc.json':
                item['type'] = 51
            elif response.url == 'http://56070.la/json/ffc_h2zx.json':
                item['type'] = 52
            elif response.url == 'http://56070.la/json/ffc_h3zx.json':
                item['type'] = 53
            else:
                item['type'] = 54
            item['gameId'] = 5

            yield item
            # 爬取 即刻开奖信息
        item = Wait_Item()
        N1 = html.get('TopGame')['R1']
        N2 = html.get('TopGame')['R2']
        N3 = html.get('TopGame')['R3']
        N4 = html.get('TopGame')['R4']
        N5 = html.get('TopGame')['R5']
        item['num'] = '{0},{1},{2},{3},{4}'.format(N1, N2, N3, N4, N5)
        item['gamedate'] = html.get('TopGame')['gameid']
        item['gameId'] = 5

        yield item


from django.shortcuts import render, get_object_or_404
from .models import Post
from .forms import CommentForm

def read_post_view(request, post_id):
    post = get_object_or_404(Post, id=post_id)

    form = CommentForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        comment = form.save(commit=False)
        comment.post = post
        comment.author = request.user if request.user.is_authenticated() else None
        comment.save()

    return render(request, 'posts/read.html', {'post': post, 'form': form})


#!/usr/bin/env python

# -*- encoding: utf-8 -*-

'''
@Author  :   {lif54334}

@Software:   PyCharm

@File    :   patent.py

@Time    :   2019/3/18 15:36

@Desc    :

'''
import re

import pymysql

def read(path):
    with open(path,'r',encoding='utf8')as f:
        lines=f.readlines()
        nums=len(lines)
        print(nums)
        # print(re.search(r'(\d+)、(.*)', line))
        contents=list()
        for i in range(0,nums,4):
            content = []
            title=lines[i].strip('\n').split('、')[1]
            abs=lines[i+1].strip('\n').split('：')[1]
            time=lines[i+2].strip('\n').split('：')[1]
            person=lines[i+3].strip('\n').split('：')[1]
            content.append(title)
            content.append(abs[0:14000])
            content.append(time[0:4])
            content.append(person[0:100])
            contents.append(content)
    # print(contents)
    return (contents)

def creat(name):
    db = pymysql.connect("localhost", "root", "1234", "xian")
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    table_name = name
    sql = "show tables;"
    cursor.execute(sql)
    tables = [cursor.fetchall()]
    table_list = re.findall('(\'.*?\')',str(tables))
    table_list = [re.sub("'",'',each) for each in table_list]
    if table_name in table_list:
        print("已存在")        #存在返回1
    else:
        print("未存在")
        cursor.execute("CREATE TABLE %s(title varchar(2000),abs varchar (14000),time int(10),person varchar (100))" % table_name)

def insert(data,name):
    table_name=name
    values=[]
    for items in data:
        values.append((items[0],items[1],items[2],items[3]))
        # print(values)
    # print(values)
    print(len(values))
    db = pymysql.connect("localhost", "root", "1234", "xian")
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    cursor.executemany("INSERT INTO %s values(%%s,%%s,%%s,%%s)"%(table_name),values)
    db.commit()
    cursor.close()

if __name__ == '__main__':
    name='zl_light'
    path="light2.txt"
    list=read(path)
    creat(name)
    insert(list,name)


import uuid

from django.db import models

class Location(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)

    organisation = models.ForeignKey('aliss.Organisation', related_name='locations',on_delete=models.CASCADE)

    name = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)

    street_address = models.CharField(max_length=100)
    locality = models.CharField(max_length=30)
    region = models.CharField(max_length=30, blank=True)
    state = models.CharField(max_length=30, blank=True)
    postal_code = models.CharField(max_length=10)
    country = models.CharField(max_length=2, default="GB")

    latitude = models.FloatField()
    longitude = models.FloatField()

    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(
        'aliss.ALISSUser',
        related_name='created_locations',
        null=True,
        on_delete=models.SET_NULL
    )
    updated_on = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(
        'aliss.ALISSUser',
        related_name='updated_locations',
        null=True,
        on_delete=models.SET_NULL
    )

    def is_edited_by(self, user):
        if user == None or user.pk == None:
            return False
        elif user.is_staff:
            return True
        elif self.organisation.claimed_by == None:
            return (user.is_editor or (self.organisation.created_by == user))
        else:
            return self.organisation.claimed_by == user

    def __str__(self):
        return self.formatted_address

    @property
    def formatted_address(self):
        return ", ".join(filter(None, [self.name, self.street_address, self.locality, self.postal_code, self.state]))


# MIT License
#
# Copyright (c) 2018-2022 Stefan Chmiela, Gregory Fonseca
# Copyright (c) 2022-2023, Alex M. Maldonado
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import numpy as np
from ..logger import GDMLLogger
from ..stress import virial_atom_loop

log = GDMLLogger(__name__)

# This calculation is too fast to be a ray task.
# pylint: disable-next=too-many-statements
def _predict_gdml_wkr(
    r_desc,
    r_d_desc,
    n_atoms,
    sig,
    n_perms,
    R_desc_perms,
    R_d_desc_alpha_perms,
    alphas_E_lin,
    wkr_start_stop=None,
    chunk_size=None,
):
    r"""Compute (part) of a GDML prediction.

    Every prediction is a linear combination involving the training points used for
    this model. This function evaluates that combination for the range specified by
    `wkr_start_stop`. This workload can optionally be processed in chunks,
    which can be faster as it requires less memory to be allocated.

    Note
    ----
    It is sufficient to provide either the parameter ``r`` or ``r_desc_d_desc``.
    The other one can be set to :obj:`None`.

    Returns
    -------
    :obj:`numpy.ndarray`
        Partial prediction of all force components and energy (appended to
        array as last element).
    """
    # pylint: disable=invalid-name
    ###   mbGDML CHANGE   ###
    n_train = int(R_desc_perms.shape[0] / n_perms)
    ###   mbGDML CHANGE END   ###

    wkr_start, wkr_stop = (0, n_train) if wkr_start_stop is None else wkr_start_stop
    if chunk_size is None:
        chunk_size = n_train

    ###   mbGDML CHANGE   ###
    dim_d = (n_atoms * (n_atoms - 1)) // 2
    dim_i = 3 * n_atoms
    dim_c = chunk_size * n_perms
    ###   mbGDML CHANGE END   ###

    # Pre-allocate memory.
    diff_ab_perms = np.empty((dim_c, dim_d), dtype=np.double)
    a_x2 = np.empty((dim_c,), dtype=np.double)
    mat52_base = np.empty((dim_c,), dtype=np.double)

    # avoid divisions (slower)
    sig_inv = 1.0 / sig
    mat52_base_fact = 5.0 / (3 * sig**3)
    diag_scale_fact = 5.0 / sig
    sqrt5 = np.sqrt(5.0)

    E_F = np.zeros((dim_d + 1,), dtype=np.double)
    F = E_F[1:]

    wkr_start *= n_perms
    wkr_stop *= n_perms

    b_start = wkr_start
    for b_stop in list(range(wkr_start + dim_c, wkr_stop, dim_c)) + [wkr_stop]:

        rj_desc_perms = R_desc_perms[b_start:b_stop, :]
        rj_d_desc_alpha_perms = R_d_desc_alpha_perms[b_start:b_stop, :]

        # Resize pre-allocated memory for last iteration,
        # if chunk_size is not a divisor of the training set size.
        # Note: It's faster to process equally sized chunks.
        c_size = b_stop - b_start
        if c_size < dim_c:
            diff_ab_perms = diff_ab_perms[:c_size, :]
            a_x2 = a_x2[:c_size]
            mat52_base = mat52_base[:c_size]

        np.subtract(
            np.broadcast_to(r_desc, rj_desc_perms.shape),
            rj_desc_perms,
            out=diff_ab_perms,
        )
        norm_ab_perms = sqrt5 * np.linalg.norm(diff_ab_perms, axis=1)

        np.exp(-norm_ab_perms * sig_inv, out=mat52_base)
        mat52_base *= mat52_base_fact
        np.einsum(
            "ji,ji->j", diff_ab_perms, rj_d_desc_alpha_perms, out=a_x2
        )  # colum wise dot product

        F += (a_x2 * mat52_base).dot(diff_ab_perms) * diag_scale_fact
        mat52_base *= norm_ab_perms + sig
        F -= mat52_base.dot(rj_d_desc_alpha_perms)

        # Energies are automatically predicted with a flipped sign here
        # (because -E are trained, instead of E)
        E_F[0] += a_x2.dot(mat52_base)

        # Energies are automatically predicted with a flipped sign here
        # (because -E are trained, instead of E)
        if alphas_E_lin is not None:

            K_fe = diff_ab_perms * mat52_base[:, None]
            F += alphas_E_lin[b_start:b_stop].dot(K_fe)

            K_ee = (
                1 + (norm_ab_perms * sig_inv) * (1 + norm_ab_perms / (3 * sig))
            ) * np.exp(-norm_ab_perms * sig_inv)
            E_F[0] += K_ee.dot(alphas_E_lin[b_start:b_stop])

        b_start = b_stop

    out = E_F[: dim_i + 1]

    # Descriptor has less entries than 3N, need to extend size of the 'E_F' array.
    if dim_d < dim_i:
        out = np.empty((dim_i + 1,))
        out[0] = E_F[0]

    # 'r_d_desc.T.dot(F)' for our special representation of 'r_d_desc'
    r_d_desc = r_d_desc[None, ...]
    F = F[None, ...]

    ###   mbGDML CHANGE   ###
    n = np.max((r_d_desc.shape[0], F.shape[0]))
    i, j = np.tril_indices(n_atoms, k=-1)

    out_F = np.zeros((n, n_atoms, n_atoms, 3))
    out_F[:, i, j, :] = r_d_desc * F[..., None]
    out_F[:, j, i, :] = -out_F[:, i, j, :]
    out[1:] = out_F.sum(axis=1).reshape(n, -1)
    ###   mbGDML CHANGE END   ###

    return out

# Possible ray task.
# pylint: disable-next=too-many-branches
def predict_gdml(Z, R, entity_ids, entity_combs, model, periodic_cell, **kwargs):
    r"""Predict total :math:`n`-body energy and forces of a single structure.

    Parameters
    ----------
    Z : :obj:`numpy.ndarray`, ndim: ``1``
        Atomic numbers of all atoms in ``r`` (in the same order).
    R : :obj:`numpy.ndarray`, ndim: ``2``
        Cartesian coordinates of a single structure to predict.
    entity_ids : :obj:`numpy.ndarray`, ndim: ``1``
        1D array specifying which atoms belong to which entities.
    entity_combs : ``iterable``
        Entity ID combinations (e.g., ``(53,)``, ``(0, 2)``,
        ``(32, 55, 293)``, etc.) to predict using this model. These are used
        to slice ``r`` with ``entity_ids``.
    model : :obj:`mbgdml.models.gdmlModel`
        GDML model containing all information need to make predictions.
    periodic_cell : :obj:`mbgdml.periodic.Cell`, default: :obj:`None`
        Use periodic boundary conditions defined by this object.

    Returns
    -------
    :obj:`float`
        Predicted :math:`n`-body energy.
    :obj:`numpy.ndarray`
        Predicted :math:`n`-body forces.
    """
    assert R.ndim == 2
    E = 0.0
    F = np.zeros(R.shape)

    alchemy_scalers = kwargs.get("alchemy_scalers", None)
    compute_virial = kwargs.get("compute_virial", False)

    periodic = bool(periodic_cell)
    compute_virial = bool(periodic and compute_virial)
    if compute_virial:
        virial = np.zeros((3, 3), dtype=np.float64)

    # Getting all contributions for each molecule combination (comb).
    for entity_id_comb in entity_combs:

        # Gets indices of all atoms in the combination of molecules.
        # r_slice is a list of the atoms for the entity_id combination.
        r_slice = []
        for entity_id in entity_id_comb:
            r_slice.extend(np.where(entity_ids == entity_id)[0])

        z = Z[r_slice]
        r = R[r_slice]
        # Note: We store the original coordinates in case the virial is requested

        # If we are using a periodic cell we convert r_comp into coordinates
        # we can use in many-body expansions.
        if periodic:
            r = periodic_cell.r_mic(r)
            if r is None:
                # Any atomic pairwise distance was larger than cutoff.
                continue

        # Checks criteria cutoff if present and desired.
        if model.criteria is not None:
            accept_r, _ = model.criteria.accept(z, r)
            if not accept_r:
                # Do not include this contribution.
                continue

        # Predicts energies and forces.
        r_desc, r_d_desc = model.desc_func(r.flatten(), model.lat_and_inv)
        wkr_args = (
            r_desc,
            r_d_desc,
            len(z),
            model.sig,
            model.n_perms,
            model.R_desc_perms,
            model.R_d_desc_alpha_perms,
            model.alphas_E_lin,
        )
        out = _predict_gdml_wkr(*wkr_args)

        out *= model.stdev
        e = out[0] + model.integ_c
        f = out[1:].reshape((len(z), 3))

        # Scale contribution if entity is included.
        if alchemy_scalers not in (None, []):
            for alchemy_scaler in alchemy_scalers:
                if alchemy_scaler.entity_id in entity_id_comb:
                    e = alchemy_scaler.scale(e)
                    f = alchemy_scaler.scale(f)

        # Adds contributions to total energy and forces.
        E += e
        F[r_slice] += f

        if compute_virial:
            virial += virial_atom_loop(r, f)

    if compute_virial:
        return E, F, virial

    return E, F

def predict_gdml_decomp(Z, R, entity_ids, entity_combs, model, **kwargs):
    r"""Predict all :math:`n`-body energies and forces of a single structure.

    Parameters
    ----------
    Z : :obj:`numpy.ndarray`, ndim: ``1``
        Atomic numbers of all atoms in ``r`` (in the same order).
    r : :obj:`numpy.ndarray`, ndim: ``2``
        Cartesian coordinates of a single structure to predict.
    entity_ids : :obj:`numpy.ndarray`, ndim: ``1``
        1D array specifying which atoms belong to which entities.
    entity_combs : ``iterable``
        Entity ID combinations (e.g., ``(53,)``, ``(0, 2)``,
        ``(32, 55, 293)``, etc.) to predict using this model. These are used
        to slice ``r`` with ``entity_ids``.
    model : :obj:`mbgdml.models.gdmlModel`
        GDML model containing all information need to make predictions.

    Returns
    -------
    :obj:`numpy.ndarray`, ndim: ``1``
        Energies of all possible :math:`n`-body structures. Some elements
        can be :obj:`numpy.nan` if they are beyond the criteria cutoff.
    :obj:`numpy.ndarray`, ndim: ``3``
        Atomic forces of all possible :math:`n`-body structure. Some
        elements can be :obj:`numpy.nan` if they are beyond the criteria
        cutoff.
    :obj:`numpy.ndarray`, ndim: ``2``
        All possible :math:`n`-body combinations of ``r`` (i.e., entity ID
        combinations).
    """
    assert R.ndim == 2

    if entity_combs.ndim == 1:
        n_atoms = np.count_nonzero(entity_ids == entity_combs[0])
    else:
        n_atoms = 0
        for i in entity_combs[0]:
            n_atoms += np.count_nonzero(entity_ids == i)

    E = np.empty(len(entity_combs), dtype=np.float64)
    F = np.empty((len(entity_combs), n_atoms, 3), dtype=np.float64)
    E[:] = np.nan
    F[:] = np.nan

    alchemy_scalers = kwargs.get("alchemy_scalers", None)

    # Getting all contributions for each molecule combination (comb).
    for i, entity_id_comb in enumerate(entity_combs):
        # Gets indices of all atoms in the combination of molecules.
        # r_slice is a list of the atoms for the entity_id combination.
        r_slice = []
        for entity_id in entity_id_comb:
            r_slice.extend(np.where(entity_ids == entity_id)[0])

        z_comp = Z[r_slice]
        r_comp = R[r_slice]

        # Checks criteria cutoff if present and desired.
        if model.criteria is not None:
            accept_r, _ = model.criteria.accept(z_comp, r_comp)
            if not accept_r:
                # Do not include this contribution.
                continue

        # Predicts energies and forces.
        r_desc, r_d_desc = model.desc_func(r_comp.flatten(), model.lat_and_inv)
        out = _predict_gdml_wkr(
            r_desc,
            r_d_desc,
            n_atoms,
            model.sig,
            model.n_perms,
            model.R_desc_perms,
            model.R_d_desc_alpha_perms,
            model.alphas_E_lin,
        )

        out *= model.stdev
        E[i] = out[0] + model.integ_c
        F[i] = out[1:].reshape((n_atoms, 3))

        # Scale contribution if entity is included.
        if alchemy_scalers not in (None, []):
            for alchemy_scaler in alchemy_scalers:
                if alchemy_scaler.entity_id in entity_id_comb:
                    E[i] = alchemy_scaler.scale(E[i])
                    F[i] = alchemy_scaler.scale(F[i])

    return E, F, entity_combs


# Урок 1
# Задание 3
"""
Узнайте у пользователя число n.
Найдите сумму чисел n + nn + nnn.
Например, пользователь ввёл число 3.
Считаем 3 + 33 + 333 = 369.
"""

# Комментарий: Вариант один, с проверкой значения от 0 до 9.
# Другие типы (float, bool и str не учитываются, т.к. пока не знаю как их учитывать, долго мучился...:(
# Знаю, что беконечный цикл - плохо, поэтому добавил условия на количество ввода
# если переменная будет другого типа, то программа выдаст ошибку, это не противоречит условию задания
i = 4
while(i > 0):
    n_number = input('Введите любое целое положительное число от 0 до 9 включительно: ', )
    if (int(n_number) >= 10):
         print("Вы ввели число больше 10, повторите ввод")
         i -= 1
         print('Осталось попыток', i)
    elif int(n_number) < 0:
         print('Вы ввели отрицательное число, не надо так, повторите ввод еще раз')
         i -= 1
         print('Осталось попыток', i)
    else:
        n_number = int(n_number) + int(str(n_number)+str(n_number)) + int(str(n_number)+str(n_number)+str(n_number))
        print('Итоговое сумма n+nn+nnn: ', n_number)
        print('Спасибо, что ввели число, соответствующее условию')
        break
if (i == 0):
    print('Попытки кончились, попробуйте запустить проект еще раз')

# Комментарий: Вариант два, если пользователь
# вводит 2+ значное значение (пользователь умный, не вводит отрицательные значения и значения других типов)
# Пример: n=123, значит nn = 123123, nnn = 123132123, sum = 123236369 и так пока не лопнем
n_number = input('Введите любое целочисленное положительное число: ', )
n_number = int(n_number) + int(str(n_number)+str(n_number)) + int(str(n_number)+str(n_number)+str(n_number))
print('Итоговое число: ', n_number)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('mess', '0003_auto_20160121_1748'),
    ]

    operations = [
        migrations.CreateModel(
            name='MessDate',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
                ('mess_start', models.DateField()),
                ('mess_end', models.DateField()),
                ('display_option', models.IntegerField(choices=[(1, 'Yes'), (0, 'No')])),
                ('deadline', models.DateField()),
            ],
        ),
    ]


from bs4 import BeautifulSoup
import requests
import bs4
import re

ulist = []

#检查url地址
def check_link(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = 'GBK'
        return r.text

    except:
        print('无法链接服务器！！！')

#爬取资源
def get_urls(rurl):
    global ulist
    soup = BeautifulSoup(rurl,'lxml')
    trs = soup.find_all('tbody')
    ulist = pattern.findall(str(trs))

def get_save_contents(content, rurl):
    soup = BeautifulSoup(rurl,'lxml')
    trs = soup.find_all('p')
    value0 = str(trs).replace('[
', '')
    value1 = value0.replace('
', '')
    value2 = value1.replace(' ', '')
    value = value2.replace('
]', '')
    content += value
    try:
        with open('十三步.txt','a') as f:
            f.write(content)
    except:
        pass

def main():
    content = ''
    rs = check_link(url)
    get_save_contents(content, rs)

url0 = 'http://www.kanunu8.com/book2/10731/'
url = url0 + 'index.html'
pattern = re.compile('(?<=href=").+?\.html')
rs = check_link(url)
get_urls(rs)

for chapterurl in ulist:
    url = url0 + chapterurl
main()