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

from django.db import migrations, models
import filebrowser.fields

class Migration(migrations.Migration):

    dependencies = [
        ('filebrowser', '0002_auto_20180301_2039'),
    ]

    operations = [
        migrations.AddField(
            model_name='filedescription',
            name='file_path_hash',
            field=models.CharField(db_index=True, max_length=64, editable=False, blank=True),
        ),
        migrations.AlterField(
            model_name='filedescription',
            name='file_path',
            field=filebrowser.fields.FileBrowseField(max_length=500, verbose_name='File path'),
        ),
    ]


import os
from pathlib import Path

from .proto.pps.pps_pb2 import Transform, CreatePipelineRequest, BuildSpec

from google.protobuf import json_format

# Default script for running python code with wheels in a pipeline that was
# deployed with `create_python_pipeline`.
RUNNER_SCRIPT_WITH_WHEELS = """
#!/bin/sh
set -{set_args}

cd /pfs/{source_repo_name}
pip install /pfs/{build_pipeline_name}/*.whl
python main.py
"""

# Default script for running python code without wheels in a pipeline that was
# deployed with `create_python_pipeline`.
RUNNER_SCRIPT_WITHOUT_WHEELS = """
#!/bin/sh
set -{set_args}

cd /pfs/{source_repo_name}
python main.py
"""

# Default script for building python wheels for a pipeline that was deployed
# with `create_python_pipeline`.
BUILDER_SCRIPT = """
#!/bin/sh
set -{set_args}
python --version
pip --version

cd /pfs/{source_repo_name}
test -f requirements.txt && pip wheel -r requirements.txt -w /pfs/out
"""

def put_files(client, source_path, commit, dest_path, **kwargs):
    """
    Utility function for recursively inserting files from the local
    `source_path` to pachyderm. Roughly equivalent to `pachctl put file -r`.

    Params:

    * `client`: The `Client` instance to use.
    * `source_path`: The directory to recursively insert content from.
    * `commit`: The `Commit` object to use for inserting files.
    * `dest_path`: The destination path in PFS.
    * `kwargs`: Keyword arguments to forward. See
    `PutFileClient.put_file_from_fileobj` for details.
    """

    with client.put_file_client() as pfc:
        for root, _, filenames in os.walk(source_path):
            for filename in filenames:
                source_filepath = os.path.join(root, filename)
                dest_filepath = os.path.join(dest_path, os.path.relpath(source_filepath, start=source_path))
                pfc.put_file_from_filepath(commit, dest_filepath, source_filepath, **kwargs)

def create_python_pipeline(client, path, input=None, pipeline_name=None, image_pull_secrets=None,
                           debug=None, env=None, secrets=None, image=None, update=False,
                           **pipeline_kwargs):
    """
    Utility function for creating (or updating) a pipeline specially built for
    executing python code that is stored locally at `path`.

    A normal pipeline creation process requires you to first build and push a
    container image with the source and dependencies baked in. As an alternative
    process, this function circumvents container image creation by using build
    step-enabled pipelines. See the pachyderm core docs for more info.

    If `path` references a directory, it should have:

    * A `main.py`, as the pipeline entry-point.
    * An optional `requirements.txt` that specifies pip requirements.

    Params:

    * `client`: The `Client` instance to use.
    * `path`: The directory containing the python pipeline source, or an
    individual python file.
    * `input`: An optional `Input` object specifying the pipeline input.
    * `pipeline_name`: An optional string specifying the pipeline name.
    Defaults to using the last directory name in `path`.
    * `image_pull_secrets`: An optional list of strings specifying the
    pipeline transform's image pull secrets, which are used for pulling images
    from a private registry. Defaults to `None`, in which case the public
    docker registry will be used. See the pipeline spec document for more
    details.
    * `debug`: An optional bool specifying whether debug logging should be
    enabled for the pipeline. Defaults to `False`.
    * `env`: An optional mapping of string keys to string values specifying
    custom environment variables.
    * `secrets`: An optional list of `Secret` objects for secret environment
    variables.
    * `image`: An optional string specifying the docker image to use for the
    pipeline. Defaults to using pachyderm's official python language builder.
    * `update`: Whether to act as an upsert.
    * `pipeline_kwargs`: Keyword arguments to forward to `create_pipeline`.
    """

    return client.create_pipeline(
        pipeline_name or Path(path).name,
        Transform(
            image_pull_secrets=image_pull_secrets,
            debug=debug,
            env=env,
            secrets=secrets,
            build=BuildSpec(path=path, image=image) if image else BuildSpec(path=path, language="python"),
        ),
        update=update,
        input=input,
        **pipeline_kwargs
    )

def parse_json_pipeline_spec(j):
    """
    Parses a string of JSON into a `CreatePipelineRequest` protobuf.
    """
    return json_format.Parse(j, CreatePipelineRequest())

def parse_dict_pipeline_spec(d):
    """
    Parses a dict of serialized JSON into a `CreatePipelineRequest` protobuf.
    """
    return json_format.ParseDict(d, CreatePipelineRequest())


import requests
import json
import sqlite3
import datetime

#sqlite3 config
con = sqlite3.connect("/var/www/html/database/smart_bus3.db")
sqlite3.Connection

cursor = con.cursor()
cursor.execute("SELECT * FROM enroll_scan_beacon WHERE transmission is null")
enroll_rows = cursor.fetchall()

try:
    if enroll_rows:

        print("now enroll beacon data exist")
        cursor = con.cursor()
        cursor.execute("SELECT config_value FROM gateway_config WHERE config_property='center_id'")
        rows_c = cursor.fetchall()
        center = rows_c[0][0]

        cursor = con.cursor()
        cursor.execute("SELECT config_value FROM gateway_config WHERE config_property='gateway'")
        rows_g = cursor.fetchall()
        gateway = rows_g[0][0]

        data='{"enroll_beacon":['

        for i in range(0,len(enroll_rows)):
            data+='{'
            data+='"gateway":"'+ gateway +'",'
            data+='"center":"'+ center +'",'
            data+='"createtime":"'+ enroll_rows[i][0] +'",'
            data+='"mac_address":"'+ enroll_rows[i][1] +'",'
            data+='"uuid":"'+ enroll_rows[i][2] +'",'
            data+='"major":'+ str(enroll_rows[i][3]) +','
            data+='"minor":'+ str(enroll_rows[i][4]) +','
            data+='"rssi":'+ str(enroll_rows[i][5]) +','
            data+='"tx_power":'+ str(enroll_rows[i][6]) +''
            if i < len(enroll_rows)-1:
                data+='},'
            else:
                data+='}'

        data+=']}'

        for i in range(0,len(enroll_rows)):
            cursor = con.cursor()
            cursor.execute("UPDATE enroll_scan_beacon SET transmission = 1 WHERE createtime = '"+ enroll_rows[i][0] +"' AND mac_address  = '"+ enroll_rows[i][1] +"'")
            con.commit()

        url = "http://192.168.0.20:8080/gateway/enrollbeacon_insert"
        res = requests.post(url, data=(data))

        print("=========")
        print(data)

        print("enroll beacon data gateway to server")

    else:
        print("no enroll beacon data")

finally:
    con.close()
    print(" == enroll scan gateway to server end == ")


infile = open("./inputs/p14-3sum.txt")
first_line = infile.readline().rstrip().split(' ')
num_lists = int(first_line[0])
list_size = int(first_line[1])

outfile = open("./outputs/p14-3sum.txt", "w+")
for counter in range(num_lists):
    curr_list = [int(x) for x in infile.readline().rstrip().split(' ')]
    sorted_list = curr_list[:]
    sorted_list.sort()
    success = False
    for i in range(list_size):
        lo = i + 1
        hi = list_size - 1
        while lo < hi:
            a = sorted_list[i]
            b = sorted_list[lo]
            c = sorted_list[hi]
            if a + b + c == 0:
                res = [curr_list.index(a), curr_list.index(b), curr_list.index(c)]
                res.sort()
                res = " ".join([str(x + 1) for x in res])
                outfile.write(res)
                success = True
                break
            elif a + b + c > 0:
                hi -= 1
            else:
                lo += 1
        if success:
            break
    if not success:
        outfile.write("-1")
    outfile.write("\n")
infile.close()
outfile.close()


import models
import nrekit
import sys
from torch import optim
from nrekit.data_loader_bert import JSONFileDataLoaderBERT as DataLoader

from pytorch_pretrained_bert import BertAdam

max_length = 90
train_data_loader = DataLoader('./data/train_train.json', vocab='./data/bert_vocab.txt', max_length=max_length)
val_data_loader = DataLoader('./data/train_val.json', vocab='./data/bert_vocab.txt', max_length=max_length, rel2id=train_data_loader.rel2id, shuffle=False)

framework = nrekit.framework.SuperviseFramework(train_data_loader, val_data_loader)
sentence_encoder = nrekit.sentence_encoder.BERTSentenceEncoder('./data/bert-base-uncased')
model = models.snowball.Siamese(sentence_encoder, hidden_size=768, drop_rate=0.1)

model_name = 'bert_siamese_on_fewrel'

# set optimizer
batch_size = 32
train_iter = 30000

