from __future__ import absolute_import, division, print_function

import getdns

from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath
from OpenSSL import crypto

from danex import _dane

class TLSADomainNameTests(SynchronousTestCase):
    def test_tlsaDomainName(self):
        """
        L{_dane.tlsaDomainName} returns the port, proto and parent domain as
        labels of a new domain name string.
        """
        self.assertEqual(
            "_443._tcp.example.com",
            _dane.tlsaDomainName('example.com', 443, 'tcp')
        )

class GetdnsResponseErrorTests(SynchronousTestCase):
    def test_errorText(self):
        """
        L{_dane.GetdnsResponseError} has an C{errorText} attribute which is the name
        of the corresponding L{getdns} constant.
        """
        self.assertEqual(
            "GETDNS_RESPSTATUS_NO_NAME",
            _dane.GetdnsResponseError(getdns.GETDNS_RESPSTATUS_NO_NAME).errorText
        )

class TLSARecordTests(SynchronousTestCase):
    def test_matchesCertificateCertTrue(self):
        """
        """
        serverCertBytes = FilePath(__file__).sibling('example_cert.bin').open().read()
        serverCert = crypto.load_certificate(crypto.FILETYPE_ASN1, serverCertBytes)
        self.assertEqual(
            True,
            _dane.TLSARecord(
                payload=serverCertBytes,
                usage=0,
                selector=_dane.SELECTOR.CERT.value,
                matchingType=_dane.MATCHING_TYPE.FULL.value
            ).matchesCertificate(serverCert)
        )

    def test_matchesCertificateCertFalse(self):
        """
        """
        serverCertBytesOriginal = FilePath(__file__).sibling('example_cert.bin').open().read()
        serverCert = crypto.load_certificate(crypto.FILETYPE_ASN1, serverCertBytesOriginal)
        originalSerial = serverCert.get_serial_number()
        serverCert.set_serial_number(100)
        self.assertNotEqual(originalSerial, serverCert.get_serial_number())
        serverCertBytesNew = crypto.dump_certificate(crypto.FILETYPE_ASN1, serverCert)
        self.assertNotEqual(serverCertBytesOriginal, serverCertBytesNew)
        self.assertEqual(
            False,
            _dane.TLSARecord(
                payload=serverCertBytesNew,
                usage=0,
                selector=_dane.SELECTOR.CERT.value,
                matchingType=_dane.MATCHING_TYPE.FULL.value
            ).matchesCertificate(serverCert)
        )
    test_matchesCertificateCertFalse.skip = True

    def test_matchesCertificateSPKITrue(self):
        """
        """
        serverCertBytesOriginal = FilePath(__file__).sibling('example_cert.bin').open().read()
        serverCert = crypto.load_certificate(crypto.FILETYPE_ASN1, serverCertBytesOriginal)
        serverCert.set_serial_number(100)
        serverCertBytes = crypto.dump_certificate(crypto.FILETYPE_ASN1, serverCert)
        self.assertEqual(serverCertBytesOriginal, serverCertBytes)
#        import pdb; pdb.set_trace()
        self.assertEqual(
            False,
            _dane.TLSARecord(
                payload=serverCertBytes + b'xxx',
                usage=0,
                selector=_dane.SELECTOR.SPKI.value,
                matchingType=_dane.MATCHING_TYPE.FULL.value
            ).matchesCertificate(serverCert)
        )
    test_matchesCertificateSPKITrue.skip = True

class FakeGetdns(object):
    """
    An in memory fake of the getdns api for testing.
    """
    def __init__(self, generalResult=None):
        self._generalResult = generalResult

        for k, v in getdns.__dict__.items():
            if k.startswith('GETDNS_'):
                setattr(self, k, v)

    def context_create(self):
        """
        """

    def general(self, context, name, request_type, extensions):
        """
        """
        return self._generalResult

class TLSATests(SynchronousTestCase):
    def test_tlsaCert(self):
        """
        L{_dane.lookup_tlsa_records} returns a L{_dane.TLSARecord} instance if
        the domain name exists and a verified record is found and the record
        selector type is CERT.
        """
        fakeGetdns = FakeGetdns(
            generalResult=createResults(status=getdns.GETDNS_RESPSTATUS_GOOD,
                                        selector=_dane.SELECTOR.CERT.value,
                                        certificate_association_data=b'FOOBAR'))
        _, (res,) = _dane.lookup_tlsa_records(
            'example.com', 443, 'tcp', getdns=fakeGetdns)
        self.assertEqual(
            (_dane.SELECTOR.CERT, b'FOOBAR'),
            (res.selector, res.payload)
        )

    def test_tlsaSPKI(self):
        """
        L{_dane.lookup_tlsa_records} returns a L{_dane.TLSARecord} instance if
        the domain name exists and a verfied record is found and the record
        selector type is SPKI.
        """
        fakeGetdns = FakeGetdns(
            generalResult=createResults(status=getdns.GETDNS_RESPSTATUS_GOOD,
                                        selector=_dane.SELECTOR.SPKI.value,
                                        certificate_association_data=b'FOOBAR'))
        _, (res,) = _dane.lookup_tlsa_records(
            'example.com', 443, 'tcp', getdns=fakeGetdns)
        self.assertEqual(
            (_dane.SELECTOR.SPKI, b'FOOBAR'),
            (res.selector, res.payload)
        )

    def test_tlsaNoname(self):
        """
        L{_dane.lookup_tlsa_records} raises LookupError if the domain name does
        not exist.
        """
        e = self.assertRaises(
            _dane.GetdnsResponseError,
            _dane.lookup_tlsa_records, 'example.com', 443, 'tcp',
            getdns=FakeGetdns(
                generalResult=createResults(
                    status=getdns.GETDNS_RESPSTATUS_NO_NAME
                )
            )
        )
        self.assertEqual(
            getdns.GETDNS_RESPSTATUS_NO_NAME,
            e.errorCode
        )

def createResults(status=getdns.GETDNS_RESPSTATUS_GOOD,
                  selector=None,
                  certificate_association_data=b"",):
    return {'answer_type': 800,
            'canonical_name': '_443._tcp.getdnsapi.org.',
            'just_address_answers': [],
            # 'replies_full': [<read-only buffer ptr 0x7fe2e0029e80, size 636 at 0x7fe2e4e58fb0>],
            'replies_tree': [{'answer': [{'class': 1,
                                          'name': '_443._tcp.getdnsapi.org.',
                                          'rdata': {
                                              'certificate_association_data': certificate_association_data,
                                              'certificate_usage': 3,
                                              'matching_type': 1,
                                              # 'rdata_raw': "",
                                              'selector': selector
                                          },
                                          # 'ttl': 450,
                                          'type': 52,
                                         # {'class': 1,
                                         #  'name': '_443._tcp.getdnsapi.org.',
                                         #  'rdata': {'algorithm': 7,
                                         #            'key_tag': 49262,
                                         #            'labels': 4,
                                         #            'original_ttl': 450,
                                         #            'rdata_raw': <read-only buffer ptr 0x7fe2e0261b70, size 161 at 0x7fe2e4e60130>,
                                         #            'signature': <read-only buffer ptr 0x7fe2e0254c40, size 128 at 0x7fe2e4e60170>,
                                         #            'signature_expiration': 1399325172,
                                         #            'signature_inception': 1398100703,
                                         #            'signers_name': 'getdnsapi.org.',
                                         #            'type_covered': 52},
                                         #  'ttl': 450,
                                         #  'type': 46
                                      }
                                     ],
                               'answer_type': 800,
                              # 'authority': [{'class': 1,
                              #                'name': 'getdnsapi.org.',
                              #                'rdata': {'nsdname': 'ns.secret-wg.org.',
                              #                          'rdata_raw': 'ns.secret-wg.org.'},
                              #                'ttl': 450,
                              #                'type': 2},
                              #               {'class': 1,
                              #                'name': 'getdnsapi.org.',
                              #                'rdata': {'nsdname': 'mcvax.nlnetlabs.nl.',
                              #                          'rdata_raw': 'mcvax.nlnetlabs.nl.'},
                              #                'ttl': 450,
                              #                'type': 2},
                              #               {'class': 1,
                              #                'name': 'getdnsapi.org.',
                              #                'rdata': {'nsdname': 'open.nlnetlabs.nl.',
                              #                          'rdata_raw': 'open.nlnetlabs.nl.'},
                              #                'ttl': 450,
                              #                'type': 2},
                              #               {'class': 1,
                              #                'name': 'getdnsapi.org.',
                              #                'rdata': {'algorithm': 7,
                              #                          'key_tag': 49262,
                              #                          'labels': 2,
                              #                          'original_ttl': 450,
                              #                          'rdata_raw': <read-only buffer ptr 0x7fe2e0261f90, size 161 at 0x7fe2e4e601f0>,
                              #                          'signature': <read-only buffer ptr 0x7fe2e0028120, size 128 at 0x7fe2e4e60230>,
                              #                          'signature_expiration': 1399278072,
                              #                          'signature_inception': 1398093503,
                              #                          'signers_name': 'getdnsapi.org.',
                              #                          'type_covered': 2},
                              #                'ttl': 450,
                              #                'type': 46}],
                              'canonical_name': '_443._tcp.getdnsapi.org.',
                              'dnssec_status': 400,
                              'header': {'aa': 0,
                                         'ad': 1,
                                         'ancount': 2,
                                         'arcount': 0,
                                         'cd': 0,
                                         'id': 0,
                                         'nscount': 4,
                                         'opcode': 0,
                                         'qdcount': 1,
                                         'qr': 1,
                                         'ra': 1,
                                         'rcode': 0,
                                         'rd': 1,
                                         'tc': 0,
                                         'z': 0},
                              'question': {'qclass': 1,
                                           'qname': '_443._tcp.getdnsapi.org.',
                                           'qtype': 52}}],
            'status': status}


