import json
import p4
import cv2
import tensorflow as tf
import pandas as pd
import numpy as np
from collections import Counter
from keras import layers, regularizers
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.callbacks import ReduceLROnPlateau

keep_stanford40 = ["applauding", "climbing", "drinking", "jumping", "pouring_liquid", "riding_a_bike", "riding_a_horse",
        "running", "shooting_an_arrow", "smoking", "throwing_frisby", "waving_hands"]

#Build and train the model
def Stanford40():
    # Split data (skeleton code)
    with open('Stanford40/ImageSplits/train.txt', 'r') as f:
        train_files = [file_name for file_name in list(map(str.strip, f.readlines())) if
                       '_'.join(file_name.split('_')[:-1]) in keep_stanford40]
        train_labels = ['_'.join(name.split('_')[:-1]) for name in train_files]

    with open('Stanford40/ImageSplits/test.txt', 'r') as f:
        test_files = [file_name for file_name in list(map(str.strip, f.readlines())) if
                      '_'.join(file_name.split('_')[:-1]) in keep_stanford40]
        test_labels = ['_'.join(name.split('_')[:-1]) for name in test_files]

    # Test train (skeleton code)
    train_exp, val_exp, trainLabels_exp, valLabels_exp = train_test_split(train_files, train_labels, test_size=0.1,
                                                                          stratify=train_labels, random_state=0)
    # Final train (skeleton code)
    all_files = train_files + test_files
    all_labels = train_labels + test_labels
    train, test, trainLabels, testLabels = train_test_split(all_files, all_labels, test_size=0.1,
                                                            stratify=all_labels, random_state=0)

    # Choice 1: data augmentation
    # train_datagen = ImageDataGenerator(
    #     rescale=1. / 255,
    #     horizontal_flip=True)

    # Create the training and validation data
    train_datagen = ImageDataGenerator(rescale=1. / 255)
    val_datagen = ImageDataGenerator(rescale=1. / 255)

    train_generator = train_datagen.flow_from_dataframe(
        # dataframe=pd.DataFrame({'filename': train_exp, 'label': trainLabels_exp}),
        dataframe=pd.DataFrame({'filename': train, 'label': trainLabels}),
        directory='./Stanford40/JPEGImages/',
        x_col='filename',
        y_col='label',
        target_size=(224, 224),
        batch_size=32,
        class_mode='categorical',
        shuffle=True
    )

    val_generator = val_datagen.flow_from_dataframe(
        # dataframe=pd.DataFrame({'filename': val_exp, 'label': valLabels_exp}),
        dataframe=pd.DataFrame({'filename': test, 'label': testLabels}),
        directory='./Stanford40/JPEGImages/',
        x_col='filename',
        y_col='label',
        target_size=(224, 224),
        batch_size=32,
        class_mode='categorical',
        shuffle=False
    )

    model = tf.keras.Sequential([
        layers.Conv2D(16, (3,3), activation='relu', input_shape=(224, 224, 3)),
        layers.MaxPooling2D(2, 2),
        layers.Conv2D(32, (3,3), activation='relu'),
        layers.MaxPooling2D(2,2),
        layers.Conv2D(64, (5,5), activation='relu'),
        layers.MaxPooling2D(2,2),
        layers.Conv2D(64, (5,5), activation='relu'),
        layers.MaxPooling2D(2,2),
        layers.Dropout(0.5),
        layers.Flatten(),
        layers.Dense(256, activation='relu', name='sta_dense'),
        layers.Dropout(0.5),
        layers.Dense(12, activation='softmax')
    ])
    model.summary()

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    Stanford = model.fit(
            train_generator,
            steps_per_epoch=len(train) // 32,
            #steps_per_epoch=len(train_exp) // 32,
            epochs=13,
            validation_data=val_generator,
            validation_steps=len(test) // 32)
            #validation_steps = len(val_exp) // 32)

    model.save('./DATA/Stanford40_final_1.h5')
    with open('./DATA/Stanford40_final_1.json', 'w') as f:
        json.dump(Stanford.history, f)

    # model.save('./DATA/Stanford40_aug.h5')
    # with open('./DATA/Stanford40_aug.json', 'w') as f:
    #     json.dump(Stanford.history, f)

if __name__ == '__main__':
    # Stanford40()
    filename_final = './DATA/Stanford40_final.json'
    filename_validation = './DATA/Stanford40_final_validation.json'
    filename_aug = './DATA/Stanford40_aug.json'
    # p4.plotting(filename_aug)
    # p4.comparison(filename_final, filename_aug)

    # p4.topAcc([filename_final, filename_validation, filename_aug])

    model = tf.keras.models.load_model('./DATA/Stanford40_final.h5')
    model.summary()


import socket
import time

import pygame

class PS4Transmitter(object):
    def __init__(self, ip, *args, **kwargs):
        super(PS4Transmitter, self).__init__(*args, **kwargs)

        self.ip = ip

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.controller = None
        self.axis_data = None
        self.button_data = None
        self.hat_data = None
        self.state = None

        pygame.init()
        pygame.joystick.init()

        self.controller = pygame.joystick.Joystick(0)
        self.controller.init()

    def send_keepalive_and_sleep(self):
        self.socket.sendto('KEEPALIVE', (self.ip, 6291))
        time.sleep(0.01)

    def listen(self):
        if not self.axis_data:
            self.axis_data = {}

        if not self.button_data:
            self.button_data = {}
            for i in range(self.controller.get_numbuttons()):
                self.button_data[i] = False

        if not self.hat_data:
            self.hat_data = {}
            for i in range(self.controller.get_numhats()):
                self.hat_data[i] = (0, 0)

        while 1:
            for event in pygame.event.get():
                if event.type == pygame.JOYAXISMOTION:
                    self.axis_data[event.axis] = round(event.value, 2)
                elif event.type == pygame.JOYBUTTONDOWN:
                    self.button_data[event.button] = True
                elif event.type == pygame.JOYBUTTONUP:
                    self.button_data[event.button] = False
                elif event.type == pygame.JOYHATMOTION:
                    self.hat_data[event.hat] = event.value

                if self.axis_data is None:
                    self.send_keepalive_and_sleep()
                    continue

                steering = self.axis_data.get(0)
                brake = self.axis_data.get(4)
                accelerator = self.axis_data.get(5)

                if None in [steering, brake, accelerator]:
                    self.send_keepalive_and_sleep()
                    continue

                # steering deadzone
                if -0.04 <= steering <= 0.04:
                    steering = 0.0

                state = [steering, brake, accelerator]

                if state == self.state:
                    self.send_keepalive_and_sleep()
                    continue

                try:
                    self.socket.sendto(repr(state), (self.ip, 6291))
                except socket.error:
                    self.send_keepalive_and_sleep()

                self.state = state

if __name__ == '__main__':
    from sys import argv

    ps4 = PS4Transmitter(argv[1])

    ps4.listen()


import numpy as np
import matplotlib.pyplot as plt
import SVM

def plot_res(folder,algo_name,num_trials=10):

    avg_accs = []
    for trial in range(0,num_trials):
        accs = np.load('%s/trial%d.npy' %(folder,trial))
        if trial == 0:
            avg_accs = accs
        else:
            avg_accs = avg_accs + accs

    avg_accs /= num_trials

    num_train_all = (1,2,5,10,15)
    plt.figure()

    labels = ('walking','walking_up','walking_down','sitting','standing','laying','all')
    print(len(labels))

    for j in range(0,7):
        plt.plot(num_train_all,avg_accs[j,:],label=labels[j])

    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.ylabel('Accuracy')
    plt.xlabel('Number of Observations')
    plt.title('User Learning Conditioned on Activity: %s' %(algo_name))
    plt.yticks([0.1*x for x in range(0,11)])
    plt.show()

#SVM.main()
plt.close("all")
plot_res('res_rbf_svm','RBF-SVM')
#plot_res('res_rbf_svm','Deep net',6)
plot_res('res_rfc','Random Forests')


#!/usr/bin/env python
import sys
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import Vector3
from std_msgs.msg import Bool, Float32
import message_filters

class traffic_light_analyzer_node:

    def __init__(self):
        # Subscribers
        self.detection_sub = message_filters.Subscriber(
            "/traffic_light_detected", Bool)
        self.size_sub = message_filters.Subscriber(
            "/traffic_light_size", Vector3)

        # Publishers
        self.zone_pub = rospy.Publisher(
            "/zone_height", Float32, queue_size=100)

        # Time synchronizer
        ts = message_filters.ApproximateTimeSynchronizer(
            [self.detection_sub, self.size_sub], 100, 0.1, allow_headerless=True)
        ts.registerCallback(self.callback)

    def callback(self, detection, size):
        # A simple calculation
        if (detection.data == True):
            self.zone_pub.publish(Float32(size.y / 3.0))

def main(args):
    rospy.init_node('traffic_light_analyzer_node', anonymous=True)
    ic = traffic_light_analyzer_node()

    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")

if __name__ == '__main__':
    main(sys.argv)


"""
Functions to Navigate the Directed Acyclic Graph (DAG)
"""
from collections import OrderedDict
import maya.cmds as cmds

import rigamajig2.shared.common as common
import rigamajig2.maya.naming as naming

def create(node, hierarchy=None, above=True, matchTransform=True, nodeType='transform'):
    """
    Build a hirachy of transforms around a given node

    :param str node: node to build hirachy around
    :param list hierarchy: list of names to add into a hirachy
    :param bool above: If True the hirachy will added above the node. False is below.
    :param bool matchTransform: match the newly created nodes to the position of the node
    :param str nodeType: Type of node to create
    """

    node = common.getFirstIndex(node)

    if not cmds.objExists(node):
        cmds.error("Node '{}' does not exist. cannot create a hierarchy".format(node))
        return

    if not cmds.nodeType(node) in ['transform', 'joint']:
        cmds.error("{} must be a transform".format(node))
        return

    parent = getParent(node)

    newHierachy = list()
    for i, name in enumerate(hierarchy):
        if cmds.objExists(name):
            name = naming.getUniqueName(name)
        new = cmds.createNode(nodeType, n=name)
        newHierachy.append(new)
        # Optionally match the transformation of the node in the hirachy
        if matchTransform:
            cmds.delete(cmds.parentConstraint(node, new, mo=False))
        # if were past the first node in the hirachy, create a new one
        if i > 0:
            cmds.parent(new, newHierachy[i - 1])

    if parent and above: cmds.parent(newHierachy[0], parent)

    if above:
        cmds.parent(node, newHierachy[-1])
    else:
        cmds.parent(newHierachy[0], node)

    return newHierachy

class DictHierarchy(object):
    """
    Hierarchy Dictionary class.
    """
    def __init__(self, hierarchy=None, parent=None, prefix=None, suffix=None, nodeType='transform'):
        """
        Constructor for the DictHierarchy class

        :param list hierarchy: Existing hierarchy dictionary
        :param str parent: parent of the hierarchy
        :param str prefix: prefix to add to all items of the hierarchy
        :param str suffix: suffix to add to all items of the hierarchy
        :param str nodeType: type of node to create the hierarchy with.
        """
        hierarchy = hierarchy or dict()
        self.hierarchy = hierarchy
        self.parent = parent
        self.prefix = prefix or ""
        self.suffix = "" if suffix is None else suffix
        self.nodeType = nodeType

        self._nodes = list()

    def create(self, hierarchy=None, parent=None):
        """
        Create a Node hiearchy from a dictionary

        :param dict hierarchy: dictonary to create the hierachy from
        :param str parent: parent the newly created hierarchy
        """
        if not hierarchy:
            hierarchy = self.hierarchy
        if not parent:
            parent = self.parent

        for name, children in hierarchy.items():
            node = "{}{}{}".format(self.prefix, name, self.suffix)
            self._nodes.append(node)
            if not cmds.objExists(node):
                node = cmds.createNode(self.nodeType, name=node)
            if parent:
                currentParent = cmds.listRelatives(node, parent=True, path=True)
                if currentParent:
                    currentParent = currentParent[0]
                if currentParent != parent:
                    cmds.parent(node, parent)

            if children:
                self.create(children, node)

    def getNodes(self):
        """return the nodes in the heirarchy"""
        return self._nodes

    @staticmethod
    def getHirarchy(node):
        """
        save a heirarchy of nodes into a dictionary

        :param node: get the hierarchy below a node
        :return: hierarchy dictionary:
        :rtype: dict
        """
        node = common.getFirstIndex(node)
        hierarchyDict = OrderedDict()

        def getChildren(n, hierarchyDict):
            """
            get children of a hierachy
            :param n: node
            :param hierarchyDict: hierarchy dict
            :return: dict
            """
            children = cmds.listRelatives(n, c=True, pa=True, type='transform')
            if children:
                hierarchyDict[n] = OrderedDict()
                for child in children:
                    hierarchyDict[n][child] = OrderedDict()
                    getChildren(child, hierarchyDict[n])
            else:
                hierarchyDict[n] = None

        getChildren(node, hierarchyDict)

        return hierarchyDict

def getTopParent(node):
    """
    Get the top parent of a hirarchy

    :param str node: input node to search
    :return: top parent of the node
    :rtype: str
    """
    return cmds.ls(node, long=True)[0].split('|')[1]

def getAllParents(node):
    """
    return a list of all a nodes parents

    :param str node: name of the input node to get all parents for
    :return: list of all parents above a node
    :rtype: List
    """
    parents = cmds.ls(node, long=True)[0].split('|')[1:-1]
    parents.reverse()
    return parents

def getParent(node):
    """
    return a the nodes parent

    :param str node: name of the node to get the parent of
    :return: name of parent of the given node
    :rtype: str None
    """
    return cmds.listRelatives(node, p=True)[0] if cmds.listRelatives(node, p=True) else None

def getChildren(node):
    """
    Get all children of a node

    :param str node: input node to search
    :return: all children of the node
    :rtype: list
    """
    return cmds.listRelatives(node, c=True)

def getAllChildren(node):
    """
    Get all children and decendents of a node

    :param str node:  input node to search
    :return: all children of the node
    :rtype: list
    """
    children = cmds.listRelatives(node, ad=True)
    children.reverse()
    return children

def getChild(node):
    """
    Get the first child of a given node

    :param str node: input node to search
    :return: the first child of a given node
    """
    return cmds.listRelatives(node, c=True)[0] if len(cmds.listRelatives(node, c=True)) > 0 else list()


'''
main module of project. developed for site-scrapping
'''
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import re
from bs4 import BeautifulSoup
import requests

def los(link):
    '''

    :param link: http://example.com
    :return: nothing to return
    '''
    if link in result:
        return
    result.append(link)
    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')
    for page in soup.find_all('a', href=True):
        buf = page.get('href')
        #print(buf)
        if buf.startswith('http') and f'{shortpage}' in buf:
            ul.add(buf)
            los(buf)
        elif buf.startswith('/'):
            buf = f'{STARTPAGE}{buf}'
            ul.add(buf)
            los(buf)

if __name__ == '__main__':
    ul = set()
    result = []
    STARTPAGE = 'https://letsenhance.io'
    if STARTPAGE.startswith('https'):
        shortpage = re.sub(r'https://', '', f'{STARTPAGE}')
    else:
        shortpage = re.sub(r'http://', '', f'{STARTPAGE}')
    print(shortpage)
    los(STARTPAGE)
    print(result)
    with open('listfile.txt', 'w') as filehandle: # pylint: disable=unspecified-encoding
        for line in result:
            filehandle.write(line + '\n')


from collections import defaultdict
import json
import logging

from jose import (
    jwk,
    jwt,
)
import tornado.ioloop
from tornado.web import (
    Application,
    HTTPError,
    RequestHandler,
)

logger = logging.getLogger()
logger.setLevel("DEBUG")

with open("./data/iam-prod-keys.json") as kf:
    KEYS = json.load(kf)
ISSUER = "https://iam.humanbrainproject.eu/auth/realms/hbp"

def bearer_authtenticated(fn: callable) -> callable:
    def wrapped(self: RequestHandler, *args, **kwargs):
        try:
            bearer = self.request.headers["authorization"].split(" ")[1]
        except Exception:
            self.write("Requires authorization with a Bearer token")
            raise HTTPError(401, f"Authorization failed, no header")
        try:
            payload = jwt.decode(
                bearer,
                KEYS,
                algorithms=["RS256"],
                issuer=ISSUER,
                options={"verify_aud": False},
            )
        except jwt.JWTError as e:
            raise HTTPError(401, f"Authorization failed {e}")
        user = payload["preferred_username"]
        return fn(self, user, *args, **kwargs)

    return wrapped

class InvalidVoteException(Exception):
    pass

class VotesHandler(RequestHandler):
    _options = ['A', 'B', 'C']

    @bearer_authtenticated
    def get(self, user: str) -> None:
        self.write({'vote': self.application.context['votes'][user]})

    @bearer_authtenticated
    def post(self, user: str) -> None:
        logging.info("Posting vote")
        try:
            vote = json.loads(self.request.body)['vote']
            self._validate(vote)
        except KeyError:
            self.write({"Error": f"Vote is required."})
            raise HTTPError(400, "Invalid option for vote.")
        except InvalidVoteException:
            self.write({"Error": f"Vote should be one of {self._options}"})
            raise HTTPError(400, "Invalid option for vote.")
        except json.JSONDecodeError:
            self.write({"error": "Invalid JSON"})
            raise HTTPError(400, "Invalid json")
        old = self.application.context['votes'][user]
        if old and not (old == vote):
            self.application.context['tally'][old] -= 1
        changed = not old == vote
        if changed:
            self.application.context['tally'][vote] += 1
            self.application.context['votes'][user] = vote
        logging.info(f"voted for: {vote}, new: {not old}, changed: {changed}")
        self.write(f"hello {user}")

    def _validate(self, vote):
        if vote not in self._options:
            raise InvalidVoteException

class ResultsHandler(RequestHandler):
    def get(self):
        self.write(self.application.context['tally'])

def main():
    import os
    try:
        port = int(os.environ.get('SVC_PORT'), 8080)
    except Exception:
        port = 8080
    app = Application([
        ("/votes", VotesHandler),
        ("/results", ResultsHandler),
    ])
    app.context = {
        "votes": defaultdict(lambda: None),
        "version": 0,
        "tally": defaultdict(int),
    }
    app.listen(port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()


#coding=utf-8
from datetime import datetime
from sandglass import Sandglass,ben

__all__ = ['tslice','timediff']

def tslice(unit,start=None,end=None,step=1,count=None):
    '''tslice(unit,start=None,end=None,step=1,count=None) -> generator of Sandglass object
    unit in ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
    this is some kind xrange-like
    '''
    if unit not in Sandglass._units:
        raise AttributeError()
    if isinstance(start,basestring):
        start = ben(start)
    if isinstance(end,basestring):
        end = ben(end)

    start = start or ben()
    count = count or float('inf')
    cur  = start
    cnt = 0
    if step>0:
        end = end or ben(datetime.max)
        while cur<end and cnt<count:
            yield cur
            cur = cur.shifted(**{unit:step})
            cnt += 1
    elif step<0:
        end = end or ben(datetime.min)
        while cur>end and cnt<count:
            yield cur
            cur = cur.shifted(**{unit:step})
            cnt += 1

def timediff(timestr,factor=86400,base=None):
    '''Get the distance to the next time
    >>>timediff('20:00:00',factor=86400,base='19:30:00')
    1800
    >>>timediff('20:00:00',factor=86400,base='21:30:00')
    81000
    '''
    base = ben(base) if base else ben()
    sg = ben(timestr)
    diff = int((sg - base).total_seconds())
    return diff%factor


linha = int(input())
operacao = input()
soma = 0

for i in range(12):
    for j in range(12):
        valor = float(input())
        if(i == linha):
            soma += valor

if(operacao == 'S'):
     print("%.1f" %soma)
else:
     print("%.1f" %(soma/12.0))


from flask import Flask,render_template,request
import os
import random

app = Flask(__name__)#Flaskクラスのインスタンス生成

num_list=[0,1,2,3,4,5,6,7,8,9]
target_num = random.sample(num_list,3)
num_log=[]
eat_log=[]
bite_log=[]
length=0

@app.route('/',methods=['GET','POST'])
def start():
   if request.method=="GET":
      global target_num
      target_num= random.sample(num_list,3)
      global num_log
      num_log=[]
      global eat_log
      eat_log=[]
      global bite_log
      bite_log=[]
      global length
      length=0
   return render_template('start.html')
@app.route('/first_declare/',methods=['GET','POST'])
def first_declare():
   return render_template('first_declare.html',title='コンピュータが数字を設定しました。',target_num=target_num)

@app.route('/main_declare',methods=['GET','POST'])
def main_declare():
   user_num=request.form['user']
   eat=0
   bite=0
   if not user_num.isdecimal():
      return render_template('main_declare.html',title='整数を入力してよ',num_log='/',eat_log='/',bite_log='/',eat=0,length=0)
   elif len(user_num) !=3:
      return render_template('main_declare.html',title='3桁の数字で入力してよ',num_log='/',eat_log='/',bite_log='/',eat=0,length=0)
   elif user_num.count(user_num[0])!=1 or user_num.count(user_num[1])!=1 or user_num.count(user_num[2])!=1:
      return render_template('main_declare.html',title='重複は論外だよ！しっかりやってね',num_log='/',eat_log='/',bite_log='/',eat=0,length=0)
   num_log.append(user_num)
   length=len(num_log)
   for index,i_tar in enumerate(target_num):
      for cnt in range(3):
         if str(target_num[index])==user_num[index]:
            eat+=1
            break
         elif str(i_tar) in user_num:
            bite+=1
            break
   eat_log.append(eat)
   bite_log.append(bite)

   if eat!=3:
      return render_template('main_declare.html',title='残念！　ハズレだドン！！！',num_log=num_log,eat_log=eat_log,bite_log=bite_log,eat=eat,length=length)
   elif eat==3:
      return render_template('main_declare.html',title='クリア！！おめでとドン！！！！',num_log=num_log,eat_log=eat_log,bite_log=bite_log,eat=eat,length=length)

app.run(debug=True,host='0.0.0.0',port=8888,threaded=True)#Webアプリの起動（Flaskサーバの起動）


from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, String, Integer,DateTime
import os

'''local database URL
database_name = "capstone"
#database_path = "postgresql://{}/{}".format('localhost:5432', database_name)'''

database_path = os.environ.get("DATABASE_PATH")
db = SQLAlchemy()

'''
setup_db(app)
    binds a flask application and a SQLAlchemy service
'''
def setup_db(app, database_path=database_path):
    app.config["SQLALCHEMY_DATABASE_URI"] = database_path
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.app = app
    db.init_app(app)
    with app.app_context(): #uncomment if FLASK version is 2.3 and above
        db.create_all()

class Movie(db.Model):
    '''This class represents the movies table'''
    __tablename__ = 'movies'

    id = Column(Integer,primary_key=True)
    title = Column(String(255),nullable=False)
    release_date = Column(DateTime,nullable=False)

    def __init__(self, title, release_date):
        self.title = title
        self.release_date = release_date

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def format(self):
        return {
            'id': self.id,
            'title': self.title,
            'release_date': self.release_date
            }

class Actor(db.Model):
    '''This class represents the actors table'''
    __tablename__ = 'actors'

    id = Column(Integer,primary_key=True)
    name = Column(String(255),nullable=False)
    age = Column(Integer,default = 35)
    gender = Column(String(10),default = "None")

    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def format(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'gender': self.gender
        }


from typing import Optional

from buffett.adapter.pandas import DataFrame
from buffett.common import Code
from buffett.common.tools import create_meta, dataframe_not_valid
from buffett.common.constants.col import FREQ, FUQUAN, SOURCE, START_DATE, END_DATE
from buffett.common.constants.col.stock import CODE
from buffett.common.constants.table import DL_RCD
from buffett.download import Para
from buffett.download.mysql import Operator
from buffett.download.mysql.types import ColType, AddReqType
from buffett.download.types import FreqType, FuquanType, SourceType

_META = create_meta(meta_list=[
    [CODE, ColType.CODE, AddReqType.KEY],
    [FREQ, ColType.ENUM_BOOL, AddReqType.KEY],
    [FUQUAN, ColType.ENUM_BOOL, AddReqType.KEY],
    [SOURCE, ColType.ENUM_BOOL, AddReqType.KEY],
    [START_DATE, ColType.DATETIME, AddReqType.NONE],
    [END_DATE, ColType.DATETIME, AddReqType.NONE]])

class DownloadRecorder:
    def __init__(self, operator: Operator):
        self._operator = operator
        self._exist = False

    def save(self, para: Para) -> None:
        ls = [[para.stock.code, para.comb.freq, para.comb.fuquan, para.comb.source, para.span.start, para.span.end]]
        cols = [CODE, FREQ, FUQUAN, SOURCE, START_DATE, END_DATE]
        data = DataFrame(data=ls, columns=cols)
        self.save_to_database(data=data)

    def save_to_database(self,
                         data: DataFrame) -> None:
        if not self._exist:
            self._operator.create_table(DL_RCD, _META, if_not_exist=True)
            self._exist = True

        self._operator.try_insert_data(DL_RCD, data, _META, update=True)  # 如果原纪录已存在，则更新

    def select_data(self) -> Optional[DataFrame]:
        df = self._operator.select_data(DL_RCD)
        if dataframe_not_valid(df):
            return

        df[CODE] = df[CODE].apply(lambda x: Code(x))
        df[FREQ] = df[FREQ].apply(lambda x: FreqType(x))
        df[FUQUAN] = df[FUQUAN].apply(lambda x: FuquanType(x))
        df[SOURCE] = df[SOURCE].apply(lambda x: SourceType(x))
        return df


s = input()

def solve(s):
    for i in range(len(s)-1, -1, -1):
        if i % 2 == 1:
            continue
        if s[:i // 2] == s[i // 2:i]:
            return i

print(solve(s))


# This code process the data according to logistic regression
import sklearn.linear_model

class Lr:
    def __init__(self,prob = 0.5):
        self.trainingData = []
        self.testingData = []
        self.prob = prob

    def setTrainingData(self,trainingData):
        self.trainingData = trainingData

    def setTestingData(self,testingData):
        self.testingData = testingData

    def buildModel(self):
        """Building sklearn linear model from training data"""
        featureVecs, labels = [],[]
        for p in self.trainingData:
            featureVecs.append(p.getFeatureVec())
            labels.append(p.getOutcome())
        LogisticRegression = sklearn.linear_model.LogisticRegression
        model = LogisticRegression().fit(featureVecs, labels)
        return model

    def applyModel(self,model,label):
        """Applying model to test data"""
        testFeatureVecs = [e.getFeatureVec() for e in self.testingData]
        probs = model.predict_proba(testFeatureVecs)
        truePos, falsePos, trueNeg, falseNeg = 0, 0, 0, 0
        for i in range(len(probs)):
            if probs[i][1] > self.prob:
                if self.testingData[i].getOutcome() == label:
                    truePos += 1
                else:
                    falsePos += 1
            else:
                if self.testingData[i].getOutcome() != label:
                    trueNeg += 1
                else:
                    falseNeg += 1
        return truePos, falsePos, trueNeg, falseNeg

    def getResult(self,lable):
        model = self.buildModel()
        return self.applyModel(model,lable)


#!/usr/bin/env python
import argparse
import datetime
import getpass
import subprocess  # nosec
import sys

import boto3
import git

# Jumpoint account id (where docker repo exists)
account_id = "432932430231"

# TODO: from .utils import output, execute

def output(message):
    print("")
    print("=========================================================")
    print(message)
    print("=========================================================")
    print("")

def execute(command):
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)  # nosec
    for line in iter(process.stdout.readline, b""):
        line = line.decode("utf-8")
        line = "[{}] {}".format(datetime.datetime.now(), line) if line.startswith("Step") else line
        sys.stdout.write(line)
    process.wait()
    if process.returncode:
        exit(process.returncode)

parser = argparse.ArgumentParser(
    description="Builds docker containers, tags them, and pushes to ECR"
)
parser.add_argument(
    "image_name", type=str, help="The name of the image to build",
)

parser.add_argument(
    "--dockerfile", dest="dockerfile", type=str, help="Docker target for multi-stage builds",
)
args = parser.parse_args()

repo = git.Repo(search_parent_directories=True)
git_hash = repo.head.object.hexsha
branch = repo.active_branch.name.replace("/", "_")
username = getpass.getuser()

# Configuring local docker to push to AWS ECR
# docker_login = subprocess.check_output(  # nosec
#     "aws ecr get-login-password --no-include-email --region us-west-2 --registry-ids {}".format(
#         account_id
#     ).split()
# ).decode("utf-8")

docker_login = subprocess.Popen(  # nosec
    "aws ecr get-login-password --region us-west-2".split()
)
docker_login_2 = subprocess.check_output(
    "docker login --username AWS --password-stdin {}.dkr.ecr.region.amazonaws.com".format(
        account_id
    ).split(),
    stdin=docker_login.stdout
).decode("utf-8")

output(docker_login_2.stdout)

output("Building image")
execute(
    "docker build -t {} -f {} --build-arg {}={} .".format(
        args.image_name, args.dockerfile, "BUILD_GIT_HASH", git_hash,
    )
)

execute(
    "docker tag {0}:latest {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:latest".format(
        args.image_name, account_id
    )
)
execute(
    "docker tag {0}:latest {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_latest".format(
        args.image_name, account_id, branch
    )
)
execute(
    "docker tag {0}:latest {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_latest".format(
        args.image_name, account_id, username
    )
)
execute(
    "docker tag {0}:latest {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_{3}".format(
        args.image_name, account_id, branch, git_hash
    )
)

execute(docker_login)

output("Pushing image to ECR")
execute(
    "docker push {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_latest".format(
        args.image_name, account_id, branch
    )
)
execute(
    "docker push {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_latest".format(
        args.image_name, account_id, username
    )
)
execute(
    "docker push {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:{2}_{3}".format(
        args.image_name, account_id, branch, git_hash
    )
)
execute(
    "docker push {1}.dkr.ecr.us-west-2.amazonaws.com/{0}:latest".format(args.image_name, account_id)
)

output(
    """Image uploaded successfully with the following tags:
- {0}:latest
- {0}:{1}_latest
- {0}:{3}_latest
- {0}:{1}_{2}""".format(
        args.image_name, branch, git_hash, username
    )
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr  9 16:47:25 2021

@author: suee
"""
#plot distribution for wate usage and time for usage

# =============================================================================
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd
# import math
#
# # water usa
# # =============================================================================
# mu, sigma, num_bins = 8, 0.5, 50
# mu1, sigma1 , num_bins1 = 10, 0.5, 50
# mu2, sigma2 , num_bins2 = 12, 0.5, 50
# mu3, sigma3 , num_bins3 = 3, 0.5, 50
# x = mu + sigma * np.random.randn(1000)
# x1 = mu1 + sigma1 * np.random.randn(1000)
# x2 = mu2 + sigma2 * np.random.randn(1000)
# x3 = mu3 + sigma3 * np.random.randn(1000)
# #
# n, bins, patches = plt.hist(x, num_bins, normed=True, facecolor = 'blue', alpha = 0.5)
# n1, bins1, patches = plt.hist(x1, num_bins1, normed=True, facecolor = 'blue', alpha = 0.5)
# n2, bins2, patches = plt.hist(x2, num_bins2, normed=True, facecolor = 'blue', alpha = 0.5)
# n3, bins3, patches = plt.hist(x3, num_bins3, normed=True, facecolor = 'blue', alpha = 0.5)
# #
# y = norm.pdf(bins, mu, sigma)
# y1 = norm.pdf(bins1, mu1, sigma1)
# y2 = norm.pdf(bins2, mu2, sigma2)
# y3 = norm.pdf(bins3, mu3, sigma3)
# plt.xlabel('water usage L/person*day')
# plt.ylabel('frequency of every X')
# plt.title('normal distribution of water usage: $\mu = 2$, $\sigma=0.5$')
# plt.plot(bins, y, 'r--')
# plt.plot(bins1, y1, 'r--')
# plt.plot(bins2, y2, 'r--')
# plt.plot(bins3, y3, 'r--')
# =============================================================================
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt
from matplotlib import cm

# 根据均值、标准差,求指定范围的正态分布概率值

def normfun(x, mu, sigma):

    pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi))

    return pdf

left,width=0.14,0.77
bottom,height=0.11,0.5
bottom_h=bottom+height+0.04

rect_line1=[left,bottom,width,height]

axbelow=plt.axes(rect_line1)

# result = np.random.randint(-65, 80, size=100) # 最小值,最大值,数量

result = np.random.normal(8, 0.5, 100) # 均值为0.5,方差为1
result1 = np.random.normal(8.2, 0.5, 100)
result2 = np.random.normal(8.3, 0.5, 100)
result3 = np.random.normal(8.4, 0.5, 100)

x = np.arange(min(result), max(result), 0.1)
x1 = np.arange(min(result1), max(result1), 0.1)
x2 = np.arange(min(result2), max(result2), 0.1)
x3 = np.arange(min(result3), max(result3), 0.1)
# 设定 y 轴，载入刚才的正态分布函数

y = normfun(x, result.mean(), result.std())
y1 = normfun(x1, result1.mean(), result1.std())
y2 = normfun(x2, result2.mean(), result2.std())
y3 = normfun(x3, result3.mean(), result3.std())
# axbelow.plot(x, y,label='person A at 8:00am') # 这里画出理论的正态分布概率曲线
# plt.plot(x1, y1,label='person B at 8:12am')
# plt.plot(x2, y2,label='person C at 8:18am')
# plt.plot(x3, y3,label='person D at 8:24am')

result7 = np.random.normal(18, 0.5, 100) # 均值为0.5,方差为1
result4 = np.random.normal(18.2, 0.5, 100)
result5 = np.random.normal(18.3, 0.5, 100)
result6 = np.random.normal(18.4, 0.5, 100)

x7 = np.arange(min(result7), max(result7), 0.1)
x4 = np.arange(min(result4), max(result4), 0.1)
x5 = np.arange(min(result5), max(result5), 0.1)
x6 = np.arange(min(result6), max(result6), 0.1)
# 设定 y 轴，载入刚才的正态分布函数

y7 = normfun(x7, result7.mean(), result7.std())
y4 = normfun(x4, result4.mean(), result4.std())
y5 = normfun(x5, result5.mean(), result5.std())
y6 = normfun(x6, result6.mean(), result6.std())
plt.plot(x7, y7,label='person A at 6:00pm') #
plt.plot(x4, y4,label='person B at 6:12pm')
plt.plot(x5, y5,label='person C at 6:18pm')
plt.plot(x6, y6,label='person D at 6:24pm')

# 这里画出实际的参数概率与取值关系

plt.hist(result, bins=10, rwidth=0.8, density=True) # bins个柱状图,宽度是rwidth(0~1),=1没有缝隙
plt.hist(result1, bins=10, rwidth=0.8, density=True)
plt.hist(result2, bins=10, rwidth=0.8, density=True)
plt.hist(result3, bins=10, rwidth=0.8, density=True)
plt.hist(result4, bins=10, rwidth=0.8, density=True) # bins个柱状图,宽度是rwidth(0~1),=1没有缝隙
plt.hist(result5, bins=10, rwidth=0.8, density=True)
plt.hist(result6, bins=10, rwidth=0.8, density=True)
plt.hist(result7, bins=10, rwidth=0.8, density=True)
plt.title('Probablity of water usage from one family during one day')

plt.xlabel('time in one day')

plt.ylabel('probability of using the filter')
plt.legend(loc='upper center', numpoints=1)

leg = plt.gca().get_legend()

ltext = leg.get_texts()

plt.setp(ltext, fontsize='small')

# 输出

plt.show()

# =============================================================
# ====================== Plots ================================
# =============================================================
colorIdx = np.linspace(0, 256, num = 20).astype('int')
xTick = np.arange(6, 20 + 1, step = 1)
xTickLabel = [str(item) + ':00' for item in xTick]

fig, ax = plt.subplots(dpi = 150)

ax.set_title('Probability of Water Usage\nfrom One Family during One Day', fontsize = 18, weight = 'bold')
ax.set_xlabel('Time of the Day', fontsize = 14, weight = 'normal')
ax.set_ylabel('Probability of Using Filter', fontsize = 14, weight = 'normal')
ax.set_xticks(xTick)
ax.set_xticklabels(xTickLabel, rotation = 30)

ax.plot(x, y, linestyle = '-', color = cm.turbo(colorIdx[3]))
ax.plot(x1, y1, linestyle = '-', color = cm.turbo(colorIdx[5]))
ax.plot(x2, y2, linestyle = '-', color = cm.turbo(colorIdx[7]))
ax.plot(x3, y3, linestyle = '-', color = cm.turbo(colorIdx[9]))

ax.plot(x4, y4, linestyle = '-', color = cm.turbo(colorIdx[11]))
ax.plot(x5, y5, linestyle = '-', color = cm.turbo(colorIdx[13]))
ax.plot(x6, y6, linestyle = '-', color = cm.turbo(colorIdx[15]))
ax.plot(x7, y7, linestyle = '-', color = cm.turbo(colorIdx[17]))
legend = ['person A at 8:00am', 'person B at 8:12am', 'person C at 8:18am', 'person D at 8:24am',
          'person B at 6:12pm', 'person C at 6:18pm', 'person D at 6:24pm', 'person A at 6:00pm']
ax.legend(legend, loc = 'best', frameon = False)

ax.hist(result, bins=10, rwidth=0.8, density=True)
ax.hist(result1, bins=10, rwidth=0.8, density=True)
ax.hist(result2, bins=10, rwidth=0.8, density=True)
ax.hist(result3, bins=10, rwidth=0.8, density=True)
ax.hist(result4, bins=10, rwidth=0.8, density=True)
ax.hist(result5, bins=10, rwidth=0.8, density=True)
ax.hist(result6, bins=10, rwidth=0.8, density=True)
ax.hist(result7, bins=10, rwidth=0.8, density=True)


#!/usr/bin/env python
#
# Visualize image with numpy and matplotlib.
#
# Last revision: 24/01/2022
from __future__ import print_function, division

import os, sys, numpy as np
import matplotlib.pyplot as plt

imgfile = sys.argv[1]

# Read info file
info = np.genfromtxt(imgfile+'.info',comments='#')
ch   = int(info[0]) # Number of channels
w    = int(info[1]) # Width
h    = int(info[2]) # Heigth

# Load image data - double array
data = np.fromfile(imgfile+'.bin').reshape(h,w,ch)

# Convert to image (uint8)
img = np.clip(data*(1<<8-1),0,1<<8-1).astype(np.uint8)

# Show image
plt.imshow(img)
plt.show()


# [4 - Vetores] O Enigma

#funções úteis:

# Limpeza de espaços vazios durante a entrada das listas originais.
def ajustandoRotor(_rotor: str) -> list:
    _rotor = _rotor.split(' ')
    _rotor = [int(num) for num in _rotor if(num != '')]
    return _rotor

# Verifica se a letra atual é maiúscula ou minúscula.
def checkMin(_charNum: int) -> bool:
    if(_charNum < 97): return False
    else: return True

# Devolve o índice da letra atual no alfabeto.
def pegarIndiceChar(_numCarac: int) -> int:
    '''
    Eu vi essa sacanagem num vídeo de branchless programming em C e desde então queria usar em algum local.
    Peço desculpas pela lógica feia, apesar de correta. Prometo não fazer novamente.
    '''
    _novoIndice = (1-checkMin(_numCarac))*(_numCarac - 65) + (checkMin(_numCarac))*(_numCarac - 97)
    return _novoIndice

# Devolve o caracter pós criptografia.
def pegarCharAtual(_numCarac: int, _nIndex: int) -> str:
    _caract = (1-checkMin(_numCarac))*chr(65 + _nIndex) + (checkMin(_numCarac))*chr(97 + _nIndex)
    return _caract

# "rotaciona" um dado vetor.
def rodandoFila(_rotor: list) -> list:
    _rotor.append(_rotor.pop(0))
    return _rotor

# Verifica se é o momento correto de "rotacionar" um  dado rotor baseado em seu "número".
def checkRodar(_contador: int,_n_dentes: int, _n_rotor: int):
    if(_contador%(_n_dentes**(_n_rotor-1)) != 0):
        return False
    else:
        return True

# Realiza as rotações.
def atualizarRotores(_r1: list, _r2: list, _r3: list, _contador: int) -> bool:
    numDentes = len(_r1)
    rodandoFila(_r1)
    if(checkRodar(_contador, numDentes, 2)): rodandoFila(_r2)
    if(checkRodar(_contador, numDentes, 3)): rodandoFila(_r3)
    return 0

def RhythmOfWar():
    cont = 0
    alfaCont = 0
    while True:
        try:
            line = input()
        except EOFError:
            break

        if(cont == 1):
            r1 = ajustandoRotor(line)
        if(cont == 2):
            r2 = ajustandoRotor(line)
        if(cont == 3):
            r3 = ajustandoRotor(line)

        if(cont > 5):
            for i in range(len(line)):
                if(line[i].isalpha()):
                    numCarac = ord(line[i])
                    indiceLetraAtual = pegarIndiceChar(numCarac)
                    novoIndice = r3[r2[r1[indiceLetraAtual]]]
                    novoCaract = pegarCharAtual(numCarac, novoIndice)
                    print(novoCaract, end='')
                    alfaCont += 1
                    atualizarRotores(r1, r2, r3, alfaCont)

                else:
                    print(line[i], end='')
            print()
        cont +=1
    return 0

RhythmOfWar()


from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
from django.shortcuts import redirect

#postのlistを見せる
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

#postの内容を見る
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

#新しい内容を書く
def post_new(request):
    #htmlのformからPOSTなら
    if request.method == "POST":
        #formのデータを減数formに入れる
        form = PostForm(request.POST)
        #validation後データを保存
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

def post_delete(request, pk):
    if pk  is not None:
        Post.objects.filter(pk=pk).delete()

    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})


#levenstein.py

#ensure you had numba module install
#pip install numba
#if your python ver is 3.11.1, it may not compatible with numba
#can try use python ver that is 3.9.x or 3.10.x

import numpy
from numba import njit

@njit
def levenshteinDistanceDP(token1, token2):

    # token1- original word
    # token2 = new word

    t1=len(token1)
    t2=len(token2)

    token1 = "#" + token1
    token2 = "#" + token2
    distance = numpy.zeros((len(token2), len(token1)))

    for t1 in range(len(token1)):
        distance[0][t1] = t1

    for t2 in range(len(token2)):
        distance[t2][0] = t2

    if (t1!=0) and (t2!=0):
        if token1[1] != token2[1]:
            distance[1,1] = 1

    for c in range(1, len(token1)):
        for r in range(1, len(token2)):

            if c==1 and r==1:
                continue

            if token1[c] != token2[r]:
                distance[r,c] = min(distance[r-1,c], distance[r,c-1], distance[r-1,c-1])+1

            else:
                distance[r,c] = distance[r-1,c-1]

    return distance[(len(token2)-1)][(len(token1)-1)]

def treshold(line1,line2):
    # calculate the Levenshtein distance between the lines
    distance = levenshteinDistanceDP(line1, line2)

    # set a threshold for the minimum distance
    # ask the user for the threshold
    threshold = int(input("Enter the minimum distance threshold: "))

    # if the distance is below the threshold, the lines are similar
    if distance <= threshold:
        print("The lines are similar and should be attributed to the same author.")
    else:
        print("The lines are different and should be attributed to different authors.")


"""
Function to run simulations on different versions of the original dataset from
https://microsoft.github.io/dowhy/dowhy_estimation_methods.html
modified_linear_dataset is a slighly modifed version of linear_dataset from
https://github.com/microsoft/dowhy/blob/master/dowhy/datasets.py
Full code is availible at
"""
import numpy as np
import pandas as pd
from dowhy import CausalModel
import dowhy.datasets
from modified_linear_dataset import modified_linear_dataset

def simulate_dag_violations(
    methods,  # estimators to use
    beta,  # true treatment effect
    num_w_affected,  # number of common causes affected
    effect_on_w,  # effect of U on common causes
    num_z_affected,  # number of common causes affected
    effect_on_z,  # effect of U on instruments
    num_t_affected,  # number of treatments affected
    effect_on_t,  # effect of U on treatment
    effect_on_y,  # effect of U on outcomes
    times,  # number of simulation
):

    output = []
    for _ in range(times):
        # beta, num_common_causes, num_instruments, num_samples, etc. are as in the tutorial
        data = modified_linear_dataset(
            beta=beta,
            # u -> common causes
            num_w_affected=num_w_affected,
            effect_on_w=effect_on_w,
            # u -> instruments
            num_z_affected=num_z_affected,
            effect_on_z=effect_on_z,
            # u -> treatment
            num_t_affected=num_t_affected,
            effect_on_t=effect_on_t,
            # u -> outcome
            effect_on_y=effect_on_y,
            num_common_causes=5,
            num_instruments=2,
            num_samples=10000,
            treatment_is_binary=True,
        )

        df = data["df"]

        model = CausalModel(
            data=df,
            treatment=data["treatment_name"],
            outcome=data["outcome_name"],
            graph=data["gml_graph"],
            instruments=data["instrument_names"],
            proceed_when_unidentifiable=True,
        )

        identified_estimand = model.identify_effect()

        estimates = [
            model.estimate_effect(
                identified_estimand, method_name=i[0], method_params=i[1]
            ).value
            for i in methods
        ]

        tmp_output = list(zip(estimates, [item[0] for item in methods]))

        output = output + tmp_output

    return output


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

__ = None

class AboutLoopStatements(unittest.TestCase):

    def test_building_a_new_transformed_list(self):

        phrase = ["fish", "and", "chips"]

        result = []
        for word in phrase:
            result.append(word.upper())

        assert [__, __, __] == result

    def test_building_a_new_transformed_list_again(self):

        round_table = [
            ["Lancelot", "Blue"],
            ["Galahad", "I don't know!"],
            ["Robin", "Blue! I mean Green!"],
            ["Arthur", "Is that an African Swallow or Amazonian Swallow?"],
        ]

        result = []
        for knight, answer in round_table:
            result.append("Contestant: '" + knight + "' Answer: '" + answer + "'")

        assert result[0] == __
        assert result[1] == __
        assert result[2] == __
        assert result[3] == __

    def test_for_with_conditional_filters_a_list(self):

        pythons = [
            ("John Cleese", 1939),
            ("Terry Gilliam", 1940),
            ("Eric Idle", 1943),
            ("Michael Palin", 1943),
        ]

        born_after_1941 = []
        for comedian, age in pythons:
            if age > 1941:
                born_after_1941.append(comedian)

        assert born_after_1941 == __

    def test_while(self):

        i = 1
        result = 1
        while i <= 10:
            result = result + i
            i = i + 1

        assert __ == result

    def test_while_with_break(self):

        i = 1
        result = 1
        while True:
            if i > 10:
                break
            result = result + i
            i = i + 1

        assert __ == result

    def test_while_with_continue(self):

        i = 0
        result = []
        while i < 10:
            i = i + 1
            if (i % 2) == 0:
                continue
            result.append(i)

        assert __ == result


from os import path

from PyQt5 import QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

import unsplash
import wall
import win_darkmode
import utils

class UnsplashWindow:
    def __init__(self, main_window):
        self.ui = main_window
        self.screenSize = QDesktopWidget().screenGeometry(0)
        self.image_path = None
        self.unsplash_instance = unsplash.Unsplash(
            self.screenSize.width(), self.screenSize.height()
        )
        self.ui.unsplashPhoto.setMaximumHeight(int(0.7 * self.screenSize.height()))
        self.ui.unsplashPhoto.setMaximumWidth(int(0.99 * self.screenSize.width()))
        self.ui.unsplashSearchTextEdit.setMaximumWidth(
            int(0.15 * self.screenSize.width())
        )
        self.ui.unsplashNextWallButton.clicked.connect(self.next_wallpaper)
        self.ui.unsplashWallpaperButton.clicked.connect(self.set_wallpaper)
        self.ui.unsplashSaveButton.clicked.connect(self.save_wallpaper)

    def next_wallpaper(self):
        self.enable_wall_buttons(False)
        query = self.ui.unsplashSearchTextEdit.toPlainText()
        if self.ui.unsplashFeaturedCheck.isChecked():
            is_featured = True
        else:
            is_featured = False

        self.download_thread = UnsplashDownloadThread(
            self.unsplash_instance, is_featured, query
        )
        self.download_thread.signal.connect(self.display_wallpaper)
        self.download_thread.start()

    def save_wallpaper(self):
        if self.image_path is None:
            messagebox = QMessageBox()
            messagebox.setWindowTitle("Wallpaper not found!")
            messagebox.setText("Choose a wallpaper to set")
            messagebox.setIcon(QMessageBox.Critical)
            messagebox.exec_()
        else:
            wall.saveWall(
                self.image_path,
                utils.Helpers.saved_wall_path(
                    self.image_path,
                    self.unsplash_instance.get_image_extension()
                    )
            )
            messagebox = QMessageBox()
            messagebox.setWindowTitle("Wallpaper saved!")
            messagebox.setText("Wallpaper saved in User's Pictures folder")
            messagebox.setIcon(QMessageBox.Information)
            messagebox.exec_()

    def set_wallpaper(self):
        if self.image_path is None:
            messagebox = QMessageBox()
            messagebox.setWindowTitle("Wallpaper not found!")
            messagebox.setText("Choose a wallpaper to set")
            messagebox.setIcon(QMessageBox.Critical)
            messagebox.exec_()
        else:
            self.toggle_dark_mode()
            wall.changeBG(self.image_path)
            if not utils.Helpers.insert_history(self.unsplash_instance.wallpaper_url, "unsplash"):
                QMessageBox.warning(QMessageBox(), 'Error', 'Could not add wall to the history.')

    def display_wallpaper(self, image_path):
        self.image_path = image_path
        self.ui.unsplashPhoto.setPixmap(QtGui.QPixmap(self.image_path))
        self.ui.unsplashPhoto.setScaledContents(True)
        self.enable_wall_buttons(True)

    def toggle_dark_mode(self):
        if self.ui.unsplashDarkModeCheck.isChecked():
            win_darkmode.setDarkMode()
        else:
            win_darkmode.setLightMode()

    def enable_wall_buttons(self, state):
        self.ui.unsplashNextWallButton.setEnabled(state)
        self.ui.unsplashSaveButton.setEnabled(state)
        self.ui.unsplashWallpaperButton.setEnabled(state)

class UnsplashDownloadThread(QThread):
    signal = pyqtSignal(str)

    def __init__(self, unsplash_instance,is_featured, query):
        QThread.__init__(self)
        self.unsplash_instance = unsplash_instance
        self.unsplash_instance.set_featured(is_featured)
        if query and not query.isspace():
            self.unsplash_instance.set_query(query)

    def run(self):
        self.unsplash_instance.get_unsplash_pic()
        print(self.unsplash_instance.wallpaper_url)
        self.image_path = self.unsplash_instance.get_download_path()
        utils.Helpers.download_wall(self.image_path,self.unsplash_instance.wallpaper_url)
        self.signal.emit(self.image_path)


import random
import sys
import time

directions = ["R", "L", "D", "U"]
moves = {
    "R": [0, 1],
    "L": [0, -1],
    "U": [-1, 0],
    "D": [1, 0]
}
maze = []
maze_size = 0

class DNA:
    def __init__(self):
        self.genes = []
        self.fitness = 0

    def create_genes(self, number):
        for i in range(number):
            self.genes.append(directions[random.randint(0, 3)])

    def update_fitness(self):
        best_score = 0
        position = [0, 0]

        for a in range(maze_size):
            for b in range(maze_size):
                if maze[a][b] == "S":
                    position = [a, b]
                    break

        goal = [0, 0]

        for a in range(maze_size):
            for b in range(maze_size):
                if maze[a][b] == "F":
                    goal = [a, b]
                    break

        for gene in self.genes:
            position[0] += moves[gene][0]
            position[1] += moves[gene][1]
            if position[0] < 0 or position[0] >= maze_size or position[1] < 0 or position[1] >= maze_size:
                position[0] -= moves[gene][0]
                position[1] -= moves[gene][1]
            elif maze[position[0]][position[1]] == "X":
                position[0] -= moves[gene][0]
                position[1] -= moves[gene][1]

            if maze[position[0]][position[1]] == "F":
                best_score = 2*maze_size
                break

            score = 2 * maze_size - (abs(goal[0] - position[0]) + abs(goal[1] - position[1]))

            if score > best_score:
                best_score = score

        self.fitness = best_score**2

    def crossover(self, data):
        parent1 = data[0]
        parent2 = data[1]

        midpoint = random.randint(1, len(parent1.genes)-1)

        self.genes = list(parent1.genes[:midpoint] + parent2.genes[midpoint:])

    def mutate(self, chance):
        for k in range(len(self.genes)):
            num = random.randint(1, 100)
            if num <= chance:
                self.genes[k] = directions[random.randint(0, 3)]

class Population:
    def __init__(self, data):
        self.population_size = data[0]
        self.mutation_rate = data[1]
        self.generations = 0
        self.population = []
        self.pool = []
        self.done = False
        self.best = 0
        self.complete = []

    def populate(self):
        for n in range(self.population_size):
            chromosome = DNA()
            chromosome.create_genes(maze_size**2)
            self.population.append(chromosome)

    def calculate_fitness(self):
        for solution in self.population:
            solution.update_fitness()
            if solution.fitness > self.best:
                self.best = solution.fitness
                self.complete = solution.genes.copy()

            if solution.fitness == (2*maze_size)**2:
                self.done = True

    def generate(self):
        self.generations += 1
        self.pool = self.population.copy()

        maximum = 0

        for sequence in self.pool:
            maximum += sequence.fitness

        if maximum == 0:
            self.population = []
            self.populate()

        else:
            for m in range(self.population_size):
                number1 = random.randint(1, maximum)
                number2 = random.randint(1, maximum)
                current = 0

                while number1 > 0:
                    number1 -= self.pool[current].fitness
                    current += 1

                parent1 = self.pool[current-1]

                current = 0

                while number2 > 0:
                    number2 -= self.pool[current].fitness
                    current += 1

                parent2 = self.pool[current-1]

                self.population[m].crossover([parent1, parent2])
                self.population[m].mutate(self.mutation_rate)

def solve(board, size_of_population, rate_of_mutation):
    global maze
    maze = board.copy()
    global maze_size
    maze_size = len(maze)

    test = Population([size_of_population, rate_of_mutation])
    test.populate()
    achieved = 0
    starting_time = time.time()

    while not test.done:
        new_time = time.time()
        if new_time >= starting_time + 10:
            print("Halting program execution, time limit exceeded")
            print("Try increasing mutation rate to 5%")
            sys.exit()

        test.calculate_fitness()
        if test.best > achieved:
            achieved = test.best
            print("Best: " + str(test.best))
        test.generate()

    print("Solved after " + str(test.generations) + " generations")
    print("".join(test.complete))

    return


from flask_app.config.mysqlconnection import connectToMySQL
from flask_app import DATABASE
from flask import flash
from flask_app.models import user_model

class Roads:
    def __init__(self, data):
        self.id = data['id']
        self.date = data['date']
        self.origin = data['origin']
        self.destination = data['destination']
        self.created_at = data['created_at']
        self.updated_at = data['updated_at']
        self.user_id = data['user_id']
        self.post_by = None

#?=========create a classmethod========
    @classmethod
    def roads_utv(cls,data):
        query = """
            INSERT INTO off_roads (origin,destination,user_id,date)
            VALUES (%(origin)s,%(destination)s,%(user_id)s,%(date)s);
        """
        return connectToMySQL(DATABASE).query_db(query,data)

#?===========read all==========
    @classmethod
    def get_all(cls):
        query = """
            SELECT * FROM off_roads
            JOIN users
            ON off_roads.user_id = users.id;

        """
        results = connectToMySQL(DATABASE).query_db(query)
        print (results)

        all_roads = []
        if results:
            for row in results:
                the_roads = cls(row)
                user_data = {
                    'id' : row['user_id'],
                    'created_at' : row['users.created_at'],
                    'updated_at' : row['users.updated_at'],
                    **row
                }
                this_user = user_model.User(user_data)
                the_roads.create_by = this_user
                all_roads.append(the_roads)
        return all_roads

#?=======read one========
#
    @classmethod
    def get_by_id(cls,data):
        query = """
            SELECT * FROM off_roads
            JOIN users
            ON off_roads.user_id = users.id
            WHERE off_roads.id = %(id)s;
        """
        results = connectToMySQL(DATABASE).query_db(query,data)
        print (results)
        this_roads = cls(results[0])
        for row in results:
            user_data = {
                **row,
                'id' : row['user_id'],
                'created_at' : row['users.created_at'],
                'updated_at' : row['users.updated_at']
            }
            this_user = user_model.User(user_data)
            this_roads.post_by = this_user
            return this_roads
        return False

#?=======update========
    # @classmethod
    # def update_roads(cls,data):
    #     query = """
    #         UPDATE off_roads
    #         SET origin = %(origin)s,
    #         destination = %(destination)s,
    #         date = %(date)s
    #         WHERE id = %(id)s;
    #     """
    #     return connectToMySQL(DATABASE).query_db(query,data)

#?=======delete========

    @classmethod
    def delete(cls,data):
        query = """
            DELETE FROM off_roads
            WHERE id = %(id)s;
        """
        return connectToMySQL(DATABASE).query_db(query,data)

#?=======validator=======

    @staticmethod
    def validator(data):
        is_valid =True
        print(data)
        # if len(data['name']) < 1:
        #     is_valid = False
        #     flash("Must have a Name")
        # if len(data['place']) < 1:
        #     is_valid = False
        #     flash("Must have a Place")
        if len(data['date']) < 1:
            is_valid = False
            flash("Must type a Date")
        if len(data['origin']) < 1:
            is_valid = False
            flash("Must create a Origin")
        if len(data['destination']) < 1:
            is_valid = False
            flash("Must type a Destination")

        return is_valid


import numpy as np

def count_unimodular(char_poly_file, in_memory=True):

    if in_memory:

        # Load characteristic polynomials
        char_polys = np.genfromtxt(char_poly_file, delimiter=',', skip_header=1, dtype=np.int64)
        counts = char_polys[:,0]
        dets = char_polys[:,-1]
        return np.sum(counts[np.abs(dets) == 1])

    else:
        n_unimodular = 0
        with open(char_poly_file) as f:
            next(f) # Skip header
            for line in f:
                data = line.split(',')
                det = int(data[-1])
                count = int(data[0])
                if abs(det) == 1:
                    n_unimodular += count
        return n_unimodular


#Kafka Stats BEYOND
KafkaSTR = 0
KafkaDEX = 2
KafkaCON = -1
KafkaINT = 3
KafkaWIS = 1
KafkaCHARM = 4

#Kafka Skills
KafkaSkills = [
    '2',
    '1',
    '3',
    '0',
    '6',
    '5',
    '3',
    '6',
    '5',
    '1',
    '3',
    '1',
    '4',
    '4',
    '3',
    '2',
    '4',
    '1',
    '1',
]

#kafka DMG
KafkaBASICDMG = 375
KafkaSKilldmg = 412.5
KafkaUltimateDMG = 412.5
KafkaSpeedAdd = 30

#Kafla Stat SHEET
KafkaATTACK = 750
KafkaHP = 1200
KafkaDEF = 535
KafkaCrit = [1]
EnergyFromEach = 25
EnergyMax = 100
Speed = 100


from keras import backend as K
import numpy as np
import cv2

def balanced_binary_crossentropy(y_true, y_pred):
    """Binary crossentropy loss function with automatic class balancing"""
    y_true_f = K.cast(y_true,K.floatx())
    num_pos = K.sum(y_true_f)+1
    num_neg = K.sum(1-y_true_f)+1
    #weights = 1/(2*num_pos)*y_true + 1/(2*num_neg)*(1-y_true)
    weights = (num_neg)/(num_pos)*y_true_f + (1-y_true_f)
    score_array = K.binary_crossentropy(y_pred,y_true_f)
    score_array *= weights
    score_array /= K.mean(K.cast(K.not_equal(weights, 0), K.floatx()))
    return K.mean(score_array)

def pad_images(imgs,pad):
    """Pad images with reflection padding"""
    imgs_p = np.ndarray((imgs.shape[0], imgs.shape[1]+pad*2, imgs.shape[2]+pad*2, imgs.shape[3]), dtype=imgs.dtype)
    for i in xrange(imgs.shape[0]):
        imgs_p[i,:,:,:] = cv2.copyMakeBorder(imgs[i,:,:,:],pad,pad,pad,pad,cv2.BORDER_REFLECT)
    return imgs_p

def remove_mean(imgs):
    """Subtract per-channel mean from each image"""
    for i in xrange(imgs.shape[0]):
        for j in xrange(imgs.shape[3]):
            imgs[i,:,:,j] -= np.mean(imgs[i,:,:,j])
    return imgs


"""
name = "Pau"

#Funciones!! (esta es la funcion "hi")
def hi(name):
	if name == 'Ola':
		print('Hi Ola!')
	elif name == 'Pau':
		print('Hi Pau!')
	else:
		print('Hi anonymous!')
hi(name) #con esto mandas llamar la funcion anterior

#si ponemos un parametro en la funcion tenemos que ponerlo
#tmb cuando lo mandamos llamar

"""

"""
def hi(name):
	print('Hi ' + name + '!')
hi("Rachel")
"""

colores = ['Blanco', 'Negro', 'Azul', 'Rojo', 'Cafe']

def color(name):
	print("color " +name+ "!!")

#Bucle p/imprimir el array anterior
for name in colores: #for variableTemporal in nombreArray
	color(name) #nombreFuncion()
	print("Next color")

#este for imprime un rango determinado de nums
max = 5
for actual in range(1,max):
	print(actual)


import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

class NeRF(nn.Module):
    def __init__(self,input_x, input_d):
        super(NeRF, self).__init__() # init nn.Module
        self.input_x = input_x
        self.input_d = input_d
        self.skip = 5
        D, W = 8, 256
        self.pts_linears = nn.ModuleList()
        for i in range(D):
            if i == 0:
                self.pts_linears.append(nn.Linear(input_x, W)) # device and dtype are default torch.cuda.FloatTensor
            elif i == self.skip:
                self.pts_linears.append(nn.Linear(W + input_x, W))
            else:
                self.pts_linears.append(nn.Linear(W, W))
        self.alpha_linear = nn.Linear(W, 1)
        self.feature_linear = nn.Linear(W, W)
        self.views_linears = nn.ModuleList()
        self.views_linears.append(nn.Linear(W + input_d, W//2))
        self.rgb_linear = nn.Linear(W//2, 3)

    def forward(self, input):
        #input [N, input_x + input_d]
        input_pts, input_views = torch.split(input, [self.input_x, self.input_d], dim = -1)
        out = input_pts
        for i, f in enumerate(self.pts_linears):
            if i == self.skip:
                out = F.relu(f(torch.cat((input_pts,out), -1)))
            else:
                out = F.relu(f(out))
        alpha = F.relu(self.alpha_linear(out)) # official version do relu in raw2outputs function
        out = self.feature_linear(out) # no activation
        out = torch.cat((out,input_views), -1)
        out = F.relu(self.views_linears[0](out))
        out = self.rgb_linear(out)
        out = torch.sigmoid(out)# official version do it in raw2outputs function

        out = torch.cat((out, alpha), -1)
        return out


from typing import Tuple, Type, TypeVar

from ssz.hashable_container import HashableContainer
from ssz.sedes import Bitvector, uint64

ATTESTATION_SUBNET_COUNT = 64

TMetaData = TypeVar("TMetaData", bound="MetaData")

default_attnets_tuple = (False,) * ATTESTATION_SUBNET_COUNT

class SeqNumber(int):
    pass

default_seq_number = SeqNumber(0)

class MetaData(HashableContainer):
    fields = [("seq_number", uint64), ("attnets", Bitvector(ATTESTATION_SUBNET_COUNT))]

    @classmethod
    def create(
        cls: Type[TMetaData],
        *,
        seq_number: SeqNumber = default_seq_number,
        attnets: Tuple[bool, ...] = default_attnets_tuple,
    ) -> TMetaData:
        return super().create(seq_number=seq_number, attnets=attnets)

    def __str__(self) -> str:
        attnets = map(lambda elem: "1" if elem else "0", self.attnets)
        return f"seq_number={self.seq_number}, attnets=0b{''.join(attnets)}"


import os
import numpy as np
import tensorflow as tf
import source.layers as lay

class DGM(object):

    def __init__(self, \
        height, width, channel, ksize, zdim, \
        learning_rate=1e-3, path='', verbose=True):

        print("\nInitializing Neural Network...")
        self.height, self.width, self.channel, self.ksize, self.zdim = \
            height, width, channel, ksize, zdim
        self.learning_rate = learning_rate
        self.path_ckpt = path

        self.x = tf.compat.v1.placeholder(tf.float32, [None, self.height, self.width, self.channel], \
            name="x")
        self.y = tf.compat.v1.placeholder(tf.float32, [None, 1], \
            name="x")
        self.batch_size = tf.compat.v1.placeholder(tf.int32, shape=[], \
            name="batch_size")
        self.training = tf.compat.v1.placeholder(tf.bool, shape=[], \
            name="training")

        self.layer = lay.Layers()

        self.variables, self.losses = {}, {}
        self.__build_model(x=self.x, ksize=self.ksize, verbose=verbose)
        self.__build_loss()

        with tf.control_dependencies(self.variables['ops_d']):
            self.optimizer_d = tf.compat.v1.train.AdamOptimizer( \
                self.learning_rate, name='Adam_d').minimize(\
                self.losses['loss_d'], var_list=self.variables['params_d'])

        with tf.control_dependencies(self.variables['ops_g']):
            self.optimizer_g = tf.compat.v1.train.AdamOptimizer( \
                self.learning_rate, name='Adam_g').minimize(\
                self.losses['loss_g'], var_list=self.variables['params_g'])

        tf.compat.v1.summary.scalar('DGM/loss_a', self.losses['loss_a'])
        tf.compat.v1.summary.scalar('DGM/loss_r', self.losses['loss_r'])
        tf.compat.v1.summary.scalar('DGM/loss_tv', self.losses['loss_tv'])
        tf.compat.v1.summary.scalar('DGM/loss_g', self.losses['loss_g'])
        tf.compat.v1.summary.scalar('DGM/loss_d', self.losses['loss_d'])
        self.summaries = tf.compat.v1.summary.merge_all()

        self.__init_session(path=self.path_ckpt)

    def step(self, x, y, iteration=0, training=False):

        feed_tr = {self.x:x, self.y:y, self.batch_size:x.shape[0], self.training:True}
        feed_te = {self.x:x, self.y:y, self.batch_size:x.shape[0], self.training:False}

        summary_list = []
        if(training):
            try:
                _, summaries = self.sess.run([self.optimizer_d, self.summaries], \
                    feed_dict=feed_tr, options=self.run_options, run_metadata=self.run_metadata)
                summary_list.append(summaries)

                _, summaries = self.sess.run([self.optimizer_g, self.summaries], \
                    feed_dict=feed_tr, options=self.run_options, run_metadata=self.run_metadata)
                summary_list.append(summaries)
            except:
                _, summaries = self.sess.run([self.optimizer_d, self.summaries], \
                    feed_dict=feed_tr)
                summary_list.append(summaries)

                _, summaries = self.sess.run([self.optimizer_g, self.summaries], \
                    feed_dict=feed_tr)
                summary_list.append(summaries)

            for summaries in summary_list:
                self.summary_writer.add_summary(summaries, iteration)

        y_hat, loss_d, loss_g, mse = \
            self.sess.run([self.variables['y_hat'], self.losses['loss_d'], self.losses['loss_g'], self.losses['mse']], \
            feed_dict=feed_te)

        outputs = {'y_hat':y_hat, 'loss_d':loss_d, 'loss_g':loss_g, 'mse':mse}
        return outputs

    def save_parameter(self, model='model_checker', epoch=-1):

        self.saver.save(self.sess, os.path.join(self.path_ckpt, model))
        if(epoch >= 0): self.summary_writer.add_run_metadata(self.run_metadata, 'epoch-%d' % epoch)

    def load_parameter(self, model='model_checker'):

        path_load = os.path.join(self.path_ckpt, '%s.index' %(model))
        if(os.path.exists(path_load)):
            print("\nRestoring parameters")
            self.saver.restore(self.sess, path_load.replace('.index', ''))

    def confirm_params(self, verbose=True):

        print("\n* Parameter arrange")

        ftxt = open("list_parameters.txt", "w")
        for var in tf.compat.v1.trainable_variables():
            text = "Trainable: " + str(var.name) + str(var.shape)
            if(verbose): print(text)
            ftxt.write("%s\n" %(text))
        ftxt.close()

    def confirm_bn(self, verbose=True):

        print("\n* Confirm Batch Normalization")

        t_vars = tf.compat.v1.trainable_variables()
        for var in t_vars:
            if('bn' in var.name):
                tmp_x = np.zeros((1, self.height, self.width, self.channel))
                tmp_y = np.zeros((1, 1))
                values = self.sess.run(var, \
                    feed_dict={self.x:tmp_x, self.y:tmp_y, self.batch_size:1, self.training:False})
                if(verbose): print(var.name, var.shape)
                if(verbose): print(values)

    def loss_l1(self, x, reduce=None):

        distance = tf.compat.v1.reduce_sum(\
            tf.math.abs(x), axis=reduce)

        return distance

    def loss_l2(self, x, reduce=None):

        distance = tf.compat.v1.reduce_sum(\
            tf.math.sqrt(\
            tf.math.square(x) + 1e-9), axis=reduce)

        return distance

    def __init_session(self, path):

        try:
            sess_config = tf.compat.v1.ConfigProto()
            sess_config.gpu_options.allow_growth = True
            self.sess = tf.compat.v1.Session(config=sess_config)

            self.sess.run(tf.compat.v1.global_variables_initializer())
            self.saver = tf.compat.v1.train.Saver()

            self.summary_writer = tf.compat.v1.summary.FileWriter(path, self.sess.graph)
            self.run_options = tf.compat.v1.RunOptions(trace_level=tf.compat.v1.RunOptions.FULL_TRACE)
            self.run_metadata = tf.compat.v1.RunMetadata()
        except: pass

    def __build_loss(self):

        # Adversarial loss
        least_square_term = tf.math.square(\
            self.variables['d_real'] - tf.ones_like(self.variables['d_real']) + 1e-9)
        self.losses['loss_a'] = tf.compat.v1.reduce_mean(0.5 * least_square_term)

        # Reconstruction losses
        self.losses['loss_r1'] = \
            self.loss_l1(self.variables['y_hat'] + self.variables['a'] - self.x, [1, 2, 3])
        self.losses['loss_r2'] = \
            self.loss_l1(self.variables['z_phat'] - self.x, [1, 2, 3])

        y_ext = tf.compat.v1.reshape(self.y, shape=[self.batch_size, 1, 1, 1], \
                name="y_ext")
        self.losses['loss_r3'] = \
            self.loss_l1(self.variables['a'] * y_ext, [1, 2, 3])

        # Total variation loss
        shift_i = tf.roll(self.variables['y_hat'], shift=[1], axis=[1])
        shift_j = tf.roll(self.variables['y_hat'], shift=[1], axis=[2])
        tv_i_term = \
            tf.math.abs(self.variables['y_hat'] - shift_i)
        tv_j_term = \
            tf.math.abs(self.variables['y_hat'] - shift_j)
        self.losses['loss_tv'] = \
            tf.compat.v1.reduce_sum(tv_i_term + tv_j_term, axis=[1, 2, 3])

        lambda_a, lambda_r, lambda_tv = 10, 10, 1 # in paper
        term_a = lambda_a * self.losses['loss_a']
        term_r = lambda_r * \
            (self.losses['loss_r1'] + self.losses['loss_r2'] + self.losses['loss_r3'])
        term_tv = lambda_tv * self.losses['loss_tv']
        self.losses['loss_g'] = \
            tf.compat.v1.reduce_mean(term_a + term_r + term_tv)
        self.losses['loss_a'] = tf.compat.v1.reduce_mean(term_a)
        self.losses['loss_r'] = tf.compat.v1.reduce_mean(term_r)
        self.losses['loss_tv'] = tf.compat.v1.reduce_mean(term_tv)

        # For D optimization
        d_real_term = \
            self.loss_l2(self.variables['d_real'] - tf.zeros_like(self.variables['d_real']), [1])
        d_fake_term = \
            self.loss_l2(self.variables['d_fake'] - tf.ones_like(self.variables['d_fake']), [1])
        self.losses['loss_d'] = tf.compat.v1.reduce_mean(0.5 * (d_real_term + d_fake_term))

        self.losses['mse'] = \
            tf.compat.v1.reduce_mean(self.loss_l2(self.variables['y_hat'] - self.x, [1, 2, 3]))

        self.variables['params_d'], self.variables['params_g'] = [], []
        for var in tf.compat.v1.trainable_variables():
            text = "Trainable: " + str(var.name) + str(var.shape)
            if('dis_' in var.name): self.variables['params_d'].append(var)
            else: self.variables['params_g'].append(var)

        self.variables['ops_d'], self.variables['ops_g'] = [], []
        for ops in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS):
            if('dis_' in ops.name): self.variables['ops_d'].append(ops)
            else: self.variables['ops_g'].append(ops)

    def __build_model(self, x, ksize=3, verbose=True):

        print("\n-*-*- Flow 1 -*-*-")
        # Module 1: E_G
        self.variables['c_z'] = \
            self.__encoder(x=x, ksize=ksize, outdim=self.zdim, reuse=False, \
            name='enc_g', norm=True, verbose=verbose)
        # Module 2: D_G
        self.variables['y_hat'] = \
            self.__decoder(z=self.variables['c_z'], ksize=ksize, reuse=False, \
            name='gen_g', norm=True, verbose=verbose)
        # Module 3: D
        self.variables['d_real'] = \
            self.__encoder(x=x, ksize=ksize, outdim=1, reuse=False, \
            name='dis_g', norm=True, verbose=verbose)
        # Revisit D
        self.variables['d_fake'] = \
            self.__encoder(x=self.variables['y_hat'], ksize=ksize, outdim=1, reuse=True, \
            name='dis_g', norm=True, verbose=False)

        print("\n-*-*- Flow 2 -*-*-")
        # Module 4: E_F
        self.variables['c_s'] = \
            self.__encoder(x=x, ksize=ksize, outdim=self.zdim, reuse=False, \
            name='enc_f', norm=False, verbose=verbose)
        # Module 5: D_F
        self.variables['a'] = \
            self.__decoder(z=self.variables['c_s'], ksize=ksize, reuse=False, \
            name='gen_f', norm=True, verbose=verbose)

        print("\n-*-*- Flow 3 -*-*-")
        # Vector joint
        self.variables['c_joint'] = \
            tf.concat([self.variables['c_z'], self.variables['c_s']], 1)
        # Module 6: D_J
        self.variables['z_phat'] = \
            self.__decoder(z=self.variables['c_joint'], ksize=ksize, reuse=False, \
            name='gen_j', norm=True, verbose=verbose)

    def __encoder(self, x, ksize=3, outdim=1, reuse=False, \
        name='enc', activation='relu', norm=True, depth=3, verbose=True):

        with tf.variable_scope(name, reuse=reuse):

            c_in, c_out = self.channel, 16
            for idx_d in range(depth):
                conv1 = self.layer.conv2d(x=x, stride=1, padding='SAME', \
                    filter_size=[ksize, ksize, c_in, c_out], batch_norm=norm, training=self.training, \
                    activation=activation, name="%s_conv%d_1" %(name, idx_d), verbose=verbose)
                conv2 = self.layer.conv2d(x=conv1, stride=1, padding='SAME', \
                    filter_size=[ksize, ksize, c_out, c_out], batch_norm=norm, training=self.training, \
                    activation=activation, name="%s_conv%d_2" %(name, idx_d), verbose=verbose)
                maxp = self.layer.maxpool(x=conv2, ksize=2, strides=2, padding='SAME', \
                    name="%s_pool%d" %(name, idx_d), verbose=verbose)

                if(idx_d < (depth-1)): x = maxp
                else: x = conv2

                c_in = c_out
                c_out *= 2

            rs = tf.compat.v1.reshape(x, shape=[self.batch_size, int(7*7*64)], \
                name="%s_rs" %(name))
            e = self.layer.fully_connected(x=rs, c_out=outdim, \
                batch_norm=False, training=self.training, \
                activation=None, name="%s_fc1" %(name), verbose=verbose)

            return e

    def __decoder(self, z, ksize=3, reuse=False, \
        name='dec', activation='relu', norm=True, depth=3, verbose=True):

        with tf.variable_scope(name, reuse=reuse):

            c_in, c_out = 64, 64
            h_out, w_out = 14, 14

            fc1 = self.layer.fully_connected(x=z, c_out=7*7*64, \
                batch_norm=norm, training=self.training, \
                activation=activation, name="%s_fc1" %(name), verbose=verbose)
            rs = tf.compat.v1.reshape(fc1, shape=[self.batch_size, 7, 7, 64], \
                name="%s_rs" %(name))

            x = rs
            for idx_d in range(depth):
                if(idx_d == 0):
                    convt1 = self.layer.conv2d(x=x, stride=1, padding='SAME', \
                        filter_size=[ksize, ksize, c_in, c_out], batch_norm=norm, training=self.training, \
                        activation=activation, name="%s_conv%d_1" %(name, idx_d), verbose=verbose)
                else:
                    convt1 = self.layer.convt2d(x=x, stride=2, padding='SAME', \
                        output_shape=[self.batch_size, h_out, w_out, c_out], filter_size=[ksize, ksize, c_out, c_in], \
                        dilations=[1, 1, 1, 1], batch_norm=norm, training=self.training, \
                        activation=activation, name="%s_conv%d_1" %(name, idx_d), verbose=verbose)
                    h_out *= 2
                    w_out *= 2

                convt2 = self.layer.conv2d(x=convt1, stride=1, padding='SAME', \
                    filter_size=[ksize, ksize, c_out, c_out], batch_norm=norm, training=self.training, \
                    activation=activation, name="%s_conv%d_2" %(name, idx_d), verbose=verbose)
                x = convt2

                if(idx_d == 0):
                    c_out /= 2
                else:
                    c_in /= 2
                    c_out /= 2

            d = self.layer.conv2d(x=x, stride=1, padding='SAME', \
                filter_size=[ksize, ksize, c_in, self.channel], batch_norm=False, training=self.training, \
                activation='sigmoid', name="%s_conv%d_3" %(name, idx_d), verbose=verbose)

            return d


import socket
import time

now = time.time()
server_address = ("192.168.43.232", 6205) # The address of the server. its "" because we are in the same machine

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # same as server
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_socket.settimeout(3)
client_socket.connect(server_address) # we initialise the connection. this will not finish excuting until the server accepts.

print("connected")

message = b'12345678' # same as server
client_socket.send(message)  # same as server
print("message sent")
total = bytearray()
while True:

    try:
        data = client_socket.recv(400000)  # same as server
        print("message recieved", data, len(data))
        total.extend(data)
    except:
        break

with open("image.jpg", "wb") as f:
    f.write(total)

client_socket.close()
print(time.time() - now)


arr = [int(x) for x in input().split()]
target = int(input())
def binSearch():
    start = 0
    end = len(arr) - 1

    while start <= end:

        mid = start + (end - start)//2

        if arr[mid] > target:
            if mid == 0 or arr[mid - 1] < target:
                return mid
            else:
                end = mid - 1

        elif arr[mid] <= target:
            if mid == len(arr) - 1:
                return mid
            else:
                start = mid + 1

    return -1

print("Elem found at - ",binSearch())


def brandGame():
    while True:
        print("Type a brand and I will tell you the brand's tradermark")
        print("Which tradermark would you like to see: Nike, Adidas, Puma, Bracelona, Under-Armour")
        brand = input("Tell me a brand: ")
        if "Nike" in brand:
            print("Just do it")
        elif "Adidas" in brand:
            print("Impissible is Nothing")
        elif "Puma" in brand:
            print("The fastest in the world")
        elif "Barcelona" in brand:
            print("mes que un club")
        elif "Under-Armour" in brand:
            print("Protect this house")
        elif brand == 'q':
            break
        else:
            print("Sorry, you might have typed it wrong, or the word typed is not an available option")

brandGame()


# -*- coding: utf-8 -*-
"""
Created on Sat Jul  7 08:36:17 2018

@author: Vishwesh
"""

import tensorflow as tf

a = tf.constant(5)
b = tf.constant(3)
d = tf.add(a,b)
c = tf.multiply(b,a)
f = tf.add(d,c)
e = tf.subtract(d,c)
g = tf.divide(f,e)

with tf.Session() as sess:
    outs = sess.run(g)
print("outs = {}".format(outs))


from dataclasses import dataclass
from typing import Any, Dict

import inflect

# See the K8s Python API's client.CustomObjectsApi() and
# create_namespaced_custom_object for examples.  The namespace field will
# be supplied at object creation time and therefore is not present in the
# CRDParser class

CRDBody = Dict[str, Any]
# This represents the body of a K8s custom object.

_p = inflect.engine()

@dataclass(frozen=True)
class CRDParser:
    group: str
    """Group is the K8s API group for the custom resource.
    e.g. 'ricoberger.de'"""

    version: str
    """Version is the API version.  e.g. 'v1alpha1'"""

    name: str
    """Name is the name of this CRD object.  e.g. 'butler-secret'"""

    plural: str
    """The plural of this object Kind.  We just defer to the 'inflect'
    package for this."""

    @classmethod
    def from_crd_body(cls, body: CRDBody) -> "CRDParser":
        """Ingest a Python Dict representation of a Custom Resource, and
        return a CRDParser with the properties filled out.  Raises KeyError
        if required fields are not present.  Required fields are currently:
        'apiVersion', 'kind', and 'metadata.name'.  The 'apiVersion' field
        must contain a slash, with the group before the slash and the version
        after it; raises IndexError if that isn't true."""
        (group, version) = body["apiVersion"].split("/")
        return cls(
            group=group,
            version=version,
            name=body["metadata"]["name"],
            plural=_p.plural(body["kind"].lower()),
        )


"""
Crie um programa que recebe uma lista de inteiros e um valor que deve ser buscado.
O programa deve retornar o índice onde o valor foi encontrado, ou -1, caso não encontre o valor.
"""
lista=[]
adicionar=1

while True:
    while adicionar==1:
        inserir=int(input("Digite um valor para adicionar a lista: "))
        lista.append(inserir)
        adicionar=int(input("Digite 1 para continuar ou 2 para parar: "))
        if adicionar!=1:
            numero= int(input("Digite o valor a buscar: "))
            for i in lista:
                if numero in lista:
                    print(f"O valor '{numero}' se encontra no indice '{i}' da lista")
                    adicionar=int(input("Digite 1 para continuar ou 2 para parar: "))
                    if adicionar!=1:
                        break
                    else:
                        continue
                elif i>len(lista):
                    print("Valor nao encontrado")
                    break
                else:
                    continue


from polyphony import testbench
from polyphony import unroll

def unroll16(start, stop):
    sum = 0
    for i in unroll(range(4)):
        sum += i

    for i in range(10):
        sum += i

    for i in unroll(range(4)):
        sum += i

    return sum

@testbench
def test():
    print(unroll16(0, 10))
    assert 57 == unroll16(0, 10)

test()


import math

import numpy

import param

class count:
        def __init__(self) -> None:
            self.min = None
            self.max = None
        def __call__(self, num):
            self.min = min(self.min, num) if self.min != None else num
            self.max = max(self.max, num) if self.max != None else num

class image:
    def __init__(self, img):
        self.img = img

    def get_image_info(self):
        le2ri = count()
        to2bo = count()
        for i in range(len(self.img)):
            for j in range(len(self.img[i])):
                if self.img[i][j] > param.threshold.pixel:
                    le2ri(j)
                    to2bo(i)
        unit = max( (le2ri.max - le2ri.min + 1) / param.threshold.ratio.width,
                    (to2bo.max - to2bo.min + 1) / param.threshold.ratio.height )
        return param._json({
            'unit': unit,
            'x':    to2bo.min,
            'y':    le2ri.min,
            'width' :int(math.ceil(unit * param.threshold.ratio.width)),
            'height':int(math.ceil(unit * param.threshold.ratio.height))
        })

    def clip_image(self, frame):
        result = numpy.zeros((frame.height, frame.width))
        for x in range(frame.height):
            for y in range(frame.width):
                try:
                    result[x][y] = self.img[x + frame.x][y + frame.y]
                except IndexError:
                    pass
        return image(result)

    def center_image(self):
        high = count()
        for i in range(len(self.img)):
            for j in range(len(self.img[i])):
                if self.img[i][j] > param.threshold.pixel:
                    high(i)
        if(high.max - high.min + 1 == len(self.img)):
            return self
        add = int( (len(self.img) - (high.max - high.min + 1)) / 2 )
        result = numpy.zeros((len(self.img), len(self.img[0])))
        for i in range(len(self.img)-add):
            for j in range(len(self.img[i])):
                result[i+add][j] = self.img[i][j]
        return image(result)

    def get_region(self, x, y):
        hight = count()
        width = count()
        hight.min = len(self.img) * x // param.threshold.split.height
        hight.max = len(self.img) * (x + 1) // param.threshold.split.height
        width.min = len(self.img[0]) * y // param.threshold.split.width
        width.max = len(self.img[0]) * (y + 1) // param.threshold.split.width
        result = numpy.zeros((hight.max - hight.min, width.max - width.min))
        for i in range(hight.min, hight.max):
            for j in range(width.min, width.max):
                result[i-hight.min][j-width.min] = self.img[i][j]
        return image(result)

    def get_density(self):
        result = 0.0
        for line in self.img:
            for pixel in line:
                result += pixel / 255
        return result

def get_absolute_density(array, more = 1):
    max_density = max(array)
    result = []
    for value in array:
#        result.append( 1.00 if((value / max_density)>=more)else (value / max_density) )
        result.append( value / max_density )
    return result

def get_visualise_density(array):
    result = []
    for idx in range(len(array)):
        for end in range(1, 1 + len(param.threshold.density)):
            if array[idx] <= sum(param.threshold.density[:end]):
                result.append("{}{}".format(idx+1, chr(96+end)))
                break
    return result

def get_density(array):
    img = image(array)
    img = img.clip_image(img.get_image_info())
    img = img.center_image()

    density = [
        img.get_region(0, 0).get_density(),
        img.get_region(0, 1).get_density(),
        img.get_region(1, 0).get_density(),
        img.get_region(1, 1).get_density(),
        img.get_region(2, 0).get_density(),
        img.get_region(2, 1).get_density()
    ]

    density = get_absolute_density(density)
    density = get_visualise_density(density)
    return density


from solver.solver import Solver
from model.baseline import Baseline

"""
    创建一个模型,
    训练这个模型,
    测试这个模型
"""

if __name__ == '__main__':
    print('C2JD Start.')
    model = Baseline()
    solver = Solver(model)
    solver.solve()
    solver.evaluate()
    print('C2JD End.')