param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
    {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
    {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
    ]
optimizer = BertAdam(optimizer_grouped_parameters, lr=2e-5)

framework.train_siamese(model, model_name, optimizer=optimizer, batch_size=batch_size, train_iter=30000, learning_rate=2e-5, warmup=True)


#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import re
from collections import namedtuple
import peglet

Var = namedtuple('Var', ['name'])
StmtCmp = namedtuple('StmtCmp', ['left', 'op', 'right'])
SubBegin = namedtuple('SubBegin', ['name', 'args'])
SubEnd = namedtuple('SubEnd', [])
StmtAssign = namedtuple('StmtAssign', ['left', 'right'])
StmtElif = namedtuple('StmtElif', ['cond', 'body'])
StmtElse = namedtuple('StmtElse', ['body'])
StmtIf = namedtuple('StmtIf', ['cond', 'body', 'extra'])
StmtWhile = namedtuple('StmtWhile', ['cond', 'body'])
StmtVar = namedtuple('StmtVar', ['name'])
Label = namedtuple('Label', ['name'])
Line = namedtuple('Line', ['file', 'idx'])
Sub = namedtuple('Sub', ['name', 'args', 'body'])
Call = namedtuple('Call', ['name', 'args'])

class Parser(object):

    grammar = r"""
    wrapper     = ^ program $
    program     = statement program | statement
    statement   = space sub space

    _           = [\t\x20]*
    space       = \s* | comments
    newline     = [\r\n]+
    comment     = \# [^\r\n$]+ newline
    comments    = _ newline comments
                | _ newline _
                | _ comment comments
                | _ comment _
    split       = comments
                | comments split
                | _ ; _ split
                | _ ; _

    name        = ([a-zA-Z_][_a-zA-Z0-9]*\b)
    label       = : name                            make_label
    maybe_label = space label space
                | space
    line        = maybe_label stmt split
    lines       = line lines
                | line

    stmt        = var_assign | stmt_if | stmt_while | stmt_var | stmt_call
    var_assign  = var _ \= _ value                  make_assign

    sub         = begin lines end                   make_sub
    begin       = (\.begin\b) _ name_args split     clean_sub
    end         = (\.end\b)                         make_endsub

    name_args   = name sub_args                     make_subbegin
    sub_args    = _ var _ sub_args
                | _ var
                | _

    stmt_call   = name call_types                   make_call
    call_types  = _ label | call_args
    call_args   = _ value _ call_args
                | _ value
                | _

    stmt_var    = (\.var) _ var_or_assign           make_var
    var_or_assign = var_assign
                  | var

    stmt_while  = (\.while\b) space bool split lines space (\.end\b)    make_while

    if_body     = space bool split lines space
    stmt_else   = (\.else\b) space lines space
    stmts_else  = stmt_else                         make_else
                | space
    stmts_elif  = stmt_elif stmts_elif
                | stmt_elif
                | space
    stmt_elif   = (\.elif\b) if_body                make_elif
    if_tail     = stmts_elif stmts_else             listify
    begin_if    = (\.if\b) if_body                  make_if_begin
    end_if      = if_tail (\.end\b)
    stmt_if     = begin_if end_if                   make_if
    bool        = value _ opcmp _ value             make_cmp
    opcmp       = (==|!=)

    value       = var | \( space stmt_call space \)
    var         = \$ name                           token_var
    """

    def __init__(self):
        kwargs = {"make_endsub": lambda *args: SubEnd(),
                  "make_cmp": StmtCmp,
                  "make_assign": StmtAssign,
                  "make_label": Label,
                  "make_var": lambda *x: StmtVar(x[1]),
                  "make_while": lambda *x: StmtWhile(x[1], x[2:-1]),
                  "make_else": lambda *x: StmtElse(x[1:]),
                  "make_if": lambda *x: StmtIf(x[0][0], x[0][1], x[1]),
                  "make_if_begin": lambda *x: (x[1], x[2:]),
                  "make_elif": lambda *x: StmtElif(x[1], x[2:]),
                  "make_call": lambda *x: Call(x[0], x[1:]),
                  "make_sub": lambda *x: Sub(x[0].name, x[0].args, x[1:-1]),
                  "make_subbegin": lambda *args: SubBegin(args[0], args[1:]),
                  "clean_sub": lambda x, y: y,
                  "token_var": Var,
                  "hug"    : peglet.hug,
                  "listify": lambda *x: list(x),
                }
        self.parser = peglet.Parser(self.grammar, **kwargs)

    def __call__(self, program):
        return self.parser(program)

def str_expr(expr, inside=False):
    if isinstance(expr, Var):
        result = "$" + expr.name
    else:
        if isinstance(expr, StmtCmp):
            result = "%s %s %s" % (str_expr(expr.left, True), expr.op, str_expr(expr.right, True))
        elif isinstance(expr, StmtAssign):
            result = "%s = %s" % (str_expr(expr.left), str_expr(expr.right, True))
        elif isinstance(expr, Call):
            result = "%s %s" % (expr.name, str_expr(expr.args))
        elif isinstance(expr, (list, tuple)):
            result = " ".join([str_expr(X) for X in expr])
        else:
            raise RuntimeError("Unknown expression: %r" % (expr,))
        if inside:
            result = "(" + result + ")"
    return result

def print_token(token, level=0):
    indent = (" " * level * 4)
    if isinstance(token, Sub):
        print(indent + ".begin %s %s" % (
            token.name,
            ' '.join([
                '$' + arg.name
                for arg in token.args])))
        for subtoken in token.body:
            print_token(subtoken, level + 1)
        print(indent + ".end")
    elif isinstance(token, Label):
        print(indent + ":" + token.name)
    elif isinstance(token, Call):
        print(indent + token.name, str_expr(token.args))
    elif isinstance(token, StmtIf):
        print(indent + ".if", str_expr(token.cond))
        for subtoken in token.body:
            print_token(subtoken, level + 1)
        for substmt in token.extra:
            print_token(substmt, level)
        print(indent + ".end")
    elif isinstance(token, StmtElif):
        print(indent + ".elif", str_expr(token.cond))
        for subtoken in token.body:
            print_token(subtoken, level + 1)
    elif isinstance(token, StmtElse):
        print(indent + ".else")
        for subtoken in token.body:
            print_token(subtoken, level + 1)
    elif isinstance(token, StmtWhile):
        print(indent + ".while", str_expr(token.cond))
        for subtoken in token.body:
            print_token(subtoken, level + 1)
        print(indent + ".end")
    elif isinstance(token, StmtAssign):
        print(indent + str_expr(token.left), "=", str_expr(token.right))
    elif isinstance(token, StmtVar):
        print(indent + ".var", str_expr(token.name))
    else:
        raise RuntimeError("Unknown token: %r" % (token,))

class Driver(object):
    def tokenize_file(self, handle):
        parser = Parser()
        token_list = parser(handle.read())
        for token in token_list:
            print_token(token)
        return token_list

if __name__ == "__main__":
    compiler = Driver()
    for filepath in sys.argv[1:]:
        with open(filepath, 'r') as handle:
            compiler.tokenize_file(handle)


def find_island(x,y):
    dx = [0,1]
    dy = [1,0]
    check_x , check_y = 0,0
    cnt =0
    island = 0
    for i in range(x,N-1):
        for j in range(y,N-1):
            if data[i][j] != 0:
                check_x = i
                check_y = j
                if data[i+dx[0]][j+dy[0]] == 0 and data[i+dx[1]][j+dy[1]] == 0 and cnt>N-1:
                    print(1)
                return i, j
            else:
                cnt +=1

    # return island

def max_height():
    max_value = 0
    for i in range(N):
        for j in range(N):
            if data[i][j] >max_value:
                max_value = data[i][j]
    return max_value

# import sys
# sys.stdin = open("문제2.txt")

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    data = [list(map(int, input().split())) for i in range(N)]
    MAX_HEIGHT = 0
    ISLAND = 0
    # print(data)
    MAX_HEIGHT= max_height()
    for i in range(N):
        for j in range(N):
            if data[i][j] != 0:
                ISLAND = find_island(i,j)
                if ISLAND != 0:
                    ISLAND =2  # 출력만 되게 했음
    print(ISLAND)

    print('#%d %d %d' %(tc, ISLAND, MAX_HEIGHT))


#16. ファイルをN分割する
#自然数Nをコマンドライン引数などの手段で受け取り，入力のファイルを行単位で
# N分割せよ．同様の処理をsplitコマンドで実現せよ
import math
rfile = './hightemp.txt'
n = int(input('自然数を入力してください: '))
with open(rfile,mode='r',encoding='utf_8') as f:
    lines = f.readlines()

out = math.ceil(len(lines)/n)

for i,line in enumerate(lines):
        print(line.replace('\n',''))
        if i % out == out - 1:
            print('='*14)

#他の回答
#問題文が分かりづらい
#print('------\n'.join([''.join(lines[i * n:(i + 1) * n]) for i in range(0, math.ceil(len(lines) / n))]))

#他の回答
#import math

#fname = 'hightemp.txt'
#n = int(input('N--> '))

#with open(fname) as data_file:
#    lines = data_file.readlines()

#count = len(lines)
#unit = math.ceil(count / n)  # 1ファイル当たりの行数

#for i, offset in enumerate(range(0, count, unit), 1):
#    with open('child_{:02d}.txt'.format(i), mode='w') as out_file:
#        for line in lines[offset:offset + unit]:
#            out_file.write(line)


import pandas as pd

from pandas import DataFrame

from matplotlib import pyplot as plt

import seaborn as sns

from fpdf import FPDF

from algorithm import knn,naive,SVM,nn

import time

def details(data,df,newcolumn,image):

    pdf = FPDF(orientation='P', unit='mm',format='A4')

    pdf.add_page()

    pdf.set_font("Arial", size=12)

    epw = pdf.w - 2 * pdf.l_margin

    col_width = epw / 4

    pdf.set_font('Times', 'B', 35)

    pdf.cell(epw, 0.0, 'Drioditor', align='C')

    pdf.set_font('Times', '', 10.0)

    pdf.cell(200, 10, txt="\n", ln=1)

    pdf.cell(200, 10, txt="\n", ln=1)

    pdf.set_font('Times', 'B', 20)

    pdf.cell(epw, 0.0, 'Recommendation Report', align='C')

    pdf.set_font('Times', '', 10.0)

    pdf.ln(0.5)

    column = len(data)

    row = len(data[0])

    pdf.cell(200, 10, txt="\n", ln=1)

    pdf.cell(200, 10, txt="\n", ln=1)

    pdf.cell(200, 10, txt="Rows : {}".format(row), ln=1)

    pdf.cell(200, 10, txt="Columns : {}".format(column), ln=1)

    pdf.cell(200, 10, txt="Missing Values : {}".format(0), ln=1)

    avg=df.mean()

    median=df.median()

    mode=df.mode()[:1]

    pdf.set_font('Times', 'B', 14.0)

    pdf.set_font('Times', '', 10.0)

    pdf.ln(0.5)

    temp=[]

    temp.append("Feature \t" + "Average\t" +"Median\t" + "Mode\n" )

    for i in range(len(newcolumn)):

        temp.append(str(newcolumn[i])+"\t"+str(round(avg[i],5)) + "\t" + str(median[i])+"\t"+str(mode[i][0])+"\n")

    #print(temp)

    th = pdf.font_size

    """

    for row in temp:

        for datum in row.split(','):

            pdf.cell(col_width, th, str(datum), border=1)

        pdf.ln(th)

    pdf.ln(4 * th)

    pdf.set_font('Times', 'B', 14.0)

    pdf.cell(epw, 0.0, 'With more padding', align='C')

    pdf.set_font('Times', '', 10.0)

    """

    for row in temp:

        for datum in row.split(','):

            pdf.cell(col_width, 2 * th, str(datum), border=1)

        pdf.ln(2 * th)

    pdf.add_page()

    pdf.set_font('Times', 'B', 14)

    pdf.cell(epw, 0.0, 'Correlation Heatmap', align='C')

    pdf.set_font('Times', '', 10.0)

    pdf.ln(0.5)

    pdf.image('{}'.format(image),x=10,y=50)

    pdf.add_page()

    pdf.set_font('Times', 'B', 14)

    pdf.cell(epw, 0.0, 'Algorithm ', align='C')

    pdf.set_font('Times', '', 10.0)

    pdf.ln(0.5)

    max_accuracy,accuracy_name=0,""

    min_time, time_name=1000,""

    t=time.time()

    accuracy,tnr,tpr = knn('{}'.format(filename))

    t=time.time() -t

    if max_accuracy<accuracy :

        max_accuracy=accuracy

        accuracy_name='Knn'

    if min_time>t:

        min_time=t

        time_name='Knn'

    pdf.set_font('Times', 'B', 12)

    pdf.cell(200, 10, txt="Knn", ln=1)

    pdf.set_font('Times', '', 10.0)

    pdf.cell(210, 10, txt="Accuracy : {}".format(accuracy), ln=1)

    pdf.cell(210, 10, txt="TNR : {}".format(tnr), ln=1)

    pdf.cell(210, 10, txt="TPR : {}".format(tpr), ln=1)

    pdf.cell(210, 10, txt="Time Taken : {}".format(t), ln=1)

    #print(accuracy,tnr,tpr,t)

    t = time.time()

    accuracy, tnr, tpr = naive('{}'.format(filename))

    t = time.time() - t

    if max_accuracy<accuracy :

        max_accuracy=accuracy

        accuracy_name='Naive Bayes'

    if min_time>t:

        min_time=t

        time_name='Naive Bayes'

    pdf.set_font('Times', 'B', 12)

    pdf.cell(200, 10, txt="Naive Bayes", ln=1)

    pdf.set_font('Times', '', 10.0)

    pdf.cell(210, 10, txt="Accuracy : {}".format(accuracy), ln=1)

    pdf.cell(210, 10, txt="TNR : {}".format(tnr), ln=1)

    pdf.cell(210, 10, txt="TPR : {}".format(tpr), ln=1)

    pdf.cell(210, 10, txt="Time Taken : {}".format(t), ln=1)

    #print(accuracy, tnr, tpr, t)

    t = time.time()

    accuracy, tnr, tpr = SVM('{}'.format(filename))

    t = time.time() - t

    if max_accuracy<accuracy :

        max_accuracy=accuracy

        accuracy_name='SVM'

    if min_time>t:

        min_time=t

        time_name='SVM'

    pdf.set_font('Times', 'B', 12)

    pdf.cell(200, 10, txt="SVM", ln=1)

    pdf.set_font('Times', '', 10.0)

    pdf.cell(210, 10, txt="Accuracy : {}".format(accuracy), ln=1)

    pdf.cell(210, 10, txt="TNR : {}".format(tnr), ln=1)

    pdf.cell(210, 10, txt="TPR : {}".format(tpr), ln=1)

    pdf.cell(210, 10, txt="Time Taken : {}".format(t), ln=1)

    #print(accuracy, tnr, tpr, t)

    t = time.time()

    accuracy, tnr, tpr = nn('{}'.format(filename))

    t = time.time() - t

    if max_accuracy<accuracy :

        max_accuracy=accuracy

        accuracy_name='Neural Network'

    if min_time>t:

        min_time=t

        time_name='Neural Network'

    pdf.set_font('Times', 'B', 12)

    pdf.cell(200, 10, txt="Neural Network", ln=1)

    pdf.set_font('Times', '', 10.0)

    pdf.cell(210, 10, txt="Accuracy : {}".format(accuracy), ln=1)

    pdf.cell(210, 10, txt="TNR : {}".format(tnr), ln=1)

    pdf.cell(210, 10, txt="TPR : {}".format(tpr), ln=1)

    pdf.cell(210, 10, txt="Time Taken : {}".format(t), ln=1)

    #print(accuracy, tnr, tpr, t)

    pdf.add_page()

    pdf.set_font('Times', 'B', 14)

    pdf.cell(epw, 0.0, 'Recommendation', align='C')

    pdf.set_font('Times', '', 10.0)

    pdf.ln(0.5)

    pdf.cell(200, 10, txt="Based on Accuracy    : {} with accuracy {}%".format(accuracy_name,max_accuracy*100), ln=1)

    pdf.cell(200, 10, txt="Based on Time        : {} with time taken {}s".format(time_name,round(min_time,6)), ln=1)

    #print(max_accuracy,accuracy_name)

    #print(min_time,time_name)

    pdf.output('data/output.pdf', 'F')

def updateDataset(check, data):
    temp=[]
    for i in range(len(check)):
        if check[i] == 1:
            temp.append(data[i])
    return temp

def updateColumn(check, column):
    temp=[]
    for i in range(len(check)):
        if check[i] == 1:
            temp.append(column[i])
    return temp

def checkData(data,length):
    temp=[]
    for i in range(length):
        try:
            float(data[i][0])
            temp.append(1)
        except :
            temp.append(0)
    return temp

def convertData(data):
    temp=[]
    length = len(data[0].split(","))
    for i in range(length):
        test=[]
        for j in range(len(data)):
            test.append(data[j].split(',')[i])
        temp.append(test)
    return temp

if __name__ == '__main__':

    filename='data/iris.csv'
    f=open('{}'.format(filename) ,'r')
    data= f.readlines()
    f.close()

    column=data[0].split(",")
    column[-1] =column[-1].replace('\n','')
    data=data[1:]
    data=convertData(data)
    check = checkData(data,len(column))
    newColumn = updateColumn(check,column)
    newData = updateDataset(check,data)
    df = DataFrame(newData)
    df= df.transpose()
    df= df.apply(pd.to_numeric)
    correlation = df.corr()
    sns.heatmap(correlation,xticklabels=newColumn,yticklabels=newColumn)
    plt.savefig('data/test.jpg')
    details(data,df,newColumn,'data/test.jpg')


#!/usr/bin/env python

import sys
import numpy as np
from frovedis.exrpc.server import FrovedisServer
from frovedis.mllib.tsa.arima.model import ARIMA

desc = "Testing get_params() after performing fit() on numpy array: "

# initializing the Frovedis server
argvs = sys.argv
argc = len(argvs)
if argc < 2:
    print ('Please give frovedis_server calling command as the first argument \n'
           '(e.g. "mpirun -np 2 /opt/nec/frovedis/ve/bin/frovedis_server")')
    quit()
FrovedisServer.initialize(argvs[1])

# sample numpy array of shape (36,)
data = np.asarray([266, 145.9, 183.1, 119.3, 180.3,
                  168.5, 231.8, 224.5, 192.8, 122.9,
                  336.5, 185.9, 194.3, 149.5, 210.1,
                  273.3, 191.4, 287, 226, 303.6, 289.9,
                  421.6, 264.5, 342.3, 339.7, 440.4,
                  315.9, 439.3, 401.3, 437.4, 575.5,
                  407.6, 682, 475.3, 581.3, 646.9])

arima = ARIMA(endog=data, order=(2, 1, 2)).fit()

try:
    arima.get_params()
    print(desc, "Passed")
except:
    print(desc, "Failed")

FrovedisServer.shut_down()


import json
import os
from ibm_watson import VisualRecognitionV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from models.red_rhino_robot import alert_3r
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())
authenticator = IAMAuthenticator(os.getenv("WATSON_VISUAL_RECOG_API_KEY"))