import requests
from bs4 import BeautifulSoup

from movexplo.constants import TOFIND, URL
from movexplo.utils import (duration_to_int, get_logger, remove_special_characters)

logger = get_logger("scrapper")

def get_soup_from_url(url):
    result = requests.get(url)
    soup = BeautifulSoup(result.text, 'html.parser')
    return soup

def get_link_from_file(file_info):
    url = URL.format(remove_special_characters(file_info["file_name"].replace(" ", "%20").lower()))
    logger.info("Searching {}".format(url))
    soup = get_soup_from_url(url)
    try:
        return get_link_from_soup(soup)
    except (IndexError, AttributeError) as e:
        logger.warning("Search failed for {} at url {}".format(file_info["file_name"], url))
        return TOFIND

def get_link_from_soup(soup):
    item = soup.find("div", "ProductListItem__TextContainer-sc-1ci68b-8 kKuZab")
    links = item.find_all("a", href=True)
    for link in links:
        if link["href"] is not None:
            return link["href"]

def get_image_from_soup(soup):
    item = soup.find("img", "pvi-hero-poster")
    return item["src"]

def get_director_from_soup(soup):
    item = soup.find("span", itemprop="name")
    return item.text

def get_date_from_soup(soup):
    item = soup.find("time")
    if item:
        return item["datetime"]

def get_genres_from_soup(soup):
    items = soup.find_all("span", itemprop="genre")
    return [item.text for item in items]

def get_duration_from_soup(soup):
    items = soup.find_all("li", "pvi-productDetails-item")
    for item in items:
        if item.find("meta", itemprop="duration"):
            return duration_to_int(item.text.replace("\n", "").replace("\t", ""))

def get_name_from_soup(soup):
    item = soup.find("h1", "pvi-product-title")
    return item["title"]

def get_original_name_from_soup(soup):
    item = soup.find("h2", "pvi-product-originaltitle")
    if item:
        return item.text

FIELD_TO_METHOD = {
    "image": get_image_from_soup,
    "director": get_director_from_soup,
    "date": get_date_from_soup,
    "genres": get_genres_from_soup,
    "duration": get_duration_from_soup,
    "name": get_name_from_soup,
    "original_name": get_original_name_from_soup,
}


import typing

from PySide6.QtGui import QDropEvent, QPixmap
from PySide6.QtWidgets import QComboBox, QTableWidgetItem

from foundry.game.gfx.objects.world_map.sprite import MAP_ITEM_SPRITES, MAP_OBJ_SPRITES
from foundry.game.level.LevelRef import LevelRef
from scribe.gui.commands import ChangeSpriteIndex, SetSpriteItem, SetSpriteType
from scribe.gui.tool_window.table_widget import (
    DialogDelegate,
    DropdownDelegate,
    TableWidget,
)
from smb3parse.constants import MAPITEM_NAMES, MAPOBJ_NAMES
from smb3parse.levels import FIRST_VALID_ROW

class SpriteList(TableWidget):
    def __init__(self, parent, level_ref: LevelRef):
        super(SpriteList, self).__init__(parent, level_ref)

        self.cellChanged.connect(self._save_sprite)

        self.set_headers(["Sprite Type", "Item Type", "Map Position"])

        self.setItemDelegateForColumn(
            0,
            DropdownDelegate(self, list(MAPOBJ_NAMES.values()), list(MAP_OBJ_SPRITES.values())),
        )
        self.setItemDelegateForColumn(
            1,
            DropdownDelegate(self, list(MAPITEM_NAMES.values()), list(MAP_ITEM_SPRITES.values())),
        )
        self.setItemDelegateForColumn(
            2,
            DialogDelegate(
                self,
                "No can do",
                "You can move sprites by dragging them around in the WorldView. "
                "Make sure they are shown in the View Menu.",
            ),
        )

        self.update_content()

    def dropEvent(self, event: QDropEvent) -> None:
        source_index = self.selectedIndexes()[0].row()
        target_index = self.indexAt(event.position().toPoint()).row()

        self.undo_stack.push(ChangeSpriteIndex(self.world, source_index, target_index))

        self.update_content()

    def _save_sprite(self, row: int, column: int):
        if column == 2:
            return

        sprite = self.world.sprites[row]

        widget = typing.cast(QComboBox, self.cellWidget(row, column))
        data = widget.currentText()

        if sprite.data.y < FIRST_VALID_ROW:
            sprite.data.y = FIRST_VALID_ROW

        if column == 0:
            self.undo_stack.push(SetSpriteType(sprite.data, list(MAPOBJ_NAMES.values()).index(data)))
        elif column == 1:
            self.undo_stack.push(SetSpriteItem(sprite.data, list(MAPITEM_NAMES.values()).index(data)))
        else:
            return

        self.world.data_changed.emit()

    def update_content(self):
        self.setRowCount(len(self.world.sprites))

        self.blockSignals(True)

        for index, sprite in enumerate(self.world.sprites):
            sprite_type = QTableWidgetItem(MAPOBJ_NAMES[sprite.data.type])
            sprite_type.setIcon(QPixmap(MAP_OBJ_SPRITES[sprite.data.type].scaled(self.iconSize())))

            item_type = QTableWidgetItem(MAPITEM_NAMES[sprite.data.item])
            item_type.setIcon(QPixmap(MAP_ITEM_SPRITES[sprite.data.item].scaled(self.iconSize())))
            pos = QTableWidgetItem(f"Screen {sprite.data.screen}: x={sprite.data.x}, y={sprite.data.y}")

            self._set_map_tile_as_icon(pos, sprite.get_position())

            self.setItem(index, 0, sprite_type)
            self.setItem(index, 1, item_type)
            self.setItem(index, 2, pos)

        self.blockSignals(False)


import json

# status, stations, started, nextrun, train_nr, finished, date
# arrival, departure, station_id, delay, delay_cause, scraped

def print_station(s):
    name = stations[str(s["station_id"])]["name"].ljust(24)
    dep = "     "
    arr = "     "
    if "departure" in s:
        h = s['departure']//60
        m = s['departure']%60
        dep = f"{h:02}:{m:02}"
    if "arrival" in s:
        h = s['arrival']//60
        m = s['arrival']%60
        arr = f"{h:02}:{m:02}"
    delay = ""
    cause = ""
    if "delay" in s:
        delay = s["delay"]
    if "delay_cause" in s:
        cause = s["delay_cause"]
    print("-", name, arr, dep, delay, cause)

def print_train(t):
    print("")
    print(t['train_nr'], t['status'])
    print(t['date'], t['started'], t['finished'], t['nextrun'])
    for s in t['stations']:
        print_station(s)

with open('data/zugfinder_example_stations.json') as myfile:
    stations = json.load(myfile)

with open('data/zugfinder_example_trains.json') as myfile:
    trains = json.load(myfile)
    for i in trains:
        print_train(trains[i])


# Data base bridge
from database_bridge import Db_bridge
#API
from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import os

app = Flask(__name__)
CORS(app)
db = None;

@app.route('/api/')
def hello_world_api():
    return 'Backend up!!'

#Get all the workers
@app.route('/api/workers/all')
def get_workers():
    workers = db.get_workers()
    print(workers)
    return jsonify(workers)

@app.route('/api/workers/add', methods=['POST'])
def add_worker():
    return "To do ..."

#Save a rotine to a worker
@app.route('/api/routines/add', methods=['POST'])
def add_routine():
    return "To do ..."

@app.route('/api/test/workers')
def test_workers():
    db.add_workers('Koko', 'Leonardo','Ortega','koko@loscantoresdechipuco.tocapues')
    db.add_workers('Coronel', 'Julian','Coronel','Coronel@loscantoresdechipuco.tocapues')
    db.add_workers('Karval', 'Carlos','Valencia','Karval@loscantoresdechipuco.tocapues')

    return get_workers()

@app.route('/')
def hello_world_web():
    return 'Yo, sup bro'

@app.route('/api/temp/')
def temp():
    return jsonify(data)