COMBUSTIBLE_OBJ={'plant', 'grass', 'wood', 'paper', 'cardboard', 'cigarette', 'leaf', 'leaves', 'flame', 'fire'}
ALERT_OBJ={'fire', 'flame', 'combustion'}

def visual_recog(frame:str, location_name:str):
    """ IBM Watson visual recognition model"""
    visual_recognition = VisualRecognitionV3(
        version='2018-03-19',
        authenticator=authenticator
    )

    visual_recognition.set_service_url(os.getenv("SERVICE_URL"))

    url = frame
    classes_result = visual_recognition.classify(url=url).get_result()

    pred_classes=set()
    for item in classes_result['images'][0]['classifiers'][0]['classes']:
        pred_classes.add(item['class'])

    # Check for occurrence of fire and activate red rhino robot accordingly
    if(pred_classes & ALERT_OBJ):
        alert_3r(location_name)

    # Check for combustible
    if (pred_classes & COMBUSTIBLE_OBJ):
        return 1
    else:
        return 0


"""URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from __future__ import print_function
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularRedocView,
    SpectacularSwaggerView,
)

# Custom admin header
admin.site.site_header = "OpenFisca Django-API Administration"

urlpatterns = [
    path("api/", include(("api.urls", "api"), namespace="api")),
    path("entities/", include(("entities.urls", "entities"), namespace="entities")),
    path("variables/", include(("variables.urls", "variables"), namespace="variables")),
    url(r"^admin/", admin.site.urls),
    path("plots/", include(("plots.urls", "plots"), namespace="plots")),
    path(
        "activities/",
        include(("activities.urls", "activities"), namespace="activities"),
    ),
    # SWAGGER PATHS
    path(
        "",
        SpectacularSwaggerView.as_view(url_name="schema"),
        name="swagger-ui",
    ),
    path(
        "schema/",
        SpectacularAPIView.as_view(),
        name="schema",
    ),
    path(
        "api/",
        SpectacularSwaggerView.as_view(url_name="api-schema"),
        name="swagger-ui",
    ),
    path(
        "api/schema/", SpectacularAPIView.as_view(urlconf="api.urls"), name="api-schema"
    ),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

# Host the static from uWSGI
if settings.IS_WSGI:
    print("uWSGI mode, adding static file patterns")
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns

    urlpatterns += staticfiles_urlpatterns()

# Add debug toolbar
if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path("__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns


"""Plot value function results."""
import argparse
from protos import results_pb2
import numpy as np
import matplotlib as mlp
mlp.use('Agg')
from matplotlib import pyplot as plt

from matplotlib import rcParams
import os

def bool_argument(parser, name, default=False, msg=''):
    dest = name.replace('-', '_')
    parser.add_argument('--%s' % name, dest=dest, type=bool, default=default, help=msg)
    parser.add_argument('--no-%s' % name, dest=dest, type=bool, default=default, help=msg)

parser = argparse.ArgumentParser()
parser.add_argument('result_directory', help=help)
FLAGS = parser.parse_args()

rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath']

PSEC_LRS = set()

def read_proto(filename):
    results = results_pb2.MethodResult()
    with open(filename, 'rb') as f:
        results.ParseFromString(f.read())
    return results

def plot_data(data, file_name, plot_params):
    fig, ax = plt.subplots()
    fig.set_size_inches(13.5, 12.0, forward=True)

    for method in sorted(data):
        label = method

        print ('method ' + method)

        sorted_trajs = sorted(data[method])
        x = []
        y = []
        ylower = []
        yupper = []
        for num_traj in sorted_trajs:
            sorted_lrs = sorted(data[method][num_traj])
            if 'PSEC' in method:
                for lr in sorted_lrs:
                    #if lr == 0.05:
                    #    continue
                    errors = np.array(data[method][num_traj][lr])

                    n = len(errors) # number of trials
                    mean = np.mean(errors)
                    std = np.std(errors)
                    #if 'Lin' in method:
                    print ('number of errors for {} trajs: {}, mean MSE {} std {} '.format(lr, len(data[method][num_traj][lr]), mean, 1.96 * std / np.sqrt(float(n))))
                    #if mean < 450 :
                    #    print (', '.join(map(str, errors)))

                    #if mean >= 400:
                    #    continue
                    yerr = 1.96 * std / np.sqrt(float(n))
                    y.append(mean)
                    ylower.append(mean - yerr)
                    yupper.append(mean + yerr)
                    x.append(lr)
            else:
                x = list(PSEC_LRS)
                x = sorted(x)
                errors = np.array(data[method][num_traj][0])

                n = len(errors) # number of trials

                mean = np.mean(errors)
                std = np.std(errors)
                print ('number of errors for {} trajs: {}, MSE mean {}, std {}'.format(0, len(data[method][num_traj][0]), mean, 1.96 * std / np.sqrt(float(n))))
                #print (', '.join(map(str, errors)))
                yerr = 1.96 * std / np.sqrt(float(n))
                y = [mean for _ in range(len(x))]
                ylower = [mean - yerr for _ in range(len(x))]
                yupper = [mean + yerr for _ in range(len(x))]

            linestyle = '-'
            #linestyle = '-.'
            #linestyle = ':'
            if method == 'TD(0)':
                color = 'red'
                line, = plt.plot(x, y, label=label, linestyle = linestyle, linewidth = 5, color = color)
            else:
                line, = plt.plot(x, y, label=label, linestyle = linestyle, linewidth = 5)
            color = line.get_color()

            alpha = 0.5
            plt.fill_between(x, ylower, yupper, facecolor=color, alpha=alpha)

    if plot_params['log_scale']:
        ax.set_xscale('log')
        #ax.set_yscale('log')
    if plot_params['x_range'] is not None:
        plt.xlim(plot_params['x_range'])
    if plot_params['y_range'] is not None:
        plt.ylim(plot_params['y_range'])

    ax.xaxis.set_tick_params(labelsize=plot_params['tfont'])
    ax.yaxis.set_tick_params(labelsize=plot_params['tfont'])

    ax.set_xlabel(plot_params['x_label'], fontsize=plot_params['bfont'])
    ax.set_ylabel(plot_params['y_label'], fontsize=plot_params['bfont'])

    if plot_params['legend']:
        plt.legend(fontsize=plot_params['lfont'], loc=plot_params['legend_loc'],
                   ncol=plot_params['legend_cols'])
    fig.tight_layout()
    plt.savefig('{}.pdf'.format(file_name))
    plt.close()
    #plt.show()

def collect_data():

    data = {}
    td_method = 'td-0-vs-mdp'
    ristd_method = 'ris-' + td_method

    for basename in os.listdir(FLAGS.result_directory):
        filename = os.path.join(FLAGS.result_directory, basename)
        if '.err' in filename:
            continue
        try:
            results = read_proto(filename)
        except Exception as e:
            if 'Tag' not in str(e):
                raise e

        #method_TD(0)_trial_847277_trajs_9_alpha_0.010000_tiling_20_t1_15_t2_9_psec-act_0_psec-nh_0_psec-ne_0_psec-lr_0.000000
        #method_TD(0)_trial_847277_trajs_9_alpha_0.010000_tiling_20_t1_15_t2_9_psec-act_0_psec-nh_0_psec-ne_0_psec-lr_0.000000
        #print (basename)
        specs = basename.split('_')

        # thing that is fixed is the seed and traj size, finding best performing based on these two fixed points
        # if td looking at lr, tc, etc
        # if psec, looking at above AND the extra PSEC stuff

        method = specs[specs.index('method') + 1]

        num_trajs = int(results.num_trajs) #int(results.num_steps_observed[0])

        if method not in data:
            data[method] = {}
        if num_trajs not in data[method]:
            data[method][num_trajs] = {}

        psec_lr = float(specs[specs.index('psec-lr') + 1])

        if psec_lr not in data[method][num_trajs]:
            data[method][num_trajs][psec_lr] = []

        errs = results.value_error
        data[method][num_trajs][psec_lr].append(errs)

        if 'PSEC' in method:
            PSEC_LRS.add(psec_lr)

    return data

def main():

    if not FLAGS.result_directory:
        print ('No result directory given. Exiting.')
        return

    data = collect_data()

    plot_params = {'bfont': 40,
               'lfont': 35,
               'tfont': 40,
               'legend': True,
               'legend_loc': 0,
               'legend_cols': 2,
               'y_range': None,
               'x_range': None,
               'log_scale': True,
               'x_label': 'PSEC Learning Rate',
               'y_label': 'MSVE',
               'shade_error': True,
               'x_mult': 1}
    plot_data(data, 'temp1', plot_params)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from annotation.models import Worker,Entry,DammyEntry
import csv

def load_entry(csv,f,Obj,dammy=False):
    #for i,line in enumerate(f):
    #    line = line.strip().split(",")
    data_Reader = csv.reader(f)
    for i,line in enumerate(data_Reader):
        content_name = str(i).zfill(5)
        print(i,line)

        if dammy:
            c1,c2,c3,c4,c5,c6,c7,c8,c9,good,bad = line
            cont = Obj(name=content_name,id=str(i+1),
            cont1=c1,
            cont2=c2,
            cont3=c3,
            cont4=c4,
            cont5=c5,
            cont6=c6,
            cont7=c7,
            cont8=c8,
            cont9=c9,
            good_instance=good,
            bad_instance=bad,
            )
        else:
            c1,c2,c3,c4,c5,c6,c7,c8,c9 = line
            cont = Obj(name=content_name,id=str(i+1),
            cont1=c1,
            cont2=c2,
            cont3=c3,
            cont4=c4,
            cont5=c5,
            cont6=c6,
            cont7=c7,
            cont8=c8,
            cont9=c9,
            )

        cont.save()
    print("id:{} - saved, name:{}".format(i+1,content_name))

with open("Dummy_examples_R3.csv","r") as f:
    load_entry(csv,f,DammyEntry,dammy=True)

with open("Annotate_examples_R3.csv","r") as f:
    load_entry(csv,f,Entry)

print("the number of saved object of DammyEntry:", len(DammyEntry.objects.all()))
print("the number of saved object of Entry:", len(Entry.objects.all()))


'''Пересчёт скорости травления образца, в зависимости от состава матрицы.
Необходимо знать индексы точек перехода от одного слоя к другому.
Необходимо знать скорости травления в каждом слое.

Использование: python3 prog.py file.

'''

import csv
import numpy as np
import sys

def prog_usage():
    '''Печать инструкции использования.'''
    print('Использование: python3', sys.argv[0], 'файл данных.')

def file_read(file_input_path):
    data = {}
    with open(file_input_path) as file:
        points, legend = [], []
        for line in csv.reader(file):
            points.append(line)
        legend = points.pop(0)
        points = np.array(points)
        for number, element in enumerate(legend):
            data[element] = [float(i) for i in points[:, number]]
    return data

class DepthCalculator:
    '''Класс расчета списка глубины для гомо- и гетероструктур.'''

    control = []

    def __init__(self, init=1):
        self.layers = init

    def _speed_and_control(self):
        '''Ввод и проверка значения скорости.'''
        speed = float(input('Введите скорость травления слоя: '))
        while speed <= 0:
            print('Скорость травления не может быть отрицательна.')
            speed = float(input('''Введите скорость травления слоя: '''))
        return speed

    def _index_and_control(self):
        '''Ввод и проверка значения индекса.'''
        for layer in range(self.layers - 1):
            index = int(input('Введите индекс точки смены слоя: '))
            while index <= 0 or index in self.control:
                print('Индекс должен быть положительным числом. \
                      Значения индексов не могут повторяться. \
                      Повторите ввод.')
                index = int(input('Введите индекс точки смены слоя: '))
            self.control.append(index)
        return self.control

    def depth(self, grid):
        list_of_indexes = self._index_and_control()
        if list_of_indexes == []:
            speed = self._speed_and_control()
            depth = [grid[i] * speed for i in range(len(grid))]
        else:
            for layer in range(self.layers):
                if layer == 0:
                    speed = self._speed_and_control()
                    index = list_of_indexes[layer]
                    depth = [grid[i] for i in range(len(grid[:index]))]
                elif layer == self.layers - 1:
                    speed = self._speed_and_control()
                    index = list_of_indexes[layer - 1]
                    grid_end = grid[index:]
                    depth_end = [grid_end[i] * speed for i in
                                 range(len(grid_end))]
                    depth += depth_end
                else:
                    speed = self._speed_and_control()
                    index_left = list_of_indexes[layer - 1]
                    index_right = list_of_indexes[layer]
                    grid_middle = grid[index_left:index_right]
                    depth_middle = [grid_middle[i] * speed for i in
                                    range(len(grid_middle))]
                    depth += depth_middle
        return depth

if __name__ == '__main__':

    data = file_read(sys.argv[1])

    layers = int(input('Введите количество слоев: '))
    while layers <= 0:
        print('Количество слоев не может быть меньше либо равно нулю.')
        layers = int(input('Введите количество слоев: '))

    dc = DepthCalculator(layers)
    data['depth'] = dc.depth(data['time'])


from django.contrib import admin

from .models import *

# Register your models here.
#from django.contrib.auth.admin import UserAdmin
#admin.site.register(User, UserAdmin)

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import Perfil

class PerfilInline(admin.StackedInline):
    model = Perfil
    can_delete = False
    verbose_name_plural = 'Perfil'
    fk_name = 'user'
    list = ['admin']

class CustomUserAdmin(UserAdmin):
    inlines = (PerfilInline, )
    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

class EscuelaAdmin(admin.ModelAdmin):
    fields = ['cct',
              'nombre',
              'nivel',
              'componente',
              'accion',
              'cambio_comp',
              'director',
              'ciclo_esc',
              'municipio',
              'localidad',
              'monto_asignado',
              'monto_ejercido',
              'sispre'
              #contraloria_s',
              #'observacion'
    ]

class DirectoresAdmin (admin.ModelAdmin):
    fields = ['nombre','a_paterno','a_materno','telefono']

class Contraloria_SocialAdmin (admin.ModelAdmin):
    fields = ['estatus',
              'acta_constitucion',
              'minuta_constitucion',
              'lista_constitucion',
              'foto_constitucion',
              'cd_constitucion',
              'pdf_constitucion',
              'acta_seguimiento',
              'minuta_seguimiento',
              'lista_seguimiento',
              'foto_seguimiento',
              'cd_seguimiento',
              'pdf_seguimiento',
              'acta_anual',
              'minuta_anual',
              'lista_anual',
              'foto_anual',
              'cd_anual',
              'pdf_anual',
              'observacion',
              ]

class InicioSAdmin (admin.ModelAdmin):
    fields = ['estatus',
              'acta_mancomunado',
              'acta_mArchivo',
              'acta_mObservacion',
              'constancia_cepse',
              'constancia_cArchivo',
              'constancia_cObservacion',
              'acta_planeacion',
              'acta_pArchivo',
              'acta_pObservacion',
              'acuse_banco',
              'acuse_bArchivo',
              'acuse_bObservacion',
              'acuse_prog',
              'acuse_pArchivo',
              'acuse_pObservacion',
              'acuse_prog_anterior',
              'acuse_prog_aArchivo',
              'acuse_prog_aObservacion',
              'compromiso_inmueble',
              'compromiso_iArchivo',
              'compromiso_iObservacion',
              'compromiso_comunidad',
              'compromiso_cArchivo',
              'compromiso_cObservacion',
              'contrato',
              'contratoArchivo',
              'contratoObservacion',
              'ife_cepse',
              'ife_cArchivo',
              'ife_cObservacion',
              'ife_plantel',
              'ife_pArchivo',
              'ife_pObservacion',
              'comision_director',
              'comision_dArchivo',
              'comision_dObservacion',
              'observacion',
              'foto_fachada']

class SeguimientoAdmin(admin.ModelAdmin):
    fields = [
        'estatus',
        'acta_seguimiento',
        'acta_sArchivo',
        'acta_sObservacion',
        'sup_tecnica',
        'sup_tArchivo',
        'sup_tObservacion',
        'evid_seguimiento',
        'evid_sArchivo',
        'evid_sObservacion',
        'acta_circunstanciada',
        'acta_cArchivo',
        'acta_cObservacion',
        'observacion',
    ]

class CierreSAdmin(admin.ModelAdmin):
    fields = [
        'estatus',
        'acta_cierre',
        'acta_cArchivo',
        'acta_cObservacion',
        'acta_entrega',
        'acta_eArchivo',
        'acta_eObservacion',
        'acta_rendicion',
        'acta_rArchivo',
        'acta_rObservacion',
        'facturas',
        'facturasArchivo',
        'facturasObservacion',
        'ficha_reintegro',
        'ficha_rArchivo',
        'ficha_rObservacion',
        'form_inventario',
        'form_iArchivo',
        'form_iObservacion',
        'form_transferencia',
        'form_tArchivo',
        'form_tObservacion',
        'evid_obra_concluida',
        'evid_obraArchivo',
        'evid_obraObservacion',
        'evid_compras',
        'evid_cArchivo',
        'evid_cObservacion',
        'registro_gastos',
        'registro_gArchivo',
        'registro_gObservacion',
        'resumen_gastos',
        'resumen_gArchivo',
        'resumen_gObservacion',
        'verificacion_sat',
        'verificacionArchivo',
        'verificacionObservacion',
        'xml',
        'xmlArchivo',
        'xmlObservacion',
        'observacion',
    ]

class SISPREAdmin (admin.ModelAdmin):
    fields = [
        'inicio',
        'seguimiento',
        'cierre',
        'pdfCompleto'
    ]

class SupervisoresAdmin(admin.ModelAdmin):
    fields = ['cct',
              'nombre',
              'a_paterno',
              'a_materno',
              'telefono',
              'zona_escolar',
              'escuelas_zona',
              ]

#admin.site.register(Municipios,MunicipiosAdmin)
admin.site.register(Escuelas,EscuelaAdmin)
admin.site.register(Directores,DirectoresAdmin)
admin.site.register(Contraloria_Social,Contraloria_SocialAdmin)
admin.site.register(SISPRE,SISPREAdmin)
admin.site.register(Supervisores,SupervisoresAdmin)

admin.site.register(InicioS,InicioSAdmin)
admin.site.register(SeguimientoS,SeguimientoAdmin)
admin.site.register(CierreS,CierreSAdmin)


# splite3をimportする
import sqlite3
# flaskをimportしてflaskを使えるようにする
from flask import Flask , render_template , request , redirect , session,url_for
#時間ごとに処理する
import time
import re

app = Flask(__name__)

app.secret_key = 'sunabakoza'

#正規表現
def word_re(word):
    re_hiragana = re.compile(r'^[あ-ん]+$')
    return re_hiragana.fullmatch(word)

@app.route('/',methods=["GET", "POST"])
def top():
    if request.method == "GET":
        return render_template("index.html")
    else:
        #テーマ名を入力してDBに保存
        theme = request.form.get("theme")
        conn = sqlite3.connect('service.db')
        c = conn.cursor()
        c.execute("insert into themes values(null,?)", (theme,) )
        #テーマIDをthemeに代入
        c.execute("select id from themes where theme = ?",(theme,))
        theme_id = c.fetchone()
        conn.commit()
        conn.close()
        # user_id が NULL(PythonではNone)じゃなければログイン成功
        if theme_id is None:
            # ログイン失敗すると、ログイン画面に戻す
            return render_template("index.html")
        else:
            session['theme_id'] = theme_id[0]
            return redirect("/shiritori")

@app.route('/shiritori',methods=["GET","POST"])
def shiritori():
    if request.method == "GET":
        return render_template("shiritori.html")
    else:
        # １　開始ボタンを押すとしりとりゲームが始まる
        # 2 60秒のカウントダウン
        # 3 しりとりのデータを入れる
        #sessionからtheme_idを取得
        theme_id = session['theme_id']
        word = request.form.get("words")
        if not word_re(word):
            error_text = "ひらがなで入力してください"
            return render_template('shiritori.html',error_text = error_text)
        else:
            error_text = ""
            conn = sqlite3.connect('service.db')
            c = conn.cursor()
            #db shiritori に theme_idと単語をインサート
            c.execute("insert into shiritori values(?,?,null)", (theme_id,word,) )
            conn.commit()
            #db から最初に入力したテーマと紐づいている単語を取得
            c.execute("select word from shiritori where theme_id = ?",(theme_id,))
            words = []
            word_list = []
            for row in c.fetchall():
                words.append(row[0])
            for i in range(len(words)):
                list_item = words[i]
                word_list.append({"id":i,"word":list_item})

            conn.close()
            return render_template('shiritori.html',word_list = word_list,error_text = error_text)

## おまじない
if __name__ == "__main__":
    app.run(debug=True)


#!/usr/bin/python

import re

secret_code="asdfxxIxxasdghxxlovexxkjhgxxyouxxwwrkerjre"

line="xyz123"
a=re.findall("x....",line)

a=re.findall("xx(.*?)xx",secret_code)

for i in a:
    print(i)
#print a


#!python

import string
import re
# Hint: Use these string constants to ignore capitalization and/or punctuation
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters is ascii_lowercase + ascii_uppercase

LETTERS = string.ascii_letters

def is_palindrome(text):
    """A string of characters is a palindrome if it reads the same forwards and
    backwards, ignoring punctuation, whitespace, and letter casing."""
    # implement is_palindrome_iterative and is_palindrome_recursive below, then
    # change this to call your implementation to verify it passes all tests
    assert isinstance(text, str), 'input is not a string: {}'.format(text)

    return is_palindrome_iterative(text)
    # return is_palindrome_recursive(text)

def is_palindrome_iterative(text):
    # TODO: implement the is_palindrome function iteratively here

    ##Method 1:
    lowercase_text = text.lower()
    left = 0
    right = len(lowercase_text) - 1

    print(LETTERS)
    while left < right:
        ##TODO: Fails two test
        # current_left_character = lowercase_text[left]
        # current_right_character = lowercase_text[right]

        if lowercase_text[left] not in LETTERS:
            left += 1
            continue

        if lowercase_text[right] not in LETTERS:
            right -= 1
            continue

        if lowercase_text[left] is not lowercase_text[right]:
            return False

        left += 1
        right -= 1

    return True
    ##Method 2:
    # S/O Stack Overflow for Regex. Link: https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python
    # text = re.sub(r'\W+', '', text).lower()

    # left = 0
    # right = len(text) - 1

    # while left < right:
    #     if text[left] is not text[right]:
    #         return False

    #     left += 1
    #     right -= 1

    # return True

    # once implemented, change is_palindrome to call is_palindrome_iterative
    # to verify that your iterative implementation passes all tests

def is_palindrome_recursive(text, left=None, right=None):
    # TODO: implement the is_palindrome function recursively here
    lowercase_text = text.lower()

    if left == None and right == None:
        left = 0
        right = len(text) - 1

    if left <= right:
        if lowercase_text[left] not in LETTERS:
            left_index = left + 1
            return is_palindrome_recursive(text, left_index, right)

        if lowercase_text[right] not in LETTERS:
            right_index = right - 1
            return is_palindrome_recursive(text, left, right_index)

        if lowercase_text[left] is not lowercase_text[right]:
            return False

        return is_palindrome_recursive(text, left + 1, right - 1)

    return True

    # once implemented, change is_palindrome to call is_palindrome_recursive
    # to verify that your iterative implementation passes all tests

def main():
    import sys
    args = sys.argv[1:]  # Ignore script file name
    if len(args) > 0:
        for arg in args:
            is_pal = is_palindrome(arg)
            result = 'PASS' if is_pal else 'FAIL'
            is_str = 'is' if is_pal else 'is not'
            print('{}: {} {} a palindrome'.format(result, repr(arg), is_str))
    else:
        print('Usage: {} string1 string2 ... stringN'.format(sys.argv[0]))
        print('  checks if each argument given is a palindrome')

if __name__ == '__main__':
    main()


import os
import cv2
import torch
import time
import random
import warnings
import torchvision as tv
import albumentations as albu
import numpy as np
from config import configs
from PIL import ImageFile
from glob import glob
from utils.reader import SegDataset
from utils.losses import *
from utils.optimizers import get_optimizer
from utils.utils import AverageMeter,get_lr,iou_metric,dice_metric,save_checkpoint
from utils.logger import Logger
from utils.metrics import Evaluator
from utils.warmup import GradualWarmupScheduler
from sklearn.model_selection import train_test_split
from albumentations import pytorch as AT
import segmentation_models_pytorch as smp
from progress.bar import Bar
from tensorboardX import SummaryWriter

# set defaul configs
ImageFile.LOAD_TRUNCATED_IMAGES = True
warnings.filterwarnings("ignore")
os.environ['CUDA_VISIBLE_DEVICES'] = configs.gpu_id
evaluator = Evaluator(configs.num_classes)
# set random seed
def seed_everything(seed):
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
seed_everything(configs.seed)

# make dir for use
def makdir():
    if not os.path.exists(configs.log_dir):
        os.makedirs(configs.log_dir)
    if not os.path.exists(configs.checkpoints):
        os.makedirs(configs.checkpoints)
    if not os.path.exists(configs.pred_mask):
        os.makedirs(configs.pred_mask)
makdir()

best_iou = 0
best_dice = 0
# augumentations
def get_training_augmentation():
    # for train
    train_transform = [
        albu.Resize(height=configs.input_size,width=configs.input_size),
        albu.HorizontalFlip(p=0.5),
        albu.VerticalFlip(p=0.5),
        albu.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), p=1),
        AT.ToTensor(),
    ]
    return albu.Compose(train_transform)
def stong_aug():
    # strong aug for  train
    train_transform = [
        albu.Resize(height=configs.input_size,width=configs.input_size),
        albu.HorizontalFlip(p=0.5),
        albu.VerticalFlip(p=0.5),
        albu.RandomRotate90(p=0.5),
        albu.OneOf([
            albu.CenterCrop(p=0.5,height=configs.input_size,width=configs.input_size),
            albu.ElasticTransform(p=0.5, alpha=120, sigma=120 * 0.05, alpha_affine=120 * 0.03),
            albu.GridDistortion(p=0.5),
            albu.OpticalDistortion(p=1, distort_limit=1, shift_limit=0.5),
        ],p=0.8),
        albu.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), p=1),
        AT.ToTensor(),
    ]
    return albu.Compose(train_transform)
def get_valid_augmentation():
    # for valid
    valid_transform = [
        albu.Resize(height=configs.input_size,width=configs.input_size),
        albu.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), p=1),
        AT.ToTensor(),
    ]
    return albu.Compose(valid_transform)
def main():
    global best_iou
    global best_dice
    # model
    model = smp.Unet(
    encoder_name=configs.encoder,
    encoder_weights=configs.encoder_weights,
    classes=configs.num_classes,
    activation=configs.activation)
    if len(configs.gpu_id)>1:
        model = nn.DataParallel(model)
    model.cuda()
    # get files
    filenames = glob(configs.dataset+"masks/*")
    filenames = [os.path.basename(i) for i in filenames]
    # random split dataset into train and val
    train_files, val_files = train_test_split(filenames, test_size=0.2)
    # define different aug
    if configs.use_strong_aug:
        transform_train = stong_aug()
    else:
         transform_train = get_training_augmentation()
    transform_valid = get_valid_augmentation()
    # make data loader for train and val
    train_dataset = SegDataset(train_files,phase="train",transforms = transform_train)
    valid_dataset = SegDataset(val_files,phase="valid",transforms = transform_valid)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=configs.bs, shuffle=True, num_workers=configs.workers)
    valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=configs.bs, shuffle=False, num_workers=configs.workers)
    optimizer = get_optimizer(model)
    loss_func = get_loss_func(configs.loss_func)
    criterion = loss_func().cuda()
    # tensorboardX writer
    writer = SummaryWriter(configs.log_dir)
    # set lr scheduler method
    if configs.lr_scheduler == "step":
        scheduler_default = torch.optim.lr_scheduler.StepLR(optimizer,step_size=10,gamma=0.1)
    elif configs.lr_scheduler == "on_loss":
        scheduler_default = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=5, verbose=False)
    elif configs.lr_scheduler == "on_iou":
        scheduler_default = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.2, patience=5, verbose=False)
    elif configs.lr_scheduler == "on_dice":
        scheduler_default = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.2, patience=5, verbose=False)
    elif configs.lr_scheduler == "cosine":
        scheduler_default = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, configs.epochs-configs.warmup_epo)
    else:
        scheduler_default = torch.optim.lr_scheduler.StepLR(optimizer,step_size=6,gamma=0.1)
    # scheduler with warmup
    if configs.warmup:
        scheduler = GradualWarmupScheduler(optimizer, multiplier=configs.warmup_factor, total_epoch=configs.warmup_epo, after_scheduler=scheduler_default)
    else:
        scheduler = scheduler_default
    for epoch in range(configs.epochs):
        print('\nEpoch: [%d | %d] LR: %.8f' % (epoch + 1, configs.epochs, optimizer.param_groups[0]['lr']))
        train_loss,train_dice,train_iou = train(train_loader,model,criterion,optimizer,epoch,writer)
        valid_loss,valid_dice,valid_iou = eval(valid_loader,model,criterion,epoch,writer)
        if configs.lr_scheduler == "step" or configs.lr_scheduler == "cosine" or configs.warmup:
            scheduler.step(epoch)
        elif configs.lr_scheduler == "on_iou":
            scheduler.step(valid_iou)
        elif configs.lr_scheduler == "on_dice":
            scheduler.step(valid_dice)
        elif configs.lr_scheduler == "on_loss":
            scheduler.step(valid_loss)
        # save model
        is_best_iou = valid_iou > best_iou
        is_best_dice = valid_dice > best_dice
        best_iou = max(valid_iou, best_iou)
        best_dice = max(valid_dice,best_dice)
        print("Best {}: {} ,Best Dice: {}".format(configs.metric,best_iou,best_dice))
        save_checkpoint({
            'state_dict': model.state_dict(),
        },is_best_iou,is_best_dice)

def train(train_loader, model, criterion, optimizer, epoch,writer):
    # switch to train mode
    model.train()

    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()
    Dice_coeff = AverageMeter()
    Iou = AverageMeter()
    end = time.time()
    evaluator.reset()
    bar = Bar('Training: ', max=len(train_loader))
    for batch_idx, (inputs, targets) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)
        inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = torch.autograd.Variable(inputs), torch.autograd.Variable(targets)
        outputs = model(inputs)
        # compute output
        loss = criterion(outputs, targets)
        # compute iou
        iou_batch = iou_metric(outputs,targets,classes = [str(i) for i in range(configs.num_classes)])
        # compute metric
        dice_batch = dice_metric(outputs,targets)
        # update
        losses.update(loss.item(), inputs.size(0))
        Dice_coeff.update(dice_batch.item(), inputs.size(0))
        target = targets.cpu().numpy()
        pred = outputs.data.cpu().numpy()
        pred = np.argmax(pred, axis=1)
        target = np.argmax(target, axis=1)
        evaluator.add_batch(target, pred)
        if configs.metric == "mIoU":
            iou_value = evaluator.Mean_Intersection_over_Union()
        else:
            iou_value = evaluator.Frequency_Weighted_Intersection_over_Union()
        Iou.update(iou_value, inputs.size(0))

        # compute gradient and do SGD step
        optimizer.zero_grad()
        loss.backward()
        # clip gradient
        #torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0, norm_type=2)
        optimizer.step()

        # measure elapsed time
        batch_time.update(time.time() - end)
        end = time.time()

        # plot progress
        bar.suffix  = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | Dice_coeff: {Dice_coeff: .4f} | {metric}: {Iou: .4f}'.format(
                    batch=batch_idx + 1,
                    size=len(train_loader),
                    data=data_time.val,
                    bt=batch_time.val,
                    total=bar.elapsed_td,
                    eta=bar.eta_td,
                    loss=losses.avg,
                    Dice_coeff=Dice_coeff.avg,
                    metric=configs.metric[0],
                    Iou=Iou.avg,
                    )
        writer.add_scalar("Train-Loss",losses.avg,epoch)
        writer.add_scalar("Train-%s"%configs.metric,Iou.avg,epoch)
        writer.add_scalar("Train-Dice",Dice_coeff.avg,epoch)

        bar.next()
    bar.finish()
    return (losses.avg, Dice_coeff.avg, Iou.avg)

def eval(valid_loader, model, criterion, epoch,writer):
    # switch to train mode
    model.eval()
    global best_dice
    global best_iou
    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()
    Dice_coeff = AverageMeter()
    Iou = AverageMeter()
    end = time.time()
    evaluator.reset()
    bar = Bar('Validing: ', max=len(valid_loader))
    with torch.no_grad():
        for batch_idx, (inputs, targets) in enumerate(valid_loader):
            # measure data loading time
            data_time.update(time.time() - end)
            inputs, targets = inputs.cuda(), targets.cuda()
            inputs, targets = torch.autograd.Variable(inputs), torch.autograd.Variable(targets)
            outputs = model(inputs)
            # compute output
            loss = criterion(outputs, targets)
            # compute iou
            iou_batch = iou_metric(outputs,targets,classes = [str(i) for i in range(configs.num_classes)])
            # compute metric
            dice_batch = dice_metric(outputs,targets)
            # update
            losses.update(loss.item(), inputs.size(0))
            Dice_coeff.update(dice_batch.item(), inputs.size(0))
            target = targets.cpu().numpy()
            pred = outputs.data.cpu().numpy()
            pred = np.argmax(pred, axis=1)
            target = np.argmax(target, axis=1)
            evaluator.add_batch(target, pred)
            if configs.metric == "mIoU":
                iou_value = evaluator.Mean_Intersection_over_Union()
            else:
                iou_value = evaluator.Frequency_Weighted_Intersection_over_Union()
            Iou.update(iou_value, inputs.size(0))
            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            # plot progress
            bar.suffix  = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | Dice_coeff: {Dice_coeff: .4f} | {metric}: {Iou: .4f}'.format(
                        batch=batch_idx + 1,
                        size=len(valid_loader),
                        data=data_time.val,
                        bt=batch_time.val,
                        total=bar.elapsed_td,
                        eta=bar.eta_td,
                        loss=losses.avg,
                        Dice_coeff=Dice_coeff.avg,
                        metric=configs.metric[0],
                        Iou=Iou.avg,
                        )
            bar.next()
            writer.add_scalar("Valid-Loss",losses.avg,epoch)
            writer.add_scalar("Valid-%s"%configs.metric,Iou.avg,epoch)
            writer.add_scalar("Valid-Dice",Dice_coeff.avg,epoch)
        bar.finish()
    return (losses.avg, Dice_coeff.avg, Iou.avg)

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# Title      : PyRogue febBoard Module
#-----------------------------------------------------------------------------
# File       : SingleNodeTest.py
# Created    : 2016-11-09
# Last update: 2016-11-09
#-----------------------------------------------------------------------------
# Description:
# Rogue interface to FEB board
#-----------------------------------------------------------------------------
# This file is part of the LCLS2-PRL. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
#    https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
# No part of the LCLS2-PRL, including this file, may be
# copied, modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.
#-----------------------------------------------------------------------------

import sys
import pyrogue as pr
import pyrogue.gui
import PyQt4.QtGui
import argparse
import Lsst5vDcPdu  as board5v
import Lsst24vDcPdu as board24v

# Set the argument parser
parser = argparse.ArgumentParser()

# Add arguments
parser.add_argument(
    "--type",
    type     = str,
    required = True,
    help     = "board type (5VC, 24VC, 24VD  or 48VD)",
)

parser.add_argument(
    "--ip",
    type     = str,
    required = True,
    help     = "IP address",
)

parser.add_argument(
    "--hwEmu",
    type     = bool,
    required = False,
    default  = False,
    help     = "hardware emulation (false=normal operation, true=emulation)",
)

parser.add_argument(
    "--pollEn",
    type     = bool,
    required = False,
    default  = False,
    help     = "enable auto-polling",
)

# Get the arguments
args = parser.parse_args()

# Set base
base = pr.Root(name='base',description='')

# Determine the type
if ( args.type == '5VC' ):
    # Add Base Device
    base.add(board5v.Top(
        ip    = args.ip,
        nChannels = 20,
        shunts = (12.8, 12.8, 12.8, 12.8, 12.8, 12.8, 10e5, 10e5, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2, 51.2),
        hwEmu = args.hwEmu,
    ))
elif ( args.type == '24VC'):
   # Add Base Device
    base.add(board24v.Top(
        ip    = args.ip,
        hwEmu = args.hwEmu,
        nChannels = 12,
        shunts = ( 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ),
        VScale = 0.03973,
        IScale = 0.0488,
    ))
elif ( args.type == '24VD'):
   # Add Base Device
    base.add(board24v.Top(
        ip    = args.ip,
        hwEmu = args.hwEmu,
        nChannels = 12,
        shunts = (4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ),
        VScale = 0.03973,
        IScale = 0.0488,
    ))
elif  ( args.type == '48VD'):
   # Add Base Device
    base.add(board24v.Top(
        ip    = args.ip,
        hwEmu = args.hwEmu,
        nChannels = 12,
        shunts = (4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ),
        VScale = 0.06772,
        IScale = 0.0282,
    ))

else:
    raise ValueError("Invalid type (%s). Valid types are 5VC, 24VC, 24VD, 48VD" % (args.type) )

# Start the system
base.start(pollEn=args.pollEn)
base.Top.Fpga.Core.AxiVersion.printStatus()

# Create GUI
appTop = PyQt4.QtGui.QApplication(sys.argv)
appTop.setStyle('Fusion')
guiTop = pyrogue.gui.GuiTop(group='rootMesh')
guiTop.addTree(base)
guiTop.resize(800, 1000)

print("Starting GUI...\n");

# Run GUI
appTop.exec_()

base.stop()
exit()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_page, name='home'),
    path('contact', views.contact_page, name='contact'),
    path('about', views.about_page, name='about'),
    path('blog', views.blog_page, name='blog'),
    path('portfolio', views.portfolio_page, name='portfolio'),
    path('get_in_touch', views.get_in_touch, name='get_in_touch'),
    path('<slug:post>', views.post_detail, name='post_detail'),
]


import numpy as np
import cv2
import matplotlib.pyplot as plt
import seaborn as sns
s1=0
def make_blocks(pixel,stride,kernel,img_size):
    blocks=[]
    index=[]
    #blocks = np.array([pixel[i:i+kernel, j:j+kernel] for j in range(0,img_size,kernel) for i in range(0,img_size,kernel)])
    for i in range(0,img_size,stride):
        for j in range(0,img_size,stride):

            if j+kernel>img_size and i+kernel>img_size:
                k=i+kernel-img_size
                l=j+kernel-img_size
                ind1=[]
                a=[]
                for p in range(i,img_size):
                    b=[]
                    ind2=[]
                    for q in range(j,img_size):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    for m in range(l):
                        c=[]
                        b.append(pixel[p][m])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][m]))
                        ind2.append(c)
                    a.append(b)
                    ind1.append(ind2)
                    #print(ind1)

                for p in range(k):
                    b=[]
                    ind2=[]
                    for q in range(j,img_size):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    for m in range(l):
                        c=[]
                        b.append(pixel[p][m])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][m]))
                        ind2.append(c)
                    a.append(b)
                    ind1.append(ind2)
                blocks.append(a)
                index.append(ind1)

            elif j+kernel>img_size:
                k=j+kernel-img_size
                a=[]
                ind1=[]
                for p in range(i,i+kernel):
                    b=[]
                    ind2=[]
                    for q in range(j,img_size):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    for l in range(k):
                        c=[]
                        b.append(pixel[p][l])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][l]))
                        ind2.append(c)
                    a.append(b)
                    ind1.append(ind2)
                blocks.append(a)
                index.append(ind1)

            elif i+kernel>img_size:
                k=i+kernel-img_size
                a=[]
                ind1=[]
                for p in range(i,img_size):
                    b=[]
                    ind2=[]
                    for q in range(j,j+kernel):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    #print(ind2)
                    a.append(b)
                    ind1.append(ind2)
                #print(np.array(ind1).shape)
                for p in range(k):
                    b=[]
                    ind2=[]
                    for q in range(j,j+kernel):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    a.append(b)
                    ind1.append(ind2)
                blocks.append(a)
                index.append(ind1)
            else:
                #blocks.append(pixel[i:i+kernel,j:j+kernel])
                a=[]
                ind1=[]
                for p in range(i,i+kernel):
                    b=[]
                    ind2=[]
                    for q in range(j,j+kernel):
                        c=[]
                        b.append(pixel[p][q])
                        c.append(p)
                        c.append(list(pixel[p]).index(pixel[p][q]))
                        ind2.append(c)
                    #print(ind2,"\n")
                    a.append(b)
                    ind1.append(ind2)
                #print(ind1,"\n")
                blocks.append(a)
                index.append(ind1)
                #print(np.array(ind1).shape)

    blocks=np.array(blocks)
    index=np.array(index)
    #print(blocks)
    print(blocks.shape)
    print(index.shape)
    #print(blocks[0])
    #print(index[0])
    return blocks,index

def diff_block_div_one(blocks):
    pixel1=[]
    q=[]
    e2=[]
    ind=1
    for array in blocks:
        b=[]
        q1=[]
        med=np.median(array)
        #print(int(med))
        sl=0
        for i in range(len(array[0])):
            a=[]
            for j in range(len(array[i])):
                a.append(int(med)-array[i][j])
                if(int(med)-array[i][j]==0):
                    sl=sl+1
            b.append(a)
        pixel1.append(b)
        s=sum(x.count(0) for x in b)
        if(s<=1):
            e2.append(ind)
        q1.append(ind)
        q1.append(sl)
        q.append(q1)
        ind=ind+1
    pixel1=np.array(pixel1)
    #print(pixel1)
    #print(pixel1.shape)
    #print(q)
    return q,pixel1,e2

def diff_block_div_two(blocks,pixel1,e2):
    pixel2=[]
    q2=[]
    for b in e2:
        g=[]
        s=[]
        bl=[]
        q1=[]
        med1=0
        med2=0
        med=int(np.median(blocks[b-1]))
        #print(int(med))
        sl=0
        for i in range(len(blocks[b-1][0])):
            for j in blocks[b-1][i]:
                if(j>med):
                    g.append(j)
                elif j<med:
                    s.append(j)
                else:
                    continue
        med1=int(np.median(g))
        med2=int(np.median(s))
        if not g:
            med1=0
        if not s:
            med2=0
        #print(med1,med2)
        #print(med)

        for i in range(len(blocks[b-1][0])):
            a=[]
            for j in blocks[b-1][i]:
                if(j>med):
                    if(med1!=0):
                        a.append(med1-j)
                    else:
                        a.append(j)
                elif j<med:
                    if(med2!=0):
                        a.append(med2-j)
                    else:
                        a.append(j)
                else:
                    a.append(med-j)
                if(med-j==0 or med1-j==0 or med2-j==0 ):
                    sl=sl+1
            bl.append(a)
        pixel2.append(bl)
        #pixel1[b-1]=bl
        q1.append(b)
        q1.append(sl)
        q2.append(q1)

    #print(np.array(pixel2))
    #print("\n")
    #print(q2)
    return q2,pixel2

def draw_cumulative_histogram(x1,x2,x3):
    # List of five airlines to plot
    sl = ['smooth level 1', 'smooth level 2', 'smooth level 3']

    # Iterate through the five airlines
    for sls in sl:

        if(sls=='smooth level 1'):
            z=x1
        elif(sls=='smooth level 2'):
            z=x2
        else:
            z=x3
        # Draw the density plot
        sns.distplot(z, hist = False, kde = True,
                     kde_kws = {'linewidth': 3},
                     label =sls)

    # Plot formatting
    plt.legend(prop={'size': 10}, title = 'levels')
    plt.title('comparision of difference historam')
    plt.xlabel('difference with the reference value')
    plt.ylabel('possibility percentage')

def tsl_calculate(q1,q2,thresold):
    count={}
    count1={}
    block1={}
    block2={}
    for i in q1:
        if i[1] not in count:
            count[i[1]]=0
        count[i[1]]+=1
        if i[1]>=thresold:
            if i[1] not in block1:
                block1[i[1]]=[]
            block1[i[1]].append(i[0])

    for i in q2:
        if i[1] not in count1:
            count1[i[1]]=0
        count1[i[1]]+=1
        if i[1]>=thresold:
            if i[1] not in block2:
                block2[i[1]]=[]
            block2[i[1]].append(i[0])
    return count,count1,block1,block2

def make_dataset(pixel1,q3,kern,thresold,file_name):
    with open(file_name,"w") as f:
        for i in range(kern**2):
            f.write("x{},".format((i+1)))
        f.write("label\n")

    with open(file_name,"a") as f:
        c=0
        for i in q3:
            p=pixel1[i[0]-1]
            if i[1]>=thresold:
                c=c+1
                for k in range(len(p[0])):
                    for n in range(len(p[k])):
                        f.write("{},".format(p[k][n]))
                f.write("ROI\n")
            else:
                for k in range(len(p[0])):
                    for n in range(len(p[k])):
                        f.write("{},".format(p[k][n]))
                f.write("NROI\n")
   #return c

def main(img_size,thresold):
    img=cv2.resize(cv2.imread('C:/Users/User/Untitled Folder 2/lena.jpeg',0),(img_size,img_size))
    #np.reshape(img,[img_size,img_size])
    plt.imshow(img,cmap="gray")
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()

    pixel=np.array(img)
    #print(pixel)
    #print(pixel)
    print(pixel.shape,len(pixel))
    stride=[1,2,3,4,5]
    kernel=[3,4,5,7]
    optimal=[]
    for i in stride:
        for l in kernel:
            opt=[]
            print("\nfor stride = ",i," and kernel = ",l)
            blocks,index=make_blocks(pixel,i,l,img_size)
            print("total smooth level before dividing blocks: ")
            q3,pixel1,e2=diff_block_div_one(blocks)
            q4,pixel2=diff_block_div_two(blocks,pixel1,e2)
            total_sl,total_sl1,block1,block2=tsl_calculate(q3,q4,thresold)
            print(total_sl)
            #print("\nblocks for different smooth level: ",sorted(block1))
            print("\ntotal smooth level after dividing blocks: ",total_sl1)
            #print("\nblocks for different smooth level: ",sorted(block2))
            tsl=0
            tsl1=0
            for j in total_sl.keys():
                if j>=thresold:
                    tsl+=total_sl[j]
                    tsl1=tsl1+j*total_sl[j]

            opt.append(i)
            opt.append(l)
            opt.append(tsl)
            opt.append(tsl1)
            optimal.append(opt)

    print(optimal)
    strd=optimal[0][0]
    kern=optimal[0][1]
    m=optimal[0][2]
    m1=optimal[0][3]

    for j in optimal:
        if j[3]>m1:
            strd=j[0]
            kern=j[1]
            m=j[2]
            m1=j[3]

    print("\noptimal tecnique is for stride: ",strd," and kernel: ",kern," with total smooth level>",thresold,":",m,"total smooth level: ",m1)
    print("\nfor stride = ",strd," and kernel = ",kern)

    blocks,index=make_blocks(pixel,strd,kern,img_size)
    q3,pixel1,e2=diff_block_div_one(blocks)
    q4,pixel2=diff_block_div_two(blocks,pixel1,e2)
    total_sl,total_sl1,block1,block2=tsl_calculate(q3,q4,thresold)

    for j in q3:
       #x=[]
       #y=[]
       if j[1]>=thresold:
            p=pixel1[j[0]-1]
            inx=index[j[0]-1]
            blocks,index1=make_blocks(p,1,2,kern)
            ind2=0
            for i in blocks:
                s=sum(list(x).count(0) for x in i)
                if s>=2:
                    inx1=index1[ind2]
                    xx1,yy1=inx1[0][0]
                    xx2,yy2=inx1[-1][-1]
                    x1,y1=inx[xx1][yy1]
                    x2,y2=inx[xx2][yy2]
                    cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,0),1)
                ind2+=1

            #cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,0),3)
            """
            for k in range(len(p[0])):
                for n in range(len(p[k])):
                    if p[k][n]==0:
                        x.append(inx[k][n][0])
                        y.append(inx[k][n][1])
            for j in range(len(x)-1):
                cv2.line(img,(x[j],y[j]),(x[j+1],y[j+1]),(255,0,0),2)"""

    plt.imshow(img,cmap="gray")
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()
    #make_dataset(pixel1,q3,kern,thresold,"sdcvg.csv")
    return pixel1,q3,kern,strd

    #thresold=[5,7,10,12]
   #roi=[]
   #roi.append(0)
   #j=0
   #th=0
    #or i in thresold:
       #roi.append(make_dataset(pixel1,q3,kern,i))
       #if(roi[j]-roi[j+1] in [1,2,3,4,5,6]):
          # th=i
          # break
   #print("thresold: ",th," roi: ",r)

'''
if __name__=="__main__":
    img_size=50
    pixel1,q3,kern,strd=main(img_size,10)
'''


import pygame, sys
from pygame.locals import *
from gl import *

from math import cos, sin, pi

mainClock = pygame.time.Clock()

pygame.init()
pygame.display.set_caption('Lab 3 UI')
screen = pygame.display.set_mode((1000,500),0,32)

font = pygame.font.SysFont("Arial", 30)

def updateFPS():
    fps = str(int(clock.get_fps()))
    fps = font.render(fps, 1, pygame.Color("white"))
    return fps

def main_menu():
    while True:

        screen.fill(pygame.Color("dimgray")) #color de fondo
        textobj = font.render('LAB3RINTO', 1, (255, 255, 255))  #titulo del juego
        textrect = textobj.get_rect()
        textrect.topleft = (20, 20) #posicion x,y del juego
        screen.blit(textobj, textrect)

        mx, my = pygame.mouse.get_pos()

        button_1 = pygame.Rect(50, 100, 200, 50)
        button_2 = pygame.Rect(350, 100, 200, 50)
        if button_1.collidepoint((mx, my)):
          if click:
            gotogame()
        if button_2.collidepoint((mx, my)):
          if click:
            exit()

        pygame.draw.rect(screen, (255, 0, 0), button_1)
        pygame.draw.rect(screen, (255, 0, 0), button_2)

        textobj = font.render('Iniciar', 1, (255, 255, 255))  #titulo del juego
        textrect = textobj.get_rect()
        textrect.topleft = (115, 105) #posicion x,y del juego
        screen.blit(textobj, textrect)

        textobj = font.render('Salir', 1, (255, 255, 255))  #titulo del juego
        textrect = textobj.get_rect()
        textrect.topleft = (425, 105) #posicion x,y del juego
        screen.blit(textobj, textrect)

        click = False
        for event in pygame.event.get():
          if event.type == QUIT:
            pygame.quit()
            sys.exit()
          if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
              pygame.quit()
              sys.exit()
          if event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
              click = True

        pygame.display.update()
        mainClock.tick(60)

def gotogame():
    running = True
    while running:
        screen.fill(pygame.Color("dimgray"))

        textobj = font.render('Aqui se abre el juego, pero todavia no xD, presione ESC para regresar al menu', 1, (255, 255, 255))  #titulo del juego
        textrect = textobj.get_rect()
        textrect.topleft = (20, 20) #posicion x,y del juego
        screen.blit(textobj, textrect)

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False

        pygame.display.update()
        mainClock.tick(60)

def exit():
  pygame.quit()

main_menu()


class Axis:
    """
    Fake enum as class with constant variable to represent the axis value that could change
    """
    x = 'X'
    y = 'Y'
    z = 'Z'

class SpaceSwitchReservedIndex:
    """
    Fake enum as class with constant variable to represent the reserved index in controller space switch
    """
    world = -3
    local = -2
    root = -1

class UIExposeFlags:
    """
    Flags used when exposing Rig or Module functionality in the ui.
    """
    trigger_network_export = 1

class EnvironmentVariables:
    """
    Customize the behavior of OMTK by defining thoses environment variables.
    """
    # Force a specific rig type as default.
    # Usefull for project-specific configurations.
    OMTK_DEFAULT_RIG = 'OMTK_DEFAULT_RIG'

    # Define additional location on disk to search for plugins.
    OMTK_PLUGINS = 'OMTK_PLUGINS'


class Fourcal:
    def setdata(self, first , second):
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second
        return result

    def print_number(self):
        print("first: %d, second: %d" % (self.first, self.second))

a = Fourcal()
a.setdata(3,2)
a.print_number()
print(a.add())

b = Fourcal()
b.setdata(1,2)
b.print_number()
print(b.add())

print(a.first + a.second)
# 위와같이 python의 모든 클래스의 맴버 변수. 함수는 속성이 public이라
# 외부에서 모두 접근이 가능하다.
# 하지만 클래스의 맴버 변수에 대해서 설정하는 것은
# 클래스 정의 시 맴버변수 정의, 생성자, setxxx() 함수로 정의 및 수정을 하는 것이
# 객체지향 프로그래밍에 가깝다.
temp  = [1,2,3,4]
temp.__class__
# 객체지향언어에서의 private 개념은 __맴버변수__.__맴버함수__() 로
# 적용할 수 있다. 접근은 가능하지만 사용하지 않는 암묵적인 룰을 준수한다.


'''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Group Project: Team Red
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Authors:
    Mark R. Mahan
    Joshua Yamdogo
    Samuel Trenter
    Shinya Honda
    Humberto Colin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is meant to run a platforming game
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''

from tkinter import *

class Platformer(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title("Platformer") #Frame's title
        self.grid()

        self.height = 600
        self.width = 1000
        self.canvas = Canvas(self, height = 600, width = 1000, bg = "white")
        self.canvas.grid(row = 1, column = 0)

        self.Game() #Runs the "game"

    def Game(self):
        print("hello world")

def main():
    Platformer().mainloop()

Group Project/Python Version (Incomplete)/Group_Project_(Team Red).py


from rest_framework.serializers import Serializer, BooleanField, CharField
from ..serializers import LBaseSerializer
from .models import Verification, EmailVerification

class VerificationSerializer(LBaseSerializer):
    VERIFICATION_SERIALIZERS = {
        'emailverification': 'EmailVerificationSerializer',
    }

    class Meta(LBaseSerializer.Meta):
        model = Verification
        fields = LBaseSerializer.Meta.fields + \
            ('id', 'code', 'expiration', 'verification', 'user', 'type', )
        read_only_fields = LBaseSerializer.Meta.read_only_fields + \
            ('type', )

    def to_representation(self, instance):
        instance = getattr(instance, instance.type)
        serializer = eval(
            self.VERIFICATION_SERIALIZERS[instance.type]
        )(instance)
        serializer.context = self.context

        return super(VerificationSerializer, serializer) \
            .to_representation(instance)

class EmailVerificationSerializer(VerificationSerializer):

    class Meta(VerificationSerializer.Meta):
        model = EmailVerification

class EmailVerifySerializer(Serializer):
    success = BooleanField()
    message = CharField()


# -*- coding:UTF-8 -*-

import threading
import queue

# 重写进程，获取返回值
class MyThread(threading.Thread):
    def __init__(self, func, args):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None

# 线程创建（阻塞）
class InputThreading:
    def __init__(self, input_text, output_text, time_out):
        self.e = threading.Event()
        self.input_thread = MyThread(self.get_input, args=(input_text, output_text))
        self.wait_thread = MyThread(self.wait_event, args=(time_out,))
        self.input_thread.daemon = True
        self.wait_thread.start()
        self.input_thread.start()
        self.wait_thread.join(time_out)  # 加入阻塞及超时时间
        self.input_thread.join(time_out)  # 加入阻塞及超时时间

    def get_input(self, in_text=None, out_text=None):
        num = input(in_text)
        print('')
        self.e.set()
        print(num)
        return num

    def wait_event(self, time_out=None):
        self.e.wait(timeout=time_out)

# 线程创建+加入队列（阻塞）
class InputThreadingQueue:
    def __init__(self, t_input, t_output, tim_out):
        self.que = queue.Queue()
        self.input_thread = MyThread(self.get_input, args=(t_input, t_output))
        self.wait_thread = MyThread(self.wait, args=(tim_out,))
        self.input_thread.daemon = True
        self.wait_thread.start()
        self.input_thread.start()
        self.wait_thread.join(tim_out)  # 加入阻塞及超时时间
        self.input_thread.join(tim_out)  # 加入阻塞及超时时间

    def get_input(self, text_input, text_output):
        print(text_output, input(text_input))
        self.que.put(1)

    def wait(self, time_out):
        try:
            self.que.get(timeout=time_out)
        except queue.Empty:
            pass

if __name__ == '__main__':
    # q = queue.Queue()
    # input_threading()
    a = InputThreadingQueue('请输入：', '结果为：', 5)
    print(a.input_thread.get_result())
    b = InputThreading('请输入：', '结果为：', 5)
    print(b.input_thread.get_result())


# -*- coding: utf-8 -*-
"""
Created on Mon Aug  5 11:25:37 2019

@author: jsten
"""
import numpy as np

"Spin Matrices"
s0=np.array([[1,0],[0,1]])
sx=np.array([[0,1],[1,0]])
sy=np.array([[0,1j],[-1j,0]])
sz=np.array([[1,0],[0,-1]])
I2=np.dot(sz,sz)
Z2=sz-sz

"""
"Parameters"
tua=1;
#U=0
Delta=0.7;
mu=0.1;

params=np.array([tua,Delta,U,mu])
np.savetxt("params",params)
"""

"Get parameters from the initilization file"
"U is not used"
"mu is divided by 2 since TEBD hits it twice"
params=np.loadtxt("params")
tua=params[0]
Delta=params[1]
U=params[2]
mu=params[3]

"Matrix Operators"
def VPOl(V):
    return np.array([I2,(tua+Delta)/2*sx,(tua-Delta)/2*sy,V*sz,-mu*sz])
def MPO(V):
    return np.array([[I2,(tua+Delta)/2*sx,(tua-Delta)/2*sy,V*sz,-mu*sz],[Z2,Z2,Z2,Z2,sx],[Z2,Z2,Z2,Z2,sy],[Z2,Z2,Z2,Z2,sz],[Z2,Z2,Z2,Z2,I2]])
def VPOr(V):
    return np.array([-mu*sz,sx,sy,sz,I2])

"Multiplying two Matrix Operators"
def TimesHMM(T1,T2):
    L1=len(T1[0,0])
    L2=len(T2[0,0])
    ttp=np.einsum('ijab,jkcd->ikabcd',T1,T2)
    ttp=np.swapaxes(ttp,2,5)
    ttp=np.reshape(ttp,(5,5,L1*L2,L1*L2))
    ttp=np.swapaxes(ttp,2,3)
    return ttp
def TimesHVM(T1,T2):
    L1=len(T1[0])
    L2=len(T2[0,0])
    ttp=np.einsum('jab,jkcd->kabcd',T1,T2)
    ttp=np.swapaxes(ttp,1,4)
    ttp=np.reshape(ttp,(5,L1*L2,L1*L2))
    ttp=np.swapaxes(ttp,1,2)
    return ttp
def TimesHMV(T1,T2):
    L1=len(T1[0,0])
    L2=len(T2[0])
    ttp=np.einsum('ijab,jcd->iabcd',T1,T2)
    ttp=np.swapaxes(ttp,1,4)
    ttp=np.reshape(ttp,(5,L1*L2,L1*L2))
    ttp=np.swapaxes(ttp,1,2)
    return ttp
def TimesHVV(T1,T2):
    L1=len(T1[0])
    L2=len(T2[0])
    ttp=np.einsum('jab,jcd->abcd',T1,T2)
    ttp=np.swapaxes(ttp,0,3)
    ttp=np.reshape(ttp,(L1*L2,L1*L2))
    ttp=np.swapaxes(ttp,0,1)
    return ttp
"Chooses the correct Matrix Operator Multiplication"
def TimesH(T1,T2):
    if len(np.shape(T1))==4:
        if len(np.shape(T2))==4:
            thtp=TimesHMM(T1,T2)
        elif len(np.shape(T2))==3:
            thtp=TimesHMV(T1,T2)
    elif len(np.shape(T1))==3:
        if len(np.shape(T2))==4:
            thtp=TimesHVM(T1,T2)
        elif len(np.shape(T2))==3:
            thtp=TimesHVV(T1,T2)
    return thtp

"returns the hamiltionian in the wavefunction basis"
def Ht(V,L):
    htp=VPOl(V)
    for i in range(1,L-1):
        htp=TimesH(htp,MPO(V))
    htp=TimesH(htp,VPOr(V))
    return htp


#Basic linked list class

class Node:
    def __init__(self,val ):
        self.val = val
        self.next = None
class LinkedList:
    def __init__(self):
        self.root = None
    def insert(self,data):
        if self.root==None:
            self.root = Node(data)
        else:
            temp = self.root
            while temp.next!=None:
                temp = temp.next
            temp.next = Node(data)
    def printList(self):
        temp = self.root
        while temp!=None:
            print(temp.val,end=" ")
            temp = temp.next
        print()
    def reverse(self):
        left = None
        right = self.root
        while right!=None :
            temp = right
            right = right.next
            temp.next = left
            left = temp
        self.root = left

ll = LinkedList()
ll.insert (1)
ll.insert (2)
ll.insert (3)
ll.insert (4)
ll.insert (5)
ll.insert (6)
ll.printList()
ll.reverse()
ll.printList()


#!/usr/bin/python

import argparse

def find_max_profit(prices):
    # loop over prices, starting from the second price
    # for each price, find min before
    # keep track of current_min_price_so_far (min before) and max_profit_so_far

    max_profit_so_far = None

    for i in range(1, len(prices)):
        current_min_price_so_far = None

        for j in range(0, i):
            if current_min_price_so_far == None or prices[j] < current_min_price_so_far:
                current_min_price_so_far = prices[j]

        if max_profit_so_far == None or prices[i] - current_min_price_so_far > max_profit_so_far:
            max_profit_so_far = prices[i] - current_min_price_so_far

    return max_profit_so_far

if __name__ == '__main__':
    # This is just some code to accept inputs from the command line
    parser = argparse.ArgumentParser(description='Find max profit from prices.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
    args = parser.parse_args()

    print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))


# Copyright (c) 2020 fortiss GmbH
#
# Authors: Patrick Hart
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.

import pandas as pd
from enum import Enum

class Tracer:
  class QueryTypes(str, Enum):
    """
    Trace: returns the trace
    Mean: calculates the mean of the trace
    """
    TRACE = "TRACE"
    MEAN  = "MEAN"
    SUM  = "SUM"
    LAST_VALUE  = "LAST_VALUE"
    ANY_TRUE  = "ANY_TRUE"

  def __init__(self):
    self._states = []
    self._df = None

  def EvalStateToDict(self, eval_state):
    """Converts an eval_state to a flat eval_dict"""
    eval_dict = {}
    if type(eval_state) is tuple:
      (state, reward, is_terminal, info) = eval_state
      eval_dict["state"] = state
      eval_dict["reward"] = reward
      eval_dict["is_terminal"] = is_terminal
      for info_key, info_value in info.items():
        eval_dict[info_key] = info_value
    if type(eval_state) is dict:
      for info_key, info_value in eval_state.items():
        eval_dict[info_key] = info_value
    return eval_dict

  def Trace(self, eval_state, **kwargs):
    """Traces and stores a state"""
    eval_dict = self.EvalStateToDict(eval_state)
    # additional things to log
    for key, value in kwargs.items():
      eval_dict[key] = value
    self._states.append(eval_dict)

  def Query(
    self,
    key="collision",
    group_by="num_episode",
    agg_type="TRACE"):
    if self.df is None:
      self.ConvertToDf()
    df = self.df.groupby(group_by)[key]
    # NOTE: different aggregation types
    if agg_type == Tracer.QueryTypes.MEAN:
      return df.mean()
    if agg_type == Tracer.QueryTypes.SUM:
      return df.sum()
    if agg_type == Tracer.QueryTypes.LAST_VALUE:
      return df.tail(1)
    elif agg_type == Tracer.QueryTypes.ANY_TRUE:
      return df.any().mean()
    return df

  @property
  def df(self):
    return self._df

  def ConvertToDf(self):
    """Conversts states to pandas dataframe"""
    self._df = pd.DataFrame(self._states)

  def Save(self, filepath="./"):
    """Saves trace as pandas dataframe"""
    if self._df is None:
      self.ConvertoToDf()
    self._df.to_pickle(filepath)

  def Reset(self):
    self._states = []
    self._df = None


# coding:"utf_8"
import MeCab

text = '今日は晴れかな？'

#天気の関連語をまとめたgazetteer
weather_set = set([u'晴れ',u'天気',u'雨'])

mecab = MeCab.Tagger("-Ochasen") #MeCabの取得
tokens = mecab.parse(text) #分かち書きを行う
token = tokens.split("\n")

#以下、分かち書き後の単語を抽出
for ele in token:
    element = ele.split("\t")
    if element[0] == "EOS":
        break

    # 単語の表層を取得
    surface = element[0]

    if surface in weather_set:
        print(surface)


#!/usr/bin/python3
# --*-- coding:utf-8 --*--
# @Author    : YuAn
# @Site      :
# @File      : list.py
# @Time      : 2018/5/30 17:21
# @software  : PyCharm

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield a

def main():
    for val in fib(20):
        print(val)

if __name__ == '__main__':
    main()