if __name__ == '__main__':
    dev_state, state = None,None

    try:
        state = os.environ['ENVSTATE']
    except:

        state = os.environ['ENVSTATE'] = 'DEV'

    if state == 'PROD':
        print("Production ENV")
        dev_state = False
    elif state == 'DEV':
        print("Deveploment ENV")
        dev_state = True
    else:
        raise Exception("ENVSTATE is unknowing, STATE -> {}".format(state))

    try:
        db = Db_bridge(dev_state)
        app.run(host='0.0.0.0', port=5000, debug=dev_state)
    except KeyboardInterrupt:
        print('Closing server....')


import pytest
import brownie

DAY = 86400  # seconds

@pytest.fixture
def vault(gov, token, Vault):
    # NOTE: Because the fixture has tokens in it already
    yield gov.deploy(Vault, token, gov, gov, "", "")

@pytest.fixture
def strategy(gov, vault, TestStrategy):
    # NOTE: Because the fixture has tokens in it already
    yield gov.deploy(TestStrategy, vault)

def test_losses(chain, vault, strategy, gov, token):
    vault.addStrategy(strategy, 1000, 1000, 0, {"from": gov})
    token.approve(vault, 500, {"from": gov})
    vault.deposit(500, {"from": gov})

    chain.sleep(DAY // 10)
    strategy.harvest({"from": gov})
    assert token.balanceOf(strategy) == 500

    # First loss
    chain.sleep(DAY // 10)
    strategy._takeFunds(100, {"from": gov})
    strategy.harvest({"from": gov})
    params = vault.strategies(strategy).dict()
    assert params["totalLoss"] == 100
    assert params["totalDebt"] == 400

    # Harder second loss
    chain.sleep(DAY // 10)
    strategy._takeFunds(300, {"from": gov})
    strategy.harvest({"from": gov})
    params = vault.strategies(strategy).dict()
    assert params["totalLoss"] == 400
    assert params["totalDebt"] == 100

    # Strike three
    chain.sleep(DAY // 10)
    assert token.balanceOf(strategy) == 100
    strategy._takeFunds(100, {"from": gov})
    assert token.balanceOf(strategy) == 0
    strategy.harvest({"from": gov})
    params = vault.strategies(strategy).dict()
    assert params["totalLoss"] == 500
    assert params["totalDebt"] == 0


'''
看看别人是怎么写代码的.
https://necromuralist.github.io/data_science/posts/predicting-cancer/
https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exist-in-a-list
'''
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import confusion_matrix, classification_report
import xgboost as xgb
import numpy as np
import math

def evaluate_predict(y_true, y_predict, model):

    print("=============" + model + "==============")
    # use confusion_matrix evaluate the classifier
    cm_res = confusion_matrix(y_true, y_predict)
    print("confusion_matrix\n", cm_res)

    # get classification report of the knn classification
    report = classification_report(y_true, y_predict)
    print("classification_report\n", report)

def forest_classifier(x_train, y_train, x_test, y_test):
    forest = RandomForestClassifier()
    forest.fit(x_train, y_train)
    y_predict = forest.predict(x_test)

    print("forest score is \n", forest.score(x_test, y_test))
    print("feature importance \n", forest.feature_importances_)
    evaluate_predict(y_test, y_predict, model = 'forest')

def tree_clf(x_train, y_train, x_test, y_test):
    clf = DecisionTreeClassifier()
    clf.fit(x_train, y_train)
    y_predict = clf.predict(x_test)

    print("tree clf is \n", clf.score(x_test, y_test))
    evaluate_predict(y_test, y_predict, model = 'tree clf')

    export_graphviz(clf, out_file = './data/clf.dot', feature_names = ['a', 'b', 'c', 'd'])

def svc_model(x_train, y_train, x_test, y_test):
    svc = SVC(kernel = 'linear')
    svc.fit(x_train, y_train)
    y_predict = svc.predict(x_test)

    evaluate_predict(y_test, y_predict, model = 'svc_model')

def knn_model(x_train, y_train, x_test, y_test):
    classifier = KNeighborsClassifier(n_neighbors = 3)
    classifier.fit(x_train, y_train)
    y_predict = classifier.predict(x_test)

    evaluate_predict(y_test, y_predict, model = 'knn_model')

def naive_bayes(x_train, y_train, x_test, y_test):
    bayes = MultinomialNB()
    bayes.fit(x_train, y_train)
    y_predict = bayes.predict(x_test)

    print("naive_bayes score is ", bayes.score(x_test, y_test))
    #your classifier is not predicting positives at all on the test data
    #Logistic Regression: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples
    evaluate_predict(y_test, y_predict, model = 'naive_bayes')

def SGDClassifier_model(x_train, y_train, x_test, y_test):
    sgd = SGDClassifier(penalty = "l2")
    sgd.fit(x_train, y_train)
    y_predict = sgd.predict(x_test)
    evaluate_predict(y_test, y_predict, model = 'SGDClassifier')

def load_iris_data():
    iris = load_iris()
    x = iris.data[:100]
    y = iris.target[:100]
    # x ndarry type, four features: sepal length, sepal width, petal length, petal width:
    # y ndarry type
    #print(iris.DESCR, x.shape, type(x), y.shape, type(y))
    # 分隔数据
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 1, shuffle = True)
    return x_train, x_test, y_train, y_test

def log_reg(y_hat, y):
    p = 1.0 / (1.0 + np.exp(-y_hat))
    g = p - y.get_label()
    h = p * (1.0-p)
    return g, h

def err_rate(y_hat, y):
    return 'error', float(sum(y.get_label() != (y_hat > 0.5))) / len(y_hat)

def xgboost(x_train, y_train, x_test, y_test):
    data_train = xgb.DMatrix(x_train, label = y_train)
    data_test = xgb.DMatrix(x_test, label = y_test) #y_train[y_train == 3] = 0 标签从0开始。
    # 设置参数
    watchlist = [(data_test, 'eval'), (data_train, 'train')]
    n_round = 5
    param = {'max_depth': 2, 'eta': 1, 'silent': 1, 'objective': 'multi:softmax', 'num_class': 3} #
    bst = xgb.train(param, data_train, num_boost_round=n_round, evals=watchlist)
    #param = {'max_depth': 4, 'eta': 1, 'silent': 1, 'objective': 'reg:logistic'} #二分类可以自己定义函数
    #bst = xgb.train(param, data_train, num_boost_round=n_round, evals=watchlist, obj = log_reg, feval = err_rate)
    '''
    'eta' learning_rate: Step size shrinkage used in update to prevents overfitting.
    'objective' reg or classification function，建立一颗树时需要指定一阶导与二阶导，与xgb.train中的obj有何不同
    'reg:logistic' 输出0到1，logitraw输出负无穷到正无穷
    multi:softmax', 多分类问题用softmax ，分为三类
    '''
    # 计算错误率
    y_hat = bst.predict(data_test)
    print(y_hat, '\n\n',y_test)
    error = float(np.sum(y_test.reshape(1, -1) != y_test))/len(y_hat)
    #error = 1- float(np.sum((y_hat > 0.5) == y_test))/len(y_hat)
    print("错误率是 ", error)

def BGDClf_model(x_train, y_train, x_test, y_test):
    '''
    批量梯度下降算法实现
    '''
    alpha = 0.001
    lamda = 0.0001        #1e-4 > lambda
    is_detailed = True
    train_times = 100
    M, N = x_train.shape  #M samples N features
    theta = np.zeros(N).reshape(-1, 1) #N * 1
    for t in range(train_times):
        loss = np.dot(x_train, theta) -y_train #M * 1 = M * 1 - M * 1，计算每个样本的损失
        theta -= alpha * np.dot(x_train.T, loss) + lamda * theta # np.dot(N * M, M * 1) = N * 1，每个样本的损失乘以每一个theta的系数加和(矩阵乘法过程中有加和)后更新theta
        if((t%10 == 0) and (is_detailed)):
            print("t is: ", t , "mean loss is: ", np.mean(loss, axis = 0), "updated theta: ", theta.tolist())
    return theta

def GDClf_model(x_train, y_train, x_test, y_test):
    '''
    随机梯度下降
    '''
    alpha = 0.001
    lamda = 0.0001        #1e-4 > lambda
    is_detailed = True
    train_times = 100
    M, N = x_train.shape  #M samples N features
    theta = np.zeros(N)
    for t in range(train_times):
        for j in range(M):  #use one sample to update all theta 随机梯度下降
            loss = np.dot(x_train[j, :],theta) - y_train[j]
            theta -= alpha * loss * x_train[j, :] + lamda * theta
        if((t%10 == 0) and (is_detailed)):
            print("times = %d  loss = %f" %(t, loss), "updated theta is", theta)
    return theta

def sigmoid(x, theta):
    '''
    计算 x * theat，带入sigmoid函数
    '''
    exp = np.exp(-np.dot(x, theta))
    pow = np.array(list(map(lambda x : x ** (-1), exp)))
    return pow

def lrGD_model(x_train, y_train, x_test, y_test):
    '''
    load_iris_data()中数据分三类，前两类线性可分，所以可以拿来实验。
    '''
    alpha = 0.001
    lamda = 0.0001        #1e-4 > lambda
    is_detailed = True
    train_times = 1000
    M, N = x_train.shape  #M samples N features
    theta = np.zeros(N).reshape(-1, 1) #N * 1
    for t in range(train_times):
        y_hat = sigmoid(x_train, theta).reshape(-1, 1)
        loss = y_hat -y_train.reshape(-1, 1) #M * 1 = M * 1 - M * 1，计算每个样本的损失
        error = float(np.sum((y_hat > 0.5) != y_train.reshape(-1, 1))) / M #
        theta -= alpha * np.dot(x_train.T, loss) + lamda * theta # np.dot(N * M, M * 1) = N * 1，每个样本的损失乘以每一个theta的系数加和(矩阵乘法过程中有加和)后更新theta
        if((t%10 == 0) and (is_detailed)):
            print("t is: ", t , "mean loss is: ", error, "updated theta: ", theta.tolist())
    return theta

if __name__ == "__main__":
    x_train, x_test, y_train, y_test = load_iris_data()
    '''
    knn_model(x_train, y_train, x_test, y_test)
    svc_model(x_train, y_train, x_test, y_test)
    naive_bayes(x_train, y_train, x_test, y_test)
    SGDClassifier_model(x_train, y_train, x_test, y_test)
    tree_clf(x_train, y_train, x_test, y_test)
    forest_classifier(x_train, y_train, x_test, y_test)
    '''
    lrGD_model(x_train, y_train, x_test, y_test)

    #xgboost(x_train, y_train, x_test, y_test)


from django.db import models
from django.contrib.auth.models import AbstractUser
from apps.users.validators import validate_file_extension

# Create your models here.

class User(AbstractUser):
    profile_image = models.FileField(
        upload_to='profile_image/',
        validators=[validate_file_extension]
    )
    GENDERS = (
        ('Мужчина', 'Мужчина'),
        ('Женщина', 'Женщина'),
        ('Другое', 'Другое'),
    )
    gender = models.CharField(
        choices=GENDERS,
        default='Другое',
        max_length=20
    )
    phone_number = models.CharField(
        max_length=25
    )
    live_in = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )
    from_in = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )
    status = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = "Пользователь"
        verbose_name_plural = "Пользователи"

class Followers(models.Model):
    to_user = models.ForeignKey(
        User,
        related_name='followers',
        on_delete=models.CASCADE
    )
    from_user = models.ForeignKey(
        User,
        related_name='followings',
        on_delete=models.CASCADE
    )


from PIL import Image, ImageSequence
from math import floor, fabs
import sys

def transform_image(original_img, crop_w, crop_h):
    img_w, img_h = (original_img.size[0], original_img.size[1])
    n_frames = getattr(original_img, 'n_frames', 1)

    def transform_frame(frame):

        if crop_w is None:
            if crop_h == img_h:
                return frame
            new_w = floor(img_w * crop_h / img_h)
            new_h = crop_h
            return frame.resize((new_w, new_h))

        if crop_w == img_w and crop_h == img_h:
            return frame

        w_diff = fabs(crop_w - img_w)
        h_diff = fabs(crop_h - img_h)
        enlarge_image = True if crop_w > img_w or crop_h > img_h else False
        shrink_image = True if crop_w < img_w or crop_h < img_h else False

        if enlarge_image is True:
            new_w = floor(crop_h * img_w /
                          img_h) if h_diff > w_diff else crop_w
            new_h = floor(crop_w * img_h /
                          img_w) if h_diff < w_diff else crop_h

        if shrink_image is True:
            new_w = crop_w if h_diff > w_diff else floor(
                crop_h * img_w / img_h)
            new_h = crop_h if h_diff < w_diff else floor(
                crop_w * img_h / img_w)

        left = (new_w - crop_w) // 2
        right = left + crop_w
        top = (new_h - crop_h) // 2
        bottom = top + crop_h

        return frame.resize((new_w, new_h)).crop((left, top, right, bottom))

    if n_frames == 1:
        return transform_frame(original_img)

    else:
        frames = []
        for frame in ImageSequence.Iterator(original_img):
            frames.append(transform_frame(frame))
        return frames

def save_new_gif(new_frames, old_gif_information, new_path):
    new_frames[0].save(new_path,
                       save_all=True,
                       append_images=new_frames[1:],
                       duration=old_gif_information['duration'],
                       loop=old_gif_information['loop'],
                       background=old_gif_information['background'],
                       extension=old_gif_information['extension'],
                       transparency=old_gif_information['transparency'])

image_path = sys.argv[1]
image = Image.open(image_path)
extension = (image.format).lower()
file_name = image.fp.name

if image.size[0] > 500 or image.size[1] > 500:
    if extension != "gif":
        image = image.resize((500, 500))

        if extension == "jpg":
            extension = "JPEG"

        image.save(file_name, extension)
    else:
        frames = transform_image(image, 500, 500)
        old_gif_information = {
            'loop': bool(image.info.get('loop', 1)),
            'duration': image.info.get('duration', 40),
            'background': image.info.get('background', 223),
            'extension': image.info.get('extension', (b'NETSCAPE2.0')),
            'transparency': image.info.get('transparency', 223)
        }
        save_new_gif(frames, old_gif_information, image_path)


from core.apps.campaign.models import KollabCampaign
from django import forms

class DateInput(forms.DateInput):
    input_type = "date"

class CampaignCreateForm(forms.ModelForm):
    class Meta:
        model = KollabCampaign
        exclude = [
            "business_id",
            "is_active",
            "created_at",
            "updated_at",
            "thumbnail_url",
        ]
        widgets = {
            "start_date": DateInput(),
            "end_date": DateInput(),
        }


import serial
import datetime

def dec2deg(value):
   dec = value/100.00
   deg = int(dec)
   min = (dec - int(dec))/0.6
   position = deg + min
   position = "%.7f" %(position)
   return position

mapscale = 18
while True:
    port="/dev/ttyAMA0"
    ser=serial.Serial(port, baudrate=9600, timeout=0.5)
    gpsdata=ser.readline()
    gpsdata = gpsdata.decode("utf8",errors='replace')
    gpsdata = gpsdata.split(',')
    if "GNRMC" in gpsdata[0]:
        hrs, mi, sec = gpsdata[1][0:2], gpsdata[1][2:4], gpsdata[1][4:6]
        day, month, year = gpsdata[9][0:2], gpsdata[9][2:4], gpsdata[9][4:6]
        status= gpsdata[2]
        latitude= dec2deg(float(gpsdata[3]))
        oLat=gpsdata[4]
        longitude = dec2deg(float(gpsdata[5]))
        oLon=gpsdata[6]
        datetimeutc = "{}:{}:{} {}/{}/{}".format(hrs, mi, sec, day, month, year)
        datetimeutc = datetime.datetime.strptime(datetimeutc, '%H:%M:%S %d/%m/%y')
        mess0= "Estado {}".format(status)
        mess1 = "Datetime = {}".format(datetimeutc)
        print(mess1)
        mess2= "Latitud {} {}, Longitud {} {}".format(latitude, oLat, longitude, oLon)
        print(mess2)
    """
    if "GNGGA" in gpsdata[0]:
        lat = dec2deg(float(gpsdata[2]))
        lon = dec2deg(float(gpsdata[4]))
        alt = gpsdata[9]
        satcount = gpsdata[7]
        message1 = "Altitude={}, Satellites={}\n".format(alt, satcount)
        print(message1)
        """


import uuid
from flask import Flask
from flask import jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
cors = CORS(app)

@app.route("/")
def index():
    return "Hello, world!"

@app.route("/destinations")
@cross_origin()
def destinations():
    return jsonify([
        {
            "id": 1,
            "name": "example name1",
            "description": "example description",
            "bounds": {
                "north": 127.115048,
                "west": 37.508038,
                "south": 127.115248,
                "east": 37.508238
            }
        },

        {
            "id": 2,
            "name": "example name2",
            "description": "example description",
            "bounds": {
                "north": 127.115048,
                "west": 37.508038,
                "south": 127.115248,
                "east": 37.508238
            }
        }
    ])

@app.route("/destinations/<string:destination_id>")
@cross_origin()
def destination(destination_id):
    return jsonify(
        {
            "id": destination_id,
            "name": "example name",
            "description": "example description",
            "bounds": {
                "north": 127.115048,
                "west": 37.508038,
                "south": 127.115248,
                "east": 37.508238
            }
        }
    )

if __name__ == "__main__":
    app.run()


import flet as ft
from customcolorpicker import CustomColorPicker
from palettecolorpicker import PaletteColorPicker

def main(page: ft.Page):
    color_picker = CustomColorPicker(color="#c8df6f")

    d = ft.AlertDialog(content=color_picker)
    page.dialog = d

    def open_color_picker(e):
        d.open = True
        page.update()

    page.add(ft.IconButton(icon=ft.icons.BRUSH, on_click=open_color_picker))

ft.app(target=main)


# -*- coding: utf-8 -*-
# @Author  : Tian Hongrong
# @Time    : 2023/1/15 13:12
# @Function: input data pre-processing, binarize iris dataset

import numpy as np
from sklearn.datasets import load_iris

iris_data = load_iris()
input_data = iris_data.data
binary_data = input_data

"""
    use 2-bit representation to represent iris flower's 4 features, hence expand the original
    4 input to 8 input, then the input matrix is (data_num *  8) = (150 * 8)
"""

new_2bit_data = np.zeros(shape=(150 * 8))
SeLen = input_data[:, 0]
SeWidth = input_data[:, 1]
PeLen = input_data[:, 2]
PeWidth = input_data[:, 3]

def sort(feature):
    MAX = np.max(feature)
    MIN = np.min(feature)
    A = (MAX - MIN) / 4

    i = 0
    for i in range(150):
        if feature[i] < MIN + A and feature[i] >= MIN:
            feature[i] = 0
        elif feature[i] < MIN + 2 * A and feature[i] >= A + MIN:
            feature[i] = 1
        elif feature[i] < MIN + 3 * A and feature[i] >= 2 * A + MIN:
            feature[i] = 2
        elif feature[i] <= MAX and feature[i] >= 3 * A + MIN:
            feature[i] = 3
    return (feature)

SeLen_sort = sort(SeLen)
SeWidth_sort = sort(SeWidth)
PeLen_sort = sort(PeLen)
PeWidth_sort = sort(PeWidth)

def binaries(feature):
    b = np.zeros(shape=(150, 2))
    i = 0
    j = 0
    for i in range(150):
        for j in range(2):
            if feature[i] == 0:
                b[i][0] = -1
                b[i][1] = -1
            elif feature[i] == 1:
                b[i][0] = 1
                b[i][1] = -1
            elif feature[i] == 2:
                b[i][0] = -1
                b[i][1] = 1
            elif feature[i] == 3:
                b[i][0] = 1
                b[i][1] = 1
    return b

SeLen_binary = binaries(SeLen_sort)
SeWidth_binary = binaries(SeWidth_sort)
PeLen_binary = binaries(PeLen_sort)
PeWidth_binary = binaries(PeWidth_sort)

new_binary_data = np.c_[SeLen_binary, SeWidth_binary, PeLen_binary, PeWidth_binary]
np.save('binary_input_data.npy', new_binary_data)


# In this program we will use KNN to predict air quality index

# Part 1: Preprocessing

# Importing required packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Reading the data
df=pd.read_csv('Real_Combine.csv')
# Checking for null values
sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis')
# Since there are very few null values, we can drop them
df = df.dropna()
# Defining dependent and independent features
X = df.iloc[:, :-1]
y = df.iloc[:, -1]

# Seeing the feature importance using ExtraTreesRegressor
from sklearn.ensemble import ExtraTreesRegressor
import matplotlib.pyplot as plt
model = ExtraTreesRegressor()
model.fit(X,y)

# Plotting the importance using ExtraTreesRegressor
feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(5).plot(kind='barh')
plt.show()

# Splitting the data using train test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

# Part 2: Making K nearest neighbour regressor

# Importing the library
from sklearn.neighbors import KNeighborsRegressor

# Making the model with k value = 1
regressor=KNeighborsRegressor(n_neighbors=1)
# Fitting the data into the model
regressor.fit(X_train,y_train)

# Printing coeficient of determination of the training set
print("Coefficient of determination R^2 <-- on train set: {}".format(regressor.score(X_train, y_train)))
# Printing coeficient of determination of the testing set
print("Coefficient of determination R^2 <-- on train set: {}".format(regressor.score(X_test, y_test)))
# The value for training set is 1, for testing set is 0.54, the model is underfitting

# Printing cross validation score for regressor model with 5 fold cross validation
from sklearn.model_selection import cross_val_score
score=cross_val_score(regressor,X,y,cv=5)
score.mean()
# The mean cross validation score is 0.39

# Part 3: Prediction and evaluation

# Making the prediction
prediction=regressor.predict(X_test)

# Plotting the difference in the test value and the predicted value
sns.distplot(y_test-prediction)
# Very low kurtosis
# Plotting the predicted values against the test values
plt.scatter(y_test,prediction)
# More or less linear with some outliers

# Part 4: Hyper parameter tuning

# We start a loop to take n value from 1 to 40 and give the mean cross validation score with 10 folds
accuracy_rate = []
for i in range(1,40):
    knn = KNeighborsRegressor(n_neighbors=i)
    score=cross_val_score(knn,X,y,cv=10,scoring="neg_mean_squared_error")
    accuracy_rate.append(score.mean())

# Plotting the cross validation score against the n value to arruve at the best n value
plt.figure(figsize=(10,6))
plt.plot(range(1,40),accuracy_rate,color='blue', linestyle='dashed', marker='o',markerfacecolor='red', markersize=10)
plt.title('Accuracy Rate vs. K Value')
plt.xlabel('K')
# Accuracy rate is highest at n=1

# Part 6: Prediction and evalution using the tuned model

# Initiating the model with one neighbour
knn = KNeighborsRegressor(n_neighbors=1)
# Fitting the data onto the model
knn.fit(X_train,y_train)
# Making the predictions
predictions = knn.predict(X_test)

# Plotting the difference of the test value and the predicted values
sns.distplot(y_test-predictions)
# Extremely high kurtosis, this is good

# Plotting the predicted values against the test values
plt.scatter(y_test,predictions)
# Very linear with several outliers

# Printing the MAE, MSE and RMSE
from sklearn import metrics
print('MAE:', metrics.mean_absolute_error(y_test, prediction))
print('MSE:', metrics.mean_squared_error(y_test, prediction))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, prediction)))

# Part 6: Dumping the model in a pickle file for later deployment

# Importing pickkle
import pickle

# opening the file to dump the model
file = open('random_forest_regression_model', 'wb')
# dumping the tuned model into the file
pickle.dump(knn, file)


from __future__ import unicode_literals

import json
import unittest

from openformats.exceptions import ParseError
from openformats.formats.json import ChromeI18nHandlerV3
from openformats.strings import OpenString
from openformats.tests.formats.common import CommonFormatTestMixin
from openformats.tests.utils.strings import generate_random_string

class ChromeI18nV3TestCase(CommonFormatTestMixin, unittest.TestCase):
    HANDLER_CLASS = ChromeI18nHandlerV3
    TESTFILE_BASE = "openformats/tests/formats/chromev3/files"

    def setUp(self):
        super(ChromeI18nV3TestCase, self).setUp()
        self.random_string = generate_random_string()
        self.random_openstring = OpenString('a', self.random_string, order=0,
                                            developer_comment='')

    def test_simple(self):
        source_template = '{"a": {"message": "%s"}}'
        source = source_template % self.random_string
        template, stringset = self.handler.parse(source)
        compiled = self.handler.compile(template, [self.random_openstring])

        self.assertEqual(
            template,
            source_template % self.random_openstring.template_replacement
        )
        self.assertEqual(len(stringset), 1)
        self.assertEqual(stringset[0].__dict__,
                         self.random_openstring.__dict__)
        self.assertEqual(compiled, source)
        # Check developer comment is empty
        self.assertEqual(stringset[0].developer_comment, '')

    def test_invalid_json(self):
        with self.assertRaises(ParseError):
            self.handler.parse('{')
        with self.assertRaises(ParseError):
            self.handler.parse('3')
        self._test_parse_error('[]', u"Source file must be a JSON object")

    def test_double_key(self):
        self._test_parse_error('{"a": 1, "a": 2}',
                               u"Key 'a' appears multiple times (line 1)")

    def test_pluralized_string(self):
        source_template = '{"a": {"message": "{cnt, plural, %s}"}}'
        source = source_template % "one {horse} other {horses}"
        openstring = OpenString('a', {1: "horse", 5: "horses"},
                                pluralized=True, order=0, developer_comment='')
        template, stringset = self.handler.parse(source)
        compiled = self.handler.compile(template, [openstring])

        self.assertEqual(template,
                         source_template % openstring.template_replacement)
        self.assertEqual(len(stringset), 1)
        self.assertEqual(stringset[0].__dict__, openstring.__dict__)
        self.assertEqual(compiled, source)
        # Check developer comment is empty
        self.assertEqual(stringset[0].developer_comment, '')

    def test_remove_strings(self):
        """ Start with a source file with 3 strings and test the parsing
            process as always. Then compile it 3 times. Each time, as the
            stringset use 2 of the 3 original strings. Make sure the compiled
            file is a valid JSON string and that it only includes the strings
            that were in the stringset.
        """

        source_template = ('{"a": {"message": "%s"}, "b": {"message": "%s"},'
                           ' "c": {"message": "%s"}}')
        source = source_template % ("aaa", "bbb", "ccc")
        openstring_a = OpenString('a', "aaa", order=0, developer_comment='')
        openstring_b = OpenString('b', "bbb", order=1, developer_comment='')
        openstring_c = OpenString('c', "ccc", order=2, developer_comment='')
        template, stringset = self.handler.parse(source)

        self.assertEqual(template,
                         source_template % (openstring_a.template_replacement,
                                            openstring_b.template_replacement,
                                            openstring_c.template_replacement))
        self.assertEqual(len(stringset), 3)
        self.assertEqual([string.__dict__ for string in stringset],
                         [openstring_a.__dict__,
                          openstring_b.__dict__,
                          openstring_c.__dict__])

        # We will compare the dict versions of the strings because the way the
        # compiler leaves over some whitespaces when removing sections makes
        # the serialized versions a bit unpredictable

        # Remove first string
        compiled = self.handler.compile(template, [openstring_b, openstring_c])
        self.assertEqual(json.loads(compiled),
                         {'b': {'message': "bbb"}, 'c': {'message': "ccc"}})

        # Remove second string
        compiled = self.handler.compile(template, [openstring_a, openstring_c])
        self.assertEqual(json.loads(compiled),
                         {'a': {'message': "aaa"}, 'c': {'message': "ccc"}})

        # Remove third string
        compiled = self.handler.compile(template, [openstring_a, openstring_b])
        self.assertEqual(json.loads(compiled),
                         {'a': {'message': "aaa"}, 'b': {'message': "bbb"}})


from middleware.current_user.data import set_current_user
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
from rest_framework import permissions
from datetime import datetime, timedelta
from django.conf import settings
from application_layer.gateway import utils
from data_layer.session_data_layer import get_current_user, get_current_user_scope
import re
from entities import models

class AppTokenAuthentication(TokenAuthentication):
    keyword = 'Bearer'

    def authenticate_credentials(self, key):

        user_session = models.UserSession.objects.filter(token=key).first()

        if not user_session:
            raise exceptions.AuthenticationFailed('Invalid token')

        if user_session.expires < datetime.now():
            raise exceptions.AuthenticationFailed('Token has expired')

        user_session.expires = datetime.now() + timedelta(hours=1)
        user_session.save()

        set_current_user(user_session.user)

        return (user_session.user,
                user_session)

class IsAuthenticated(permissions.BasePermission):

    def url_regex_exact_matched (self, regex, string):
        reg = '^' + regex + '$'
        return True if re.match(reg, string) != None else False

    def has_permission(self, request, view):

        if not request.user and not request.auth:
            return False

        user_context = None

        inputs = utils.get_request_values(request)

        rms_context_allowed_urls = set([
            '/api/v1/auth/login/',
            '/api/v1/auth/current-user/',
            '/api/v1/auth/current-user/scope/'])

        if inputs['client_path'] in rms_context_allowed_urls:
            return True

        user_context = get_current_user(request.user, request.auth)

        if not user_context:
            return False

        if user_context.is_superuser:
            return True

        user_context_scope = get_current_user_scope(request.user, request.auth)

        if not user_context_scope:
            return False

        if user_context_scope['is_admin']:
            return True

        permissions = user_context_scope['service_routes']
        client_path = inputs.get('client_path')
        client_method = inputs.get('client_method')

        return len(
            list(filter(lambda item: self.url_regex_exact_matched(item['url'], client_path)
                                 and item['method'] == client_method,
                        permissions))
        ) > 0

class AllowAny(permissions.BasePermission):

    def has_permission(self, request, view):
        return True


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  8 00:07:14 2022

@author: Shahir, Faraz, Pratyush
Modified from: https://github.com/MCG-NJU/VideoMAE
"""

import os
import json

import numpy as np

from torch.utils.data import Dataset

import decord
from PIL import Image

class TinyVIRAT(Dataset):
    def __init__(
            self,
            root_dir,
            train=True,
            num_segments=1,
            new_length=1,
            new_step=1,
            temporal_jitter=False,
            verbose=False):

        super().__init__()

        self.root_dir = root_dir
        self.train = train
        self.num_segments = num_segments
        self.new_length = new_length
        self.new_step = new_step
        self.temporal_jitter = temporal_jitter
        self.verbose = verbose

        self.skip_length = self.new_length * self.new_step

        self.settings_fname = os.path.join(self.root_dir, "tiny_train.json" if train else "tiny_test.json")
        self.data_dir = os.path.join(self.root_dir, "videos", "train" if self.train else "test")

        self.clips, self.label_index_to_class_name = self._make_dataset()
        self.num_channels = 3

        self.rng = np.random.default_rng()

    def __getitem__(self, index):
        video_fname, label = self.clips[index]

        video_reader = decord.VideoReader(video_fname, num_threads=1)
        duration = len(video_reader)

        segment_indices, skip_offsets = self._sample_train_indices(duration)

        # t, PIL image (h, w, c)
        if self.verbose:
            print("Decoding", video_fname, duration, segment_indices, skip_offsets)
        try:
            images_per_frame = self._video_tsn_decord_batch_loader(
                video_reader, duration, segment_indices, skip_offsets)
        except:
            if self.verbose:
                print("Failed to decode", video_fname, duration, segment_indices, skip_offsets)
            raise

        return images_per_frame, label

    def __len__(self):
        return len(self.clips)

    def _make_dataset(self):
        with open(os.path.join(self.root_dir, "tiny_train.json")) as f:
            self.train_settings = json.load(f)
        with open(os.path.join(self.root_dir, "tiny_test.json")) as f:
            self.test_settings = json.load(f)

        all_tubes = self.train_settings["tubes"] + self.test_settings["tubes"]
        selected_set_tubes = self.train_settings["tubes"] if self.train else self.test_settings["tubes"]

        class_names = set()
        class_name_to_label_index = {}
        label_index_to_class_name = {}

        for tube in all_tubes:
            label = tube["label"]
            if label[0] not in class_names:
                class_names.add(label[0])
        class_names = sorted(class_names)

        counter = 0
        for label in class_names:
            class_name_to_label_index[label] = counter
            label_index_to_class_name[counter] = label
            counter = counter + 1
        clips = []
        for tube in selected_set_tubes:
            clip_path = os.path.join(self.data_dir, tube["path"])
            label = tube["label"][0]
            label = class_name_to_label_index[label]
            item = (clip_path, label)
            clips.append(item)

        return clips, label_index_to_class_name

    def _sample_train_indices(self, num_frames):
        average_duration = (
            num_frames - self.skip_length + 1) // self.num_segments
        if average_duration > 0:
            offsets = np.multiply(
                list(range(self.num_segments)), average_duration)
            offsets = offsets + \
                self.rng.integers(average_duration, size=self.num_segments)
        elif num_frames > max(self.num_segments, self.skip_length):
            offsets = np.sort(self.rng.integers(
                num_frames - self.skip_length + 1, size=self.num_segments))
        else:
            offsets = np.zeros((self.num_segments,))

        if self.temporal_jitter:
            skip_offsets = self.rng.integers(
                self.new_step, size=self.skip_length // self.new_step)
        else:
            skip_offsets = np.zeros(self.skip_length // self.new_step)

        return (offsets + 1).astype(int), skip_offsets.astype(int)

    def _video_tsn_decord_batch_loader(
            self,
            video_reader,
            duration,
            segment_indices,
            skip_offsets):

        frame_ids = []

        for segment_index in segment_indices:
            offset = int(segment_index)
            for i, _ in enumerate(range(0, self.skip_length, self.new_step)):
                if offset + skip_offsets[i] <= duration:
                    frame_id = offset + skip_offsets[i] - 1
                else:
                    frame_id = offset - 1
                frame_ids.append(frame_id)
                if offset + self.new_step < duration:
                    offset += self.new_step

        video_data = video_reader.get_batch(frame_ids).asnumpy()
        sampled_images = [Image.fromarray(video_data[i]).convert('RGB') for i in range(len(frame_ids))]

        return sampled_images


from rest_framework import viewsets
from wesPool.models import Ride,Requests
from .serializers import UserSerializer,RideSerializer,RequestsSerializer

from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, BasePermission, SAFE_METHODS, DjangoModelPermissionsOrAnonReadOnly
from django.contrib.auth.models import User
from rest_framework import filters
from rest_framework.permissions import AllowAny
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, OAuth2Authentication
from oauth2_provider.models import AccessToken
from rest_framework.decorators import action
from django.db.models import Q
from functools import reduce
from rest_framework import status
from rest_framework.response import Response
from wesPool.models import Ride, Requests

# Create your views here.
class PostReviewWritePermission(BasePermission):
    message = "Editing posts is restricted to the author only"

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        try:
            user = AccessToken.objects.get(token=request.data['access_token'])
            return True
        except:
            print('not logged in')
            return False
        return obj.host == user.user

class RideViewSet(viewsets.ModelViewSet):
    # queryset = Ride.objects.all()
    serializer_class = RideSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_fields = (
        'src',
        'dst',
        'date_time'
    )

    # def list(self, request):
    #     serializer = ItemSerializer(self.queryset, many=True)
    #     return Response(serializer.data)

    # def perform_create(self, serializer,request):
    #     # here you will send `created_by` in the `validated_data`
    #     user = AccessToken.objects.get(token=request.data['access_token'])
    #     serializer.save(
    #         date_time=self.request.data.date,
    #         src=self.request.data.src,
    #         dst=self.request.data.dst,
    #         seats=self.request.data.seats,
    #         price=self.request.data.price,
    #         uber=self.request.data.uber,
    #         host=user,
    #         group=self.request.data.group
    #     )
    def create(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        del request.data['host']
        del request.data['group']
        request.data['host'] = user.id
        request.data['group'] = [user.id]
        print(request.data['date_time'],'HI AGAIN')
        return super().create(request)

    def get_queryset(self, *args, **kwargs):
        print('hello?',self.request.query_params)
        user = AccessToken.objects.get(token=self.request.META['HTTP_AUTHORIZATION'][7:]).user
        if len(self.request.query_params)==0:
            data = Ride.objects.all()
            return data
        res = []
        res2 = []
        for key in self.request.query_params:
            try:
                if key == "host":
                    res = Ride.objects.filter(host=user)
                if key == "group":
                    res2 = Ride.objects.filter(group__in=[user.id]).exclude(host=user)
            except:
                print('oops')
        final = res | res2
        return final.distinct()

    def get(self, *args, **kwargs):
        print('wa')

    def update(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        ride = Ride.objects.get(id=self.request.data['id'])
        if len(self.request.data)==2:
            print('helllllllooooo')
            user = User.objects.get(id=self.request.data['req_by'])

            # new_lst = []
            for user_d in ride.group.all():
                if user==user_d:
                    return Response({},status.HTTP_204_NO_CONTENT)
            # new_lst.append(user)
            ride.group.add(user)
            # ride.save(update_fields=['group'])
            print(ride.get_fields())
            return Response({}, status.HTTP_204_NO_CONTENT)

        host = ride.host
        old_ride = ride.get_fields()
        if user == old_ride['host']:
            for key in old_ride:
                if key=='id' or key=='host':
                    continue
                if key=='group':
                    if old_ride['group']!=self.request.data['group']:
                        print('hi',old_ride['group'],self.request.data['group'])
                if self.request.data[key]!=old_ride[key]:
                    if key=="src":
                        ride.src = self.request.data[key]
                    elif key=="dst":
                        ride.dst = self.request.data[key]
                    elif key =="uber":
                        ride.uber = self.request.data[key]
                    elif key=="group":
                        ride.group = self.request.data[key]
                    elif key=="seats":
                        ride.seats = self.request.data[key]
                    elif key=="price":
                        ride.price = self.request.data[key]
                    elif key == 'date_time':
                        ride.date_time = self.request.data[key]
                    ride.save(update_fields=[key])
        else:
            print('NOOOO')

        return Response({}, status.HTTP_204_NO_CONTENT)

    def destroy(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        print(self.request.data,"????")
        ride = Ride.objects.get(id=self.request.data['id'])
        old_ride = ride.get_fields()
        if user == old_ride['host']:
            ride.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = User.objects.all()
    serializer_class = UserSerializer

class RequestsViewSet(viewsets.ModelViewSet, PostReviewWritePermission):
    # queryset = Requests.objects.all()
    serializer_class = RequestsSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_fields = (
        'req_by',
        'req_to'
    )

    def create(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        ride = Ride.objects.get(id=request.data['req_to'])
        del request.data['req_by']
        del request.data['req_to']
        request.data['req_by'] = user.id
        request.data['req_to'] = ride.id
        return super().create(request)

    def get_queryset(self, *args, **kwargs):
        # print('hello?',self.request)
        if len(self.request.query_params)==1:
            ride = Ride.objects.get(id=self.request.query_params['req_to'])
            print(Requests.objects.filter(req_to=ride))
            return Requests.objects.filter(req_to=ride)
        user = AccessToken.objects.get(token=self.request.META['HTTP_AUTHORIZATION'][7:]).user
        req = Requests.objects.filter(req_by=user.id)
        return req

    def destroy(self, request, *args, **kwargs):
        user = AccessToken.objects.get(token=request.META['HTTP_AUTHORIZATION'][7:]).user
        print(self.request.data,"????")
        req = Requests.objects.get(id=self.request.data['id'])
        req.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


import sys
from functools import reduce

def calc_trees(board, right, down):
    width = len(board[0])
    trees = 0
    col = right
    row = down

    while row < len(board):
        if board[row][col] == "#":
            trees += 1
        row += down
        col = (col + right) % width

    return trees

def main():
    board = []
    for line in sys.stdin:
        board.append(line.rstrip())

    slopes = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]

    slopes = list(map(lambda x: calc_trees(board, x[0], x[1]), slopes))
    total = reduce(lambda x, y: x * y, slopes)

    print(total)

if __name__ == "__main__":
    main()


from asgiref.sync import async_to_sync
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.generic.websocket import WebsocketConsumer
import json
from .models import *

state_reference = {"ready": "https://media.giphy.com/media/26BkNrGhy4DKnbD9u/giphy.gif",
                   "preparing": "https://media.giphy.com/media/9g1h1BQx9a55m/giphy.gif", "": "", None: ""}

class RoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        self.user = self.scope["user"]
        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        usernow = self.user
        room_id = self.room_group_name[5:]
        codeUser = CodingUser.objects.get(user=usernow)
        room_instance = Room.objects.get(id=room_id)
        room_owner = room_instance.room_owner
        user1 = room_instance.user1
        user2 = room_instance.user2
        user3 = room_instance.user3
        user4 = room_instance.user4
        if room_instance != None:
            if user2 == None:
                url2 = ""
                state2 = ""
            else:
                url2 = user2.picture.url
                state2 = room_instance.user2_state
            if user3 == None:
                url3 = ""
                state3 = ""
            else:
                url3 = user3.picture.url
                state3 = room_instance.user3_state
            if user4 == None:
                url4 = ""
                state4 = ""
            else:
                url4 = user4.picture.url
                state4 = room_instance.user4_state
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'disconnection_update': "true",
                    'user1_url': user1.picture.url,
                    'user2_url': url2,
                    'user3_url': url3,
                    'user4_url': url4,
                    'user1_status': room_instance.user1_state,
                    'user2_status': state2,
                    'user3_status': state3,
                    'user4_status': state4
                }
            )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        if text_data_json.get("userstatus"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            position = ""
            new_status = ""
            gamestart = "no"
            if room_instance.user4 == codeUser:
                position = 'user4'
                if room_instance.user4_state == 'preparing':
                    room_instance.user4_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user4_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user3 == codeUser:
                position = 'user3'
                if room_instance.user3_state == 'preparing':
                    room_instance.user3_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user3_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user2 == codeUser:
                position = 'user2'
                if room_instance.user2_state == 'preparing':
                    room_instance.user2_state = 'ready'
                    new_status = 'ready'
                else:
                    room_instance.user2_state = 'preparing'
                    new_status = 'preparing'
            if room_instance.user1 == codeUser:
                position = 'user1'
                if room_instance.user1_state == 'preparing':
                    room_instance.user1_state = 'ready'
                    new_status = 'ready'
                    gamestart = 'yes'
                else:
                    room_instance.user1_state = 'preparing'
                    new_status = 'preparing'
            room_instance.save()
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'position': position,
                    'new_status': new_status,
                    'gamestart': gamestart,
                    'room_id': room_id
                }
            )

        if text_data_json.get("newarrival"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            position = ""
            user_url = "/codewar" + codeUser.picture.url
            user_status = 'preparing'
            if room_instance.user1 == codeUser:
                position = 'user1'
            if room_instance.user2 == codeUser:
                position = 'user2'
            if room_instance.user3 == codeUser:
                position = 'user3'
            if room_instance.user4 == codeUser:
                position = 'user4'
                # Send message to room group

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'position': position,
                    'url': user_url,
                    'status': user_status,
                    'newarrival': 'newarrival'
                }
            )
        if text_data_json.get("change"):
            change = text_data_json['change']
            room_id = text_data_json['room_id']

            usernow = self.user

            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            message = 'nochange'
            initial = ''

            if change == "user2":
                if room_instance.user2 != None:
                    message = "nochange"
                elif room_instance.user3 == codeUser:
                    if room_instance.user3_state == "preparing":
                        message = 'change'
                        initial = 'user3'
                elif room_instance.user4 == codeUser:
                    if room_instance.user4_state == "preparing":
                        message = 'change'
                        initial = 'user4'
            if change == "user3":
                if room_instance.user3 != None:
                    message = "nochange"
                elif room_instance.user2 == codeUser:
                    if room_instance.user2_state == "preparing":
                        message = 'change'
                        initial = 'user2'
                elif room_instance.user4 == codeUser:
                    if room_instance.user4_state == "preparing":
                        message = 'change'
                        initial = 'user4'
            if change == "user4":
                if room_instance.user4 != None:
                    message = "nochange"
                elif room_instance.user3 == codeUser:
                    if room_instance.user3_state == "preparing":
                        message = 'change'
                        initial = 'user3'
                elif room_instance.user2 == codeUser:
                    if room_instance.user2_state == "preparing":
                        message = 'change'
                        initial = 'user2'
            # Send message to room group
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message,
                    'initial': initial,
                    'modify': change,
                    'room_id': room_id
                }
            )
        if text_data_json.get("exit"):
            usernow = self.user
            room_id = text_data_json['room_id']
            codeUser = CodingUser.objects.get(user=usernow)
            room_instance = Room.objects.get(id=room_id)
            room_owner = room_instance.room_owner
            user_url = codeUser.picture.url
            exit_user = ""
            adjusted_user = ""
            if room_owner == codeUser:
                if room_instance.user2 != None:
                    exit_user = "user1"
                    adjusted_user = "user2"
                elif room_instance.user3 != None:
                    third_user = room_instance.user3
                    room_instance.room_owner = third_user
                    room_instance.user1 = third_user
                    room_instance.user1_state = room_instance.user3_state
                    room_instance.user3 = None
                    room_instance.user3_state = None
                    room_instance.save()
                    exit_user = "user1"
                    adjusted_user = "user3"
                elif room_instance.user4 != None:
                    fourth_user = room_instance.user4
                    room_instance.room_owner = fourth_user
                    room_instance.user1 = fourth_user
                    room_instance.user1_state = room_instance.user4_state
                    room_instance.user4 = None
                    room_instance.user4_state = None
                    room_instance.save()
                    exit_user = "user1"
                    adjusted_user = "user4"
                else:
                    room_instance.delete()
                    # Send message to room group
            if room_instance.user2 == codeUser:
                room_instance.user2 = None
                room_instance.user2_state = ""
                exit_user = "user2"
                adjusted_user = "nouser"
            if room_instance.user3 == codeUser:
                room_instance.user3 = None
                room_instance.user3_state = ""
                exit_user = "user3"
                adjusted_user = "nouser"
            if room_instance.user4 == codeUser:
                room_instance.user4 = None
                room_instance.user4_state = ""
                exit_user = "user4"
                adjusted_user = "nouser"

            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'exit_user': exit_user,
                    'adjusted_user': adjusted_user

                }
            )
        if text_data_json.get("room_acces_symbol"):
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'room_acces_symbol': text_data_json.get("room_acces_symbol")
                }
            )

    # Receive message from room group
    async def chat_message(self, event):
        if event.get('new_status') != None:
            position = event['position']
            new_status = event['new_status']
            room_id = event["room_id"]
            room_instance = Room.objects.get(id=room_id)
            user1_name = room_instance.user1.user.username
            user2_name = ""
            user3_name = ""
            user4_name = ""
            if room_instance.user2:
                user2_name = room_instance.user2.user.username
            if room_instance.user3:
                user3_name = room_instance.user3.user.username
            if room_instance.user4:
                user4_name = room_instance.user4.user.username
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'position': position,
                'new_status': new_status,
                "new_status_url": state_reference[new_status],
                'gamestart': event['gamestart'],
                "user1_username": user1_name,
                "user2_username": user2_name,
                "user3_username": user3_name,
                "user4_username": user4_name
            }))
        elif event.get('message') != None:
            message = event['message']
            if message == 'nochange':
                pass
            else:
                room_id = event['room_id']
                room_instance = Room.objects.get(id=room_id)
                initial = event['initial']
                modify = event['modify']
                if modify == "user2":
                    if room_instance.user2 != None:
                        message = 'nochange'
                if modify == "user3":
                    if room_instance.user3 != None:
                        message = 'nochange'
                if modify == "user4":
                    if room_instance.user4 != None:
                        message = 'nochange'
                # Send message to WebSocket
                await self.send(text_data=json.dumps({

                    'type': 'chat_message',
                    'message': message,
                    'initial': initial,
                    'modify': modify

                }))
        elif event.get('newarrival') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'position': event['position'],
                'url': event['url'],
                'status': event['status'],
                'status_url': state_reference[event['status']],
                'newarrival': 'newarrival'
            }))
        elif event.get('exit_user') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'exit_user': event['exit_user'],
                'adjusted_user': event['adjusted_user']
            }))
        elif event.get('disconnection_update') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'disconnection_update': event['disconnection_update'],
                'user1_url': event['user1_url'],
                'user1_status': event['user1_status'],
                'user1_status_url': state_reference[event['user1_status']],
                'user2_url': event['user2_url'],
                'user2_status': event['user2_status'],
                'user2_status_url': state_reference[event['user2_status']],
                'user3_url': event['user3_url'],
                'user3_status': event['user3_status'],
                'user3_status_url': state_reference[event['user3_status']],
                'user4_url': event['user4_url'],
                'user4_status': event['user4_status'],
                'user4_status_url': state_reference[event['user4_status']]
            }))
        elif event.get('room_acces_symbol') != None:
            await self.send(text_data=json.dumps({

                'type': 'chat_message',
                'room_acces_symbol': event['room_acces_symbol']
            }))

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        print("disconnect")
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))


import os
import json
from utils.logger import Logger
from journey.builder import build
from journey.controller.request.travel import service

logger = Logger('RECOMMENDED')
logger.get()
logger = logger._logger

filepath = os.path.join('./journey/controller/static', 'string_message.json')
LIST_OF_MESSAGE = []
with open(filepath) as message_file:
    LIST_OF_MESSAGE = json.load(message_file)

def choose_recommended(profile, messages, parameters):
    """user choose recommended, astral will provide data wisata place to user based on category"""
    lists = []
    user_id = profile.user_id
    display_name = profile.display_name

    logger.info("%s - %s choose %s" % (display_name, user_id, parameters['travel-tipe']))

    switcher = {
        'Adventure': show_recommended_adventure,
        'Sweet Escape': show_recommended_sweetescape,
        'Culinary': show_recommended_culinary
    }

    fx = switcher.get(parameters['travel-tipe'], "")(profile, messages, parameters)

    if fx is None:
        logger.error("%s - %s | Data : %s" % (display_name, user_id, fx))
        bubble_text = build.show_text(LIST_OF_MESSAGE['message_error_general'])
        lists.append(bubble_text)
    else:
        lists = fx

    return lists

def show_recommended_adventure(profile, messages, parameters):
    user_id = profile.user_id
    display_name = profile.display_name

    logger.info("%s - %s choose %s" % (display_name, user_id, parameters['tipe-adventure']))

    place_type = parameters['tipe-adventure'].lower()
    req_attr = ("", 'chat', place_type, "", "", "y", "", "", user_id)

    lists_data_carousel = service.get_adventure(req_attr)

    lists = build_message(user_id, display_name, messages,  lists_data_carousel)

    return lists

def build_message(user_id, display_name, messages,  lists_data_carousel):
    lists = []

    key = 'errorCode'
    if key in lists_data_carousel:
        logger.error("%s - %s | Data : %s" % (display_name, user_id, lists_data_carousel))
        bubble_text = build.show_text(LIST_OF_MESSAGE['message_error_datanotfound_recommended'])
        lists.append(bubble_text)
    else:
        attr_action = ('message', 'View Detail', 'place_name')
        attr_column = ('url_image', 'place_name', 'short_desc')
        lists_columns = build.populate_carousel_img(lists_data_carousel, attr_action, attr_column, None)

        alt_text = LIST_OF_MESSAGE['alt_recommended']
        bubble_carousel = build.show_carousel_with_img(alt_text, lists_columns)

        if len(messages) > 0:
            bubble_text = build.show_text(messages[0]['speech'])

        lists.append(bubble_text)
        lists.append(bubble_carousel)

    return lists

def show_recommended_sweetescape(profile, messages, parameters):
    user_id = profile.user_id
    display_name = profile.display_name

    logger.info("%s - %s choose %s" % (display_name, user_id, parameters['tipe-sweetescape']))
    pass

def show_recommended_culinary(profile, messages, parameters):
    user_id = profile.user_id
    display_name = profile.display_name

    logger.info("%s - %s choose %s" % (display_name, user_id, parameters['tipe-culinary']))
    pass


from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import EmployeeForm
from .models import Employee
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import EmployeeSerializer

def employee_list(request):
    context = {
        'employee_list': Employee.objects.all(),
    }
    return render(request, "employee_register/employee_list.html", context)

def employee_form(request, id=0):
    if request.method == "GET":
        if id == 0:
            form = EmployeeForm()
        else:
            employee = Employee.objects.get(pk=id)
            form = EmployeeForm(instance=employee)
        return render(request, "employee_register/employee_form.html", {'form': form})
    else:
        if id == 0:
            form = EmployeeForm(request.POST)
        else:
            employee = Employee.objects.get(pk=id)
            form = EmployeeForm(request.POST, instance=employee)
        if form.is_valid():
            form.save()
        return redirect('/employee/list')

def employee_delete(request, id):
    employee = Employee.objects.get(pk=id)
    employee.delete()
    return redirect('/employee/list')

class EmployeeAPI(APIView):

    def get(self, request):
        emp = Employee.objects.all()
        serializer = EmployeeSerializer(emp, many=True)
        return Response(serializer.data)

    def post(self, request):
        pass