import xlsxwriter
from datetime import datetime

# Create a new Format object to formats cells
# in worksheets using add_format() method .
def Pi_Chart_creation(workbook,worksheet,data,info_list):
    # here we create bold format object .
    bold = workbook.add_format({'bold': 1})

    # create a data list .
    headings = ['Title', 'Number']

    # Write a row of data starting from 'A1'
    # with bold format.
    worksheet.write_row('A1', headings, bold)

    # Write a column of data starting from
    # A2, B2, C2 respectively.
    worksheet.write_column('A2', data[0])
    worksheet.write_column('B2', data[1])

    # Create a chart object that can be added
    # to a worksheet using add_chart() method.

    # here we create a pie chart object .
    chart1 = workbook.add_chart({'type': 'pie'})
    chart2 = workbook.add_chart({'type': 'pie'})
    chart3 = workbook.add_chart({'type': 'pie'})
    # Add a data series to a chart
    # using add_series method.
    # Configure the first series.
    # [sheetname, first_row, first_col, last_row, last_col].
    chart1.add_series({
        'name': 'SWR Coverage',
        'categories': ['KPI', 1, 0, 2, 0],
        'values': ['KPI', 1, 1, 2, 1],
    })
    chart2.add_series({
        'name': 'DWI Coverage',
        'categories': ['KPI', 3, 0, 4, 0],
        'values': ['KPI', 3, 1, 4, 1],
    })

    chart3.add_series({
        'name': 'SWC Coverage',
        'categories': ['KPI', 5, 0, 6, 0],
        'values': ['KPI', 5, 1, 6, 1],
    })
    # Add a chart title
    chart1.set_title({'name': 'SWR Coverage'})
    chart2.set_title({'name': 'DWI Coverage'})
    chart3.set_title({'name': 'SWC Coverage'})
    # Set an Excel chart style. Colors with white outline and shadow.
    chart1.set_style(10)
    chart2.set_style(10)
    chart3.set_style(10)

    # Insert the chart into the worksheet(with an offset).
    # the top-left corner of a chart is anchored to cell C2.
    worksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10})
    worksheet.insert_chart('L2', chart2, {'x_offset': 25, 'y_offset': 10})
    worksheet.insert_chart('L18', chart3, {'x_offset': 25, 'y_offset': 10})
    # Finally, close the Excel file
    # via the close() method.
    return workbook


import  xdrlib ,sys
import xlrd
import xlwt
from xlutils.copy import copy

#打开excel文件
def open_excel(file):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception as e:
        print(str(e))

#获取单元格值
def excel_cell_bycells(file,by_name,row,column):
    data = open_excel(file) #打开excel文件
    table = data.sheet_by_name(by_name) #根据sheet名字来获取excel中的sheet
    cell = table.cell(row,column).value #获取cell值
    return cell

#获取多单元格值
def excel_cell_bylist(file,by_name,list):
    app = []
    data = open_excel(file) #打开excel文件
    table = data.sheet_by_name(by_name) #根据sheet名字来获取excel中的sheet
    for x in range(len(list)):
        row = list[x][0]
        column = list[x][1]
        cell = table.cell(row,column).value #获取cell值
        app.append(cell)
    return app

#获取行
def excel_table_byname(file, by_name, colnameindex):
    data = open_excel(file) #打开excel文件
    table = data.sheet_by_name(by_name) #根据sheet名字来获取excel中的sheet
    colnames = table.row_values(colnameindex) #某一行数据
    app =[] #装读取结果的序列
    if colnames: #如果行存在
        for i in range(len(colnames)): #读取行的内容
            app.append(row[i])
    #获取指定行内容
    print(app)
    return app

#根据名称获取Excel表格中的数据   参数:file：Excel文件路径     colnameindex：表头列名所在行的索引  ，by_name：Sheet1名称
def excel_table_byname(file, by_name):
    data = open_excel(file) #打开excel文件
    table = data.sheet_by_name(by_name) #根据sheet名字来获取excel中的sheet
    nrows = table.nrows #行数
    list =[] #装读取结果的序列
    for rownum in range(0, nrows): #遍历每一行的内容
         row = table.row_values(rownum) #根据行号获取行
         if row: #如果行存在
             app = [] #一行的内容
             for i in range(len(row)): #一列列地读取行的内容
                app.append(row[i])
             list.append(app) #装载数据
    return list

#将list中的内容写入一个新的file文件
def testXlwt_list(file, Sheet, list):

    book = xlwt.Workbook() #创建一个Excel
    sheet1 = book.add_sheet(Sheet) #在其中创建一个名为hello的sheet
    i = 0 #行序号
    for app in list : #遍历list每一行
        j = 0 #列序号
        for x in app : #遍历该行中的每个内容（也就是每一列的）
            sheet1.write(i, j, x) #在新sheet中的第i行第j列写入读取到的x值
            j = j+1 #列号递增
        i = i+1 #行号递增
    book.save(file) #创建保存文件

#指定位置写数据
def testXlwt_cell(file, Sheet, row, column, cell):
    book = xlrd.open_workbook(file) #打开一个Excel
    xbook = copy(book)
    sheet1 = xbook.get_sheet(Sheet) #在其中打开sheet
    sheet1.write(row,column,cell) #往sheet里第row行第column列写一个数据
    xbook.save(file) #保存文件

#新建sheet页指定位置写数据
def testrw(file):
    book = xlwt.Workbook()
    table = book.add_sheet('hello')
    table.write(0,0,'5')
    book.save(file)


import asyncio
import json
import os

import aiohttp
import pytest
from aioresponses import aioresponses
from pyeasee import Charger, Easee

BASE_URL = "https://api.easee.com"

def load_json_fixture(filename):
    with open(os.path.join(os.path.dirname(__file__), "fixtures", filename)) as f:
        return json.load(f)

@pytest.fixture
def aioresponse():
    with aioresponses() as m:
        yield m

@pytest.fixture
async def aiosession():
    return aiohttp.ClientSession()

@pytest.mark.asyncio
async def test_get_chargers(aiosession, aioresponse):

    token_data = load_json_fixture("token.json")
    aioresponse.post(f"{BASE_URL}/api/accounts/login", payload=token_data)

    chargers_data = load_json_fixture("chargers.json")
    aioresponse.get(f"{BASE_URL}/api/chargers", payload=chargers_data)

    easee = Easee("+46070123456", "password", aiosession)
    chargers = await easee.get_chargers()
    assert chargers[0].id == "EH12345"

    chargers_state_data = load_json_fixture("charger-state.json")
    aioresponse.get(f"{BASE_URL}/api/chargers/EH12345/state", payload=chargers_state_data)

    state = await chargers[0].get_state(raw=True)

    assert state["chargerOpMode"] == 2

    await easee.close()
    await aiosession.close()

@pytest.mark.asyncio
async def test_get_sites(aiosession, aioresponse):

    token_data = load_json_fixture("token.json")
    aioresponse.post(f"{BASE_URL}/api/accounts/login", payload=token_data)

    sites_data = load_json_fixture("sites.json")
    aioresponse.get(f"{BASE_URL}/api/sites", payload=sites_data)

    site_data = load_json_fixture("site.json")
    aioresponse.get(f"{BASE_URL}/api/sites/55555?detailed=true", payload=site_data)

    easee = Easee("+46070123456", "password", aiosession)
    sites = await easee.get_sites()

    assert sites[0].id == 55555

    circuits = sites[0].get_circuits()
    assert circuits[0].id == 12345

    chargers_data = load_json_fixture("chargers.json")
    aioresponse.get(f"{BASE_URL}/api/chargers", payload=chargers_data)

    chargers = circuits[0].get_chargers()

    assert chargers[0].id == "ES12345"
    await easee.close()
    await aiosession.close()

@pytest.mark.asyncio
async def test_get_site_state(aiosession, aioresponse):

    token_data = load_json_fixture("token.json")
    aioresponse.post(f"{BASE_URL}/api/accounts/login", payload=token_data)

    site_state_data = load_json_fixture("site-state.json")
    aioresponse.get(f"{BASE_URL}/api/sites/54321/state", payload=site_state_data)

    easee = Easee("+46070123456", "password", aiosession)
    site_state = await easee.get_site_state("54321")

    charger_config = site_state.get_charger_config("EH123497")
    assert charger_config["localNodeType"] == "Master"

    charger_state = site_state.get_charger_state("EH123497", raw=True)

    assert charger_state["chargerOpMode"] == 1

    charger_state = site_state.get_charger_state("NOTEXIST")
    assert charger_state is None

    await easee.close()
    await aiosession.close()


import argparse
import socket
import os

parser = argparse.ArgumentParser()
parser.add_argument(
  "-p",
  "--ping",
  dest="ping",
  type=str,
  help="Pinglenecek site",
)
parser.add_argument(
  "-o",
  "--output",
  dest="output",
  type=str,
  help="Pinglenecek site",
)
args = parser.parse_args()
adress = args.ping

socket.setdefaulttimeout(2)
host = socket.gethostbyname(args.ping)
print(host)

cwd = os.getcwd()
print(cwd)
# nmap -sV --script=vulscan/vulscan.nse www.example.com

os.system("nmap -sv --script="+cwd+"""/vulscan/vulscan.nse """+host)


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

"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

__author__ = "timmyliang"
__email__ = "820472580@qq.com"
__date__ = "2020-11-04 15:30:25"

import os
import six
import uuid
import json
import random
import hashlib
import inspect
import tempfile
from functools import partial
from collections import OrderedDict
from Qt import QtCore, QtWidgets

from .util import nestdict
from .binding import Binding, FnBinding, BindingProxy
from .eventhook import QEventHook, Iterable

event_hook = QEventHook.instance()

class BinderCollector(QtCore.QObject):
    Binders = OrderedDict()
    __flag__ = True

    def get_current_Binders(self):
        uid = uuid.uuid4()
        if self.Binders:
            last_uid = list(self.Binders.keys())[-1]
            if self.__flag__:
                uid = last_uid
                self >> event_hook(QtCore.QEvent.User, lambda: self.set_flag(False))
                event = QtCore.QEvent(QtCore.QEvent.User)
                QtWidgets.QApplication.postEvent(self, event)
            else:
                self.set_flag(True)

        BinderCollector.Binders.setdefault(uid, [])
        return BinderCollector.Binders[uid]

    @classmethod
    def set_flag(cls, flag):
        cls.__flag__ = flag

    @classmethod
    def get_last_key(cls):
        return list(cls.Binders.keys())[-1]

class BinderDumper(QtCore.QObject):
    _dumper_dict_ = {}

    @classmethod
    def instance(cls, binder, *args, **kwargs):
        instance = cls._dumper_dict_.get(id(binder))
        if not instance:
            instance = cls(binder, *args, **kwargs)
            cls._dumper_dict_[id(binder)] = instance

        return instance

    def __init__(self, binder, db_name, filters=None):
        if self._dumper_dict_.get(id(binder)):
            raise Exception("This class is a singleton! Use `instance` method instead.")
        super(BinderDumper, self).__init__()
        self.binder = binder
        self.db_name = db_name
        self._filters_ = (
            {filters}
            if isinstance(filters, str)
            else set(filters)
            if isinstance(filters, Iterable)
            else set()
        )
        folder = os.path.join(tempfile.gettempdir(), "QBinder")
        if not os.path.isdir(folder):
            os.mkdir(folder)
        self.path = os.path.join(folder, "%s.json" % db_name)

        # NOTE using timer call the __prepare__ in the next evnet loop (for loading delay)
        self >> event_hook(
            QtCore.QEvent.User, lambda: QtCore.QTimer.singleShot(0, self.__prepare__)
        )
        event = QtCore.QEvent(QtCore.QEvent.User)
        QtWidgets.QApplication.postEvent(self, event)

        self.auto_load = True

    def set_auto_load(self, enabled):
        self.auto_load = enabled

    def __prepare__(self):
        if self.auto_load:
            for k, binding in self.binder._var_dict_.items():
                if k in self._filters_:
                    binding.connect(self.save)
            self.load()

    def __enter__(self):
        BinderBase._trace_flag_ = True
        return self

    def __exit__(self, *args):
        BinderBase._trace_flag_ = False
        self._filters_.update(BinderBase._trace_setattr_)

    def __del__(self):
        self._dumper_dict_.pop(self)
        super(BinderDumper, self).__del__()

    def save(self, path="", indent=None):
        path = path if path else self.path
        data = {
            k: v.val for k, v in self.binder._var_dict_.items() if k in self._filters_
        }
        with open(path, "w") as f:
            json.dump(data, f, indent=indent)

    def load(self, path=""):
        path = path if path else self.path
        if not os.path.exists(path):
            return
        QtCore.QTimer.singleShot(0, partial(self.read, path))

    def read(self, path):
        try:
            with open(path, "r") as f:
                data = json.load(f, object_pairs_hook=OrderedDict, encoding="utf-8")
            for k, v in data.items():
                setattr(self.binder, k, v)
        except:
            # NOTE May be the file broken for some reason.
            os.remove(path)
        # TODO add read hook

    def clear(self):
        if os.path.exists(self.path):
            os.remove(self.path)

class BinderDispatcher(QtCore.QObject):
    _trace_dict_ = nestdict()
    __instance = None

    @classmethod
    def instance(cls, binder):
        cls.binder = binder
        if not cls.__instance:
            cls.__instance = cls()
        return cls.__instance

    def __init__(self):
        if self.__instance:
            raise Exception("This class is a singleton! Use `instance` method instead.")
        super(BinderDispatcher, self).__init__()
        self >> event_hook(QtCore.QEvent.User, self.__bind_cls__)
        event = QtCore.QEvent(QtCore.QEvent.User)
        QtWidgets.QApplication.postEvent(self, event)

    def __bind_cls__(self):
        for module, data in self._trace_dict_.items():
            for cls_name, _data in data.items():
                if hasattr(module, cls_name):
                    cls = getattr(module, cls_name)
                    for _, binding in _data.items():
                        binding.cls = cls
        self._trace_dict_.clear()

    def dispatch(self, command, *args, **kwargs):
        method_dict = OrderedDict(inspect.getmembers(self, predicate=inspect.ismethod))
        method_dict.pop("dispatch")
        func = method_dict.get(command)
        if func is None:
            raise RuntimeError("Binder Action %s not found" % command)
        return func(*args, **kwargs)

    def dumper(self, db_name=None, filters=None):
        dumper = BinderDumper._dumper_dict_.get(id(self.binder))
        db_name = dumper.db_name if dumper else db_name
        if not db_name:
            uid = BinderCollector.get_last_key()
            binder_list = BinderCollector.Binders[uid]
            index = binder_list.index(self.binder)
            rd = random.Random()
            rd.seed(index)
            hex = uuid.UUID(int=rd.getrandbits(128)).hex
            path = inspect.stack()[-1][1]
            md5 = hashlib.md5("".join((path, hex)).encode("utf-8")).hexdigest()
            db_name = md5

        return BinderDumper.instance(self.binder, db_name, filters)

    def fn_bind(self, attr=None):
        """fn_bind
        https://stackoverflow.com/a/13699329
        """

        def wrapper(func):
            binding = FnBinding(self.binder, func)
            function = func if six.callable(func) else func.__func__
            fn_name = attr if attr else function.__name__
            setattr(self.binder.__class__, fn_name, binding)

            stack = inspect.stack()[-2]
            cls_name = stack[3]
            frame = stack[0]
            module = inspect.getmodule(frame)

            self._trace_dict_[module][cls_name][fn_name] = binding

            return func

        return wrapper

    def dispatcher(self):
        return self

class BinderProxy(object):
    _var_dict_ = {}

    def __getitem__(self, key):
        return self._var_dict_.get(key)

    def __setitem__(self, key, value):
        var = self._var_dict_.get(key)
        var.set(value) if var else None

    def __setattr__(self, key, value):
        self._var_dict_[key] = value
        value = value if isinstance(value, Binding) else Binding(value)
        self.__dict__[key] = value

class BinderBase(object):
    _var_dict_ = {}
    _trace_flag_ = False
    _trace_setattr_ = []

    def __getitem__(self, key):
        val = self._var_dict_.get(key)
        if val is not None:
            return val
        else:
            return BindingProxy(self, key)

    def __setitem__(self, key, value):
        var = self._var_dict_.get(key)
        var.set(value) if var else None

    # def __getattr__(self, key):
    #     return BindingProxy(self, key)

    def __setattr__(self, key, value):
        if self._trace_flag_:
            self._trace_setattr_.append(key)
        binding = self._var_dict_.get(key)
        if binding:
            binding.set(value)
        else:
            # NOTE assign binding to class static member
            binding = Binding(value)
            binding.__binder__ = self
            self._var_dict_[key] = binding
            setattr(self.__class__, key, binding)
            if isinstance(value, FnBinding):
                value.connect_binder(key, self)

    def __call__(self, *args):
        # NOTE __call__ dispatch function avoid polluting local scope
        return BinderDispatcher.instance(self).dispatch(*args)

    def __enter__(self):
        # NOTE support with statement for group indent
        self.proxy = BinderProxy()
        return self.proxy

    def __exit__(self, *args):
        # NOTE get the outer frame
        frame = inspect.currentframe().f_back

        for k, v in frame.f_locals.items():
            if self.proxy is v:
                for n, s in inspect.getmembers(self.proxy):
                    if isinstance(s, Binding):
                        self._var_dict_[n] = s
                        setattr(self.__class__, n, s)
                # NOTE overwrite the local scope like `return` action
                frame.f_locals.update({k: self})
                break

class Binder(BinderBase):
    def __new__(cls, *args, **kw):
        # NOTE spawn different class instance to contain static member
        class BinderInstance(BinderBase):
            _var_dict_ = {}

        instance = cls.__new__(BinderInstance)
        binder_list = BinderCollector().get_current_Binders()
        binder_list.append(instance)
        return instance

class GBinder(BinderBase):
    # NOTE Global Singleton
    __instance = None
    _var_dict_ = {}

    # TODO Group by arg string
    def __new__(cls, *args, **kw):
        if cls.__instance is None:
            cls.__instance = BinderBase.__new__(cls)
            binder_list = BinderCollector().get_current_Binders()
            binder_list.append(
                cls.__instance
            ) if cls.__instance not in binder_list else None
        return cls.__instance

class BinderTemplateMeta(type):
    def __new__(cls, name, bases, attrs):
        # NOTE wrap all method into staticmethod
        for name, member in attrs.items():
            if inspect.isroutine(member):
                attrs[name] = staticmethod(member)
        return type.__new__(cls, name, bases, attrs)

# NOTE with_metaclass make staticmethod work
class BinderTemplate(six.with_metaclass(BinderTemplateMeta, object)):
    def __new__(cls, *args, **kwargs):
        binder = Binder()
        for name, member in inspect.getmembers(cls):
            if name.startswith("__"):
                continue
            if inspect.isroutine(member):
                setattr(binder, name, partial(member, binder))
            else:
                setattr(binder, name, member)
        cls.__init__(binder, *args, **kwargs)
        return binder

    def __getitem__(self, key):
        """stub method for pylint & autocomplete"""
        return Binding()

    def __setitem__(self, key, value):
        """stub method for pylint & autocomplete"""
        return Binding()

    def __call__(self, key):
        """stub method for pylint & autocomplete"""
        return


#HW6
#Strings

def countCharInString (findChar , targetString):
    return targetString.count(findChar)

phrase = input('Please enter a phrase: ')
phrase = phrase.lower()

alphabet = 'abcdefghijklmnopqrstuvwxyz'
letterCountZeroList = []

for letter in alphabet:
    count = countCharInString(letter, phrase)
    if count == 1:
        print('There is only 1', letter)
    elif count > 1:
        print('There are', count, 'of the letter', letter)
    else:
        letterCountZeroList.append(letter)

print('There were none of the following letters found:')
for letter in letterCountZeroList:
    print(letter)


from django.shortcuts import render
from django.shortcuts import render_to_response

# session requires HttpResponse
from django.http import HttpResponse
from article.models import Article
#from django.template.loader import get_template
#from django.template import Context

def hello(request):
   name=request.GET["k"]
   html="Moro %s. Mita kuuluu?" % name
   return render_to_response('hello.html',{'name':html})

def articles(request):
	language = "en-gb"
	session_language = "en-gb"
	if 'lang' in request.COOKIES:
		language = request.COOKIES["lang"]

	if 'lang' in request.session:
		session_language = request.session["lang"]

	return render_to_response('articles.html',
								{'articles': Article.objects.all(),
								  'language': language,
								  'session_language': session_language})

def article(request, article_id=1):
	return render_to_response('article.html',
								{'article' : Article.objects.get(id=article_id)})

def language(request,language="en-gb"):
	response = HttpResponse("setting language to %s" % language)
	response.set_cookie("lang", language)
	request.session["lang"] = language
	return response


# class Hero:     # template
#     pass
# hero1 = Hero()   # object / instance (proses : instansiate)
# hero2 = Hero()
# hero3 = Hero()

# hero1.name = 'sniper'
# hero1.health = 100

# hero2.name = 'sven'
# hero2.health = 200

# hero3.name = 'ucup'
# hero3.health = 1000

# print(hero1)
# print(hero1.__dict__)
# print(hero1.name)

class Hero:
    # class varible
    jumlah_hero = 0
    def __init__(self, inputName, inputHealth, inputPower, inputArmor):
        # instance Variable
        self.name = inputName
        self.health = inputHealth
        self.power = inputPower
        self.armor = inputArmor
        Hero.jumlah_hero += 1
        # print('membuat Hero dengan nama ' + inputName)

    # void function, method tanpa return tanpa argumen
    def siapa(self):
        print('namaku adalah ' + self.name)

    # method dengan argumen tanpa return
    def healthUp(self,up):
        self.health += up

    # method dengan return
    def getHealth(self):
        return self.health

hero1 = Hero('sniper', 100,10,5)
# print(Hero.jumlah)
hero2 = Hero('mario bros',90,5,10)
# print(Hero.jumlah)
# hero3 = Hero('ucup',1000,100,0)
# print(Hero.jumlah)
# print(hero1.__dict__)
# print(hero2.__dict__)
hero1.siapa()
hero1.healthUp(10)

print(hero1.getHealth())

# print(hero1.__dict__)
# print(hero2.__dict__)
# print(hero3.__dict__)
# print(Hero.__dict__)

print(hero1.__dict__)


from back.agent import Agent
from back.board import Board
from back.cell import Cell
from copy import deepcopy
from back.ghost import Ghost

from back.pacman import Pacman

class Perception():
    """Class describing a perception of the pacman game (agent or team)
    """
    _board: Board
    _pacman_sighting: list[int, Pacman]  # [time since sighting, Pacman]
    _ghost_sightings: dict[str: list[int, Ghost]]  # id: [time since sighting, Ghost]]
    _last_cell_seen: list[tuple[int, int]]  # x, y

    def __init__(self, board_size: tuple[int, int]) -> None:
        """Perception's initialization

        :param board_size: game board's size
        :type board_size: tuple[int, int]
        """
        assert isinstance(board_size, tuple)
        assert len(board_size) > 0
        assert isinstance(board_size[0], int)

        self._board = Board()
        self._board.set_board(
            [[Cell['UNKNOWN'] for y in range(board_size[1])] for x in range(board_size[0])])
        self._last_cell_seen = []
        self._pacman_sighting = None
        self._ghost_sightings = {}

    def set_board(self, board: Board) -> None:
        """Set the perception's board

        :param board: board to set
        :type board: Board
        """
        assert isinstance(board, Board)

        self._board = deepcopy(Board)

    def step_time(self) -> None:
        """Step the time in the perception, increase the counters telling how long ago we saw each agents
        """
        # step_time
        if self._pacman_sighting is not None:
            self._pacman_sighting[0] += 1
        for sighting in self._ghost_sightings.values():
            sighting[0] += 1
        # refresh last cell seen
        self._last_cell_seen = []

    def update(self, other: 'Perception') -> None:
        """Update a peception with the informations of an other

        :param other: other perception with the update informations
        :type other: Perception
        """
        assert isinstance(other, Perception)

        # update board
        width, height = self._board.get_size()
        other_board = other.get_board()
        for x in range(width):
            for y in range(height):
                if other_board.get_cell((x, y)) == Cell['UNKNOWN']:
                    continue
                if (x, y) not in self._last_cell_seen:
                    self._last_cell_seen.append((x, y))

                self._board.set_cell((x, y), other_board.get_cell((x, y)))
        # update Pacman seen
        sighting = other.get_pacman_sighting()
        if len(sighting) > 0 and sighting[0][0] == 0:
            self._pacman_sighting = [0, deepcopy(sighting[0][1])]
        # update Ghosts seen
        for time, ghost in other.get_ghost_sightings():
            if time == 0:
                self._ghost_sightings[ghost.get_id()] = [0, deepcopy(ghost)]

    def get_board(self) -> Board:
        """Get the perception's board

        :return: the perception's board
        :rtype: Board
        """
        return self._board

    def get_last_cells_seen(self) -> list[tuple[int]]:
        """returns the list of positions of the last cells seen by the team

        :return: list of positions
        :rtype: list[tuple[int]]
        """
        return self._last_cell_seen

    def get_sightings(self) -> list[list[int, Agent]]:
        """Get the perception's sighting of ghosts and pacman combined

        :return: the list of all sightings
        :rtype: list[tuple] [(id, time since sighting, x, y), ...]
        """
        return self.get_ghost_sightings() + self.get_pacman_sighting()

    def get_pacman_sighting(self) -> list[list[int, Pacman]]:
        """Get the perception's pacman sighting

        :return: the pacman sighting
        :rtype: list[int, Pacman]
        """
        if self._pacman_sighting is None:
            return []
        return [self._pacman_sighting]

    def get_ghost_sightings(self) -> list[list[int, Ghost]]:
        """Get the perception's ghost sightings

        :return: the list of ghost sightings
        :rtype: list[list[int, Ghost]]
        """
        return list(self._ghost_sightings.values())

    def update_sightings(self, agent: Agent) -> None:
        """Update the sighting informations of a given agent

        :param agent: agent to add to the sightings
        :type agent: Agent
        """
        if isinstance(agent, Pacman):
            self._pacman_sighting = [0, deepcopy(agent)]
        else:
            self._ghost_sightings[agent.get_id()] = [0, deepcopy(agent)]

    def get_ids(self) -> list[str]:
        """Get ids of all sightings

        :return: list of all ids
        :rtype: list[str]
        """
        return [sighting[1].get_id() for sighting in self.get_sightings()]

    def get_ghost_ids(self) -> list[str]:
        """Get the ids of the ghost that have been seen

        :return: list of ids
        :rtype: list[str]
        """
        return [sighting[1].get_id() for sighting in self.get_ghost_sightings()]

    def __str__(self) -> str:
        out = str(self._board)
        width, _ = self._board.get_size()
        for id, value in self._agents_seen.items():
            if value[0] != 0:
                continue
            print(value)
            _, pos = value
            x, y = pos
            out = out[:(width + 1) * y + x] + id[0] + out[(width + 1) * y + x + 1:]
        return out + str(self._agents_seen) + '\n'


import random
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("pi") \
    .getOrCreate()

sc = spark.sparkContext

num_samples = 100000000

def inside(p):
  x, y = random.random(), random.random()
  return x*x + y*y < 1

count = sc.parallelize(range(0, num_samples)).filter(inside).count()
pi = 4 * count / num_samples
print(pi)
sc.stop()


# importing required libraries of opencv
import cv2
from matplotlib import pyplot as plt
import numpy as np
import os
from images_repository import ImagesRepository
def get_meancolor_value(myimg):
    avg_color_per_row = np.average(myimg, axis=0)
    avg_color = np.average(avg_color_per_row, axis=0)
    return avg_color.tolist()
def add_histo(image):
    image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    hist = cv2.calcHist([image], [0], None, [256], [0, 256]) / 255

    return hist.flatten().tolist()

def compare_i_gray_hist(hist,image2):
    hist=np.array([[i] for i in hist])
    image2=cv2.cvtColor(image2, cv2.COLOR_RGB2HSV)
    hist2= cv2.calcHist([image2], [0], None, [256], [0, 256])/255
    return cv2.compareHist(hist2,hist,cv2.HISTCMP_CORREL)
def add_color_layout(image):
    colorlayout=[]

    image = cv2.resize(image, (1152, 960), interpolation=cv2.INTER_AREA)
    for r in range (15):

        for b in range(18):
            mean = np.zeros((1, 3))
            for i in range(3):
                mean[0, i] = np.mean(image[64*r:64*(r+1), 64*b:64*(b+1), i])/255
            colorlayout.append(mean)
    colorlayout=np.array(colorlayout).reshape(-1)
    return colorlayout.tolist()

def compare_color_layout(image1,color):
    color=np.array(color).reshape(270,3)
    score=0
    image1=cv2.resize(image1,(1152,960),interpolation = cv2.INTER_AREA)
    index=0

    for r in range (15):

        for b in range(18):
            mean = np.zeros((1, 3))
            for i in range(3):
                mean[0, i] = np.mean(image1[64*r:64*(r+1), 64*b:64*(b+1), i])/255

            sub=np.abs(np.subtract(mean,color[index])).reshape(-1)
            index+=1
            if  sub[0]<0.4 and sub[1]<0.4 and sub[2]<0.4:

                score+=1

    print("The sore is :",(score/270)*100,"%")
    if (score/270)*100 >=55 :
        #print(score)
        return 1
    else:
        return 0

image_repo=ImagesRepository()

# plt.show()

# image_repo=ImagesRepository()
# #####################################processing data ##############################################
# path="D:\\Abdelrhman\\4th computer\\Multimedia\\project\\images"
# files_and_directories = os.listdir(path)
# for item in files_and_directories :
#     path_ = path+'/'+item
#     img1=cv2.imread(path_)
#     image_repo.save_image(path_,get_meancolor_value(img1),add_histo(img1),add_color_layout(img1) )


a = input("Enter a: ")
b = input("Enter b: ")
a = int(a)
b = int(b)

if a > b:
	n = b
	N = a
elif a < b:
	n = a
	N = b
else:
	n = 1
	N = 0
	print("Numbers should be different!")

while n <= N:
	print(n)
	n += 1


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

# # Explore U.S. Birth Data
#
# This Project works with a [dataset](https://raw.githubusercontent.com/fivethirtyeight/data/master/births/US_births_1994-2003_CDC_NCHS.csv) on births in the U.S. In this project, we are using the dataset compiled by FiveThirtyEight.
#
# The dataset contains the following columns:
# - `year` -- Year(1994 to 2003).
# - `month` -- Month(1 to 12).
# - `date_of_month` -- Day number of the month (1 to 31).
# - `day_of_week` -- Day of week (1 to 7).
# - `births` -- Number of births that day.

# ### First, open the file and convert it to a list.

f = open("US_births_1994-2003_CDC_NCHS.csv", "r")
file = f.read().split("\n")

# ### Or create a function that can convert a dataset into a list of lists where each nested list contains integer values.

def read_csv(csv):
    f = open(csv,"r")
    file = f.read().split("\n")
    string_list = file[1:len(file)-1]
    final_list = []
    for sl in string_list:
        int_fields = []
        string_fields = sl.split(',')
        for sf in string_fields:
            int_fields.append(int(sf))
            final_list.append(int_fields)
    return final_list

cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv")

# ### Then create a function to calculate the total number of births that occured in each month and each day of week, across all of the years in the dataset.

def month_births(input_list):
    births_per_month = {}
    for ls in input_list:
        month = ls[1]
        births = ls[4]
        if month in births_per_month:
            births_per_month[month] = births_per_month[month] + births
        else:
            births_per_month[month] = births
    return births_per_month

cdc_month_births = month_births(cdc_list)

def dow_births(input_list):
    births_per_dow = {}
    for ls in input_list:
        dow = ls[3]
        births = ls[4]
        if dow in births_per_dow:
            births_per_dow[dow] = births_per_dow[dow] + births
        else:
            births_per_dow[dow] = births
    return births_per_dow

cdc_day_births = dow_births(cdc_list)

# ### To make this process easier, create a function that can calculate the births based on the column we need.
#
# The `column` can indicate year, month or day of week.

def calc_counts(input_list, column):
    calc_result = {}
    for ls in input_list:
        calc_index = ls[column]
        result = ls[4]
        if calc_index in calc_result:
            calc_result[calc_index] = calc_result[calc_index] + result
        else:
            calc_result[calc_index] = result
    return calc_result

cdc_year_births = calc_counts(cdc_list, 0)

# ### We can then use the same function to calculate sum of births based on columns.

cdc_month_births = calc_counts(cdc_list, 1)
cdc_dom_births = calc_counts(cdc_list, 2)
cdc_dow_births = calc_counts(cdc_list, 3)

# ## Calculate the min and max births in certain dictionary.

def find_most(input_dict):
    most_result = {}
    most_result["min_birth"] = min(input_dict.values())
    most_result["max_birth"] = max(input_dict.values())
    return most_result

min_max_month_birth = find_most(cdc_month_births)


import os
from PyQt5 import uic
from PyQt5 import QtWidgets
import qgis
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QAction,QMessageBox,QTreeWidget,QTreeWidgetItem

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'OpenDataCube_Product_Loader_dialog_base.ui'))
import time
import datacube

class OpenDataCubeProductLoaderDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(OpenDataCubeProductLoaderDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.setFixedSize(self.frameSize())
        self.setWindowIcon(QIcon(":/plugins/OpenDataCube_Product_Loader/assets/icon.png"))

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            pass

    def closeEvent(self,event):
        reply=QtWidgets.QMessageBox.question(self,'OpenDatacube',"Are you sure to quit?",QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.No)
        if reply==QtWidgets.QMessageBox.Yes:
            event.accept()
            qgis.utils.reloadPlugin('opendatacubeproductloader')
            self.pConn.close()
            self.lld.close()
            if self.dbConnectionString is not None:
                del self.dbConnectionString
        else:
            event.ignore()

    def appendLogs(self,text):
        self.displayLogs.setReadOnly(True)
        self.displayLogs.textCursor().insertHtml(time.strftime('%m/%d/%Y %I:%M:%S %p')+' '+str(text)+'<br>')

    #list products and their variables to let the user choose
    def listProducts(self):
        global dc
        try:
            dc=datacube.Datacube(app="dc")
            product_name=dc.list_products().name.tolist()
            if len(product_name) != 0:
                product_variables=[]
                for products_variables in dc.list_measurements().name.to_dict():
                    product_variables.append(products_variables)
                for products in product_name:
                    #create a tree item
                    parent=QTreeWidgetItem(self.treeProductInfo)
                    #add parent item
                    parent.setText(0,products)
                    #set flag of tristate checkbox
                    parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
                    #extract band variables from product variable list
                    for product_vars,var in product_variables:
                        if product_vars == products:
                            #add child to the parent item
                            child=QTreeWidgetItem(parent)
                            #set the checkbox flag user checkable
                            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                            child.setText(0,var)
                            child.setCheckState(0, Qt.Unchecked)
                            #to display products in tree view
                    self.treeProductInfo.addTopLevelItem(parent)
                self.appendLogs('Products loaded!')
            else:
                self.appendLogs('Product List Empty!')
        except datacube.index.postgres._connections.IndexSetupError:
            self.appendLogs('No DB schema exists. Have you run init? datacube system init')

    def showIngestedDataProductList(self):
        import ast
        import datetime
        try:
            curs=self.dbConnectionString.cursor()
            product_name=dc.list_products().name.tolist()
            if len(product_name) != 0:
                product_variables=[]
                for products_variables in dc.list_measurements().name.to_dict():
                    product_variables.append(products_variables)
                for products in product_name:
                    parent=QTreeWidgetItem(self.treeProductInfo_2) #create a tree item
                    parent.setText(0,products) #add parent item
                    dataset_info_dict={}
                    curs.execute('SELECT id,lat,lon,upper(time) FROM agdc.dv_'+products+'_dataset;')
                    for info in curs:
                        i=str(ast.literal_eval(info[1])+ast.literal_eval(info[2]))
                        dataset_info_dict[i]=dataset_info_dict.get(i,())
                        dataset_info_dict[i]+=(info[0],info[3].strftime('%d-%m-%Y'))
                    for keys in dataset_info_dict:
                        child=QTreeWidgetItem(parent) #create a tree item
                        child.setText(0,keys) #add parent item
                        for values in dataset_info_dict[keys]:
                            child1=QTreeWidgetItem(child) #create a tree item
                            child1.setText(0,values) #add parent item
                    self.treeProductInfo_2.addTopLevelItem(parent) #to display products in tree view
            self.dc=dc
        except datacube.index.postgres._connections.IndexSetupError:
            self.appendLogs('No DB schema exists. Have you run init? datacube system init')

    def listCheckedProducts(self):
        checked = dict()
        root = self.treeProductInfo.invisibleRootItem()
        signal_count = root.childCount()

        for i in range(signal_count):
            signal = root.child(i)
            checked_sweeps = list()
            num_children = signal.childCount()

            for n in range(num_children):
                child = signal.child(n)

                if child.checkState(0) == Qt.Checked:
                    checked_sweeps.append(child.text(0))
            if signal.checkState(0) == Qt.Checked:
                checked[signal.text(0)] = checked_sweeps
            elif signal.checkState(0) == Qt.PartiallyChecked:
                checked[signal.text(0)] = checked_sweeps

        return checked

    def loadCoordinatesInPlugin(self,feature):
        self.ingestedLayer.removeSelection()
        self.ingestedLayer.select(feature.id())
        self.xMinMax.setText(','.join(feature['extent'].split(",", 2)[:2]))
        self.yMinMax.setText(','.join(feature['extent'].split(",", 2)[2:]))


import requests
import json

url = "https://api.imagga.com/v2/tags"

querystring = {"image_url":"https://cdn.pixabay.com/photo/2021/03/03/14/55/rhino-6065480_1280.jpg"}

headers = {
    'accept': "application/json",
    'authorization': "Basic YWNjXzJhNDg3YWFiZWM4ZWUwZjoyYzIyYTc1OTc4ZTc2MDZhNTllOTlmODllODhhNDFkOA=="
    }

response = requests.request("GET", url, headers=headers, params=querystring)
data = json.loads(response.text.encode("ascii"))

for i in range(6):
    tag = data["result"]["tags"][i]["tag"]["en"]
    print(tag)


from django.db.models import Q

from rest_framework.views import APIView
from rest_framework.response import Response

from .models import University

class ListUniversities(APIView):
    """
    View to list all known universities in the system
    """

    def get(self, request, format=None, query=None):
        """
        Return a list of all vocabulary items
        :return:
        """
        terms = request.GET.get('term', '')
        term_list = terms.split(' ')

        if len(term_list):
            filtered_unis = University.objects.filter(
                reduce(lambda x, y: x & y, [Q(name__icontains=word) for word in term_list])
            )
            universities = [uni.name for uni in filtered_unis]
        else:
            universities = []

        if len(universities) > 50:
            universities = ['Too many items to list, please continue typing...']

        return Response(universities)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 05 11:00:28 2015

@author: jhchen
"""
import gdal,ogr    ### osheo can't be imported with pyhdf
import osgeo
import gdalinfo
import numpy as np
import matplotlib.pyplot as plt
### this is a fuction to obtain the lon and lat in gdal
def pixel2coord(x, y,geoform):
    """Returns global coordinates from pixel x, y coords"""
    xoff=geoform[0]
    a=geoform[1]
    b=geoform[2]
    yoff=geoform[3]
    d=geoform[4]
    e=geoform[5]
    xp = a * x + b * y + xoff
    yp = d * x + e * y + yoff
    return(xp, yp)
# xoff, a, b, yoff, d, e = ds.GetGeoTransform()
dirin="D:/MyPaper/PhD04/Cases/ETP/20100604_0704/MODIS/ETP20100604-32d/"
fnm="MYD08_D3.A2010154.006.2014264200556.hdf"
fpath=dirin+fnm
modis=gdal.Open(fpath)
modisinfo=gdalinfo(fpath)
listvar=modis.GetSubDatasets()
lc_data=gdal.Open(listvar[253][0])
lc=lc_data.ReadAsArray()
nx=lc_data.RasterXSize
ny=lc_data.RasterYSize
geoform=lc_data.GetGeoTransform()
lon=np.ndarray(shape=(nx,ny), dtype=float)
lat=np.ndarray(shape=(nx,ny), dtype=float)
for i in range(0,nx):
    for j in range(0,ny):
        lon[i,j],lat[i,j] =pixel2coord(i,j,geoform)
minlat=int(lat.min())
maxlat=int(lat.max())
minlon=int(lon.min())
maxlon=int(lon.max())
lonlabs=[]
latlabs=[]
for i in range(0,nx):
    itm="%d"%int(lon[i,0])
    lonlabs.append(itm)
for i in range(0,ny):
    itm="%d"%int(lat[0,i])
    latlabs.append(itm)
fig,ax = plt.subplots(nrows=1,ncols=1)
#ax.set_ylim(35,80)
#ax.set_xlim(250,350)
plt.imshow(lc[:,:])
ax.set_xticks(range(0,nx,30))
xticklabels = [lonlabs[nn] for nn in range(0,nx,30)]
ax.set_xticklabels(xticklabels, size=14)
ax.set_yticks(range(0,ny,15))
yticklabels = [latlabs[nn] for nn in range(0,ny,15)]
ax.set_yticklabels(yticklabels, size=14)
plt.colorbar()
plt.show()
"""
fpath=dirin+"MYD08_D3.txt"
i=0
f=open(fpath,'w')
for nm in listvar:
    iband="%d "%i
    f.write(iband)
    itme="%s "%nm[1]
    f.write(itme)
    f.write('\n')
    i+=1
f.close()
"""


import logging
from homeassistant.util.dt import utcnow
import asyncio

from .const import (
  DOMAIN,
)

async def async_setup_entry(hass, entry):
  """This is called from the config flow."""
  hass.data.setdefault(DOMAIN, {})

  # Forward our entry to setup our default sensors
  hass.async_create_task(
    hass.config_entries.async_forward_entry_setup(entry, "sensor")
  )

  return True

async def options_update_listener(hass, entry):
  """Handle options update."""
  await hass.config_entries.async_reload(entry.entry_id)

async def async_unload_entry(hass, entry):
  """Unload a config entry."""

  unload_ok = all(
      await asyncio.gather(
          *[hass.config_entries.async_forward_entry_unload(entry, "sensor")]
      )
  )

  return unload_ok


from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder

    # def __init__(self, field, gps_actual, gps_target):
    #     self.field = field
    #     self.gps_actual = gps_actual
    #     self.gps_target = gps_target

def finder_path(field, gps_actual, gps_target, finder=AStarFinder):
    """Shortest pathfinding algorithms.

    Args:
        field (np.ndarray):
            The current field of fake environment.
        gps_actual (tulple):
            The current position of RL agent.
        gps_actual (tulple):
            The target position.
        finder (optional):
            Choose different algorithms. Defaults to AStarFinder.

    Returns:
        Each grid position of shortest path.
    """
    grid = field.copy()
    grid[grid > 0] = 99
    grid[grid == 0] = 1
    grid[grid == 99] = 0
    grid = grid.astype(int)
    grid = grid.tolist()
    grid = Grid(matrix=grid)

    # find path
    sx, sy = gps_actual
    tx, ty = gps_target
    start = grid.node(sy, sx)
    end = grid.node(ty, tx)
    finder = finder()
    path, _ = finder.find_path(start, end, grid)

    return path


def main():
    n = int(input())
    banks = eval(input()) #eval использую только для удобства ввода как в примере
    result = [0]
    combs = []
    for i in range(1, 2**n):
        x = bin(i)[2:].zfill(n)
        if not '11' in x: combs.append(x)
    max_money = 0
    banks_list = []
    for i in range(len(combs)):
        money = 0
        robbed_banks = []
        cur_comb = combs[i]
        for j in range(n):
            if cur_comb[j] == '1':
                money += int(banks[j][1])
                robbed_banks.append(tuple([banks[j][0], j+1]))
        if money > max_money:
            max_money = money
            banks_list = robbed_banks
    result[0] = max_money
    for i in banks_list:
        result.append(i)
    print(result)

if __name__ == '__main__':
    main()


#triangle solver app by rokteck

import math #this imports mathi library for higher mathematical operations

print("Welcome to the Triangle Area calculation App: ")

first_leg = float(input("Enter the first leg of triangle here: "))
second_leg = float(input("Enter the secong leg of triangle here: "))

#calculations or operations
h = math.sqrt(first_leg**2 + second_leg**2)
h = round(h,3)

#calculation for the area
area = 0.5*first_leg * second_leg
area = round(area,3)

print("For a triangle with " + str(first_leg) + " and " + str(second_leg) + " legs, the hypotenuse is " + str(h))

print("For a triangle with " + str(first_leg) + " and " + str(second_leg) + " legs, the area is " + str(area))


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 16:41:27 2020

@author: dkallen78
"""

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    for i in secretWord:
        if i not in lettersGuessed:
            return False
    return True

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    string = ""
    for i in secretWord:
        if i in lettersGuessed:
            string += i
        else:
            string += "_ "
    return string

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    letters = "abcdefghijklmnopqrstuvwxyz"
    string = ""
    for i in letters:
        if i not in lettersGuessed:
            string += i
        else:
            string += " "
    return string

secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']

print(getAvailableLetters(lettersGuessed))


import click
from nltk import word_tokenize
from collections import defaultdict

@click.command()
@click.argument("foo")
def baboon(foo):
    with open(foo,"r") as fi:
        words = word_tokenize(fi.read())
    freq = defaultdict(lambda :0)
    for word in words:
        freq[word]+=1

    report = [(v,k) for k,v in freq.items()]
    report.sort(reverse=True)
    for x in report:
        print(x)


from collections.abc import Iterator
class OrderIterator(Iterator):

    _position: int = None

    _reverse: bool = False

    def __init__(self, collection, reverse: bool = False) -> None:
        self._collection = collection
        self._reverse = reverse
        self._position = -1 if reverse else 0

    def __next__(self):

        try:
            value = self._collection[self._position]
            self._position += -1 if self._reverse else 1
        except IndexError:
            raise StopIteration()

        return value


# -*- coding: UTF-8 -*-
import tensorflow as tf
from tensorflow.python.estimator.canned import head as head_lib
from tensorflow.python.ops.losses import losses
import collections
from tensorflow.python.ops import metrics as metrics_lib
from metric import cal_group_auc

def build_deep_layers(net, params):
    # Build the hidden layers, sized according to the 'hidden_units' param.

    for num_hidden_units in params['hidden_units']:
        net = tf.layers.dense(net, units=num_hidden_units, activation=tf.nn.relu,
                              kernel_initializer=tf.glorot_uniform_initializer())
    return net

def _check_fm_columns(feature_columns):
  if isinstance(feature_columns, collections.Iterator):
    feature_columns = list(feature_columns)
  column_num = len(feature_columns)
  if column_num < 2:
    raise ValueError('feature_columns must have as least two elements.')
  dimension = -1
  for column in feature_columns:
    if dimension != -1 and column.dimension != dimension:
      raise ValueError('fm_feature_columns must have the same dimension.')
    dimension = column.dimension
  return column_num, dimension

def dfm_model_fn(features, labels, mode, params):
    net = tf.feature_column.input_layer(features, params['feature_columns']) # shape(batch_size, column_num * embedding_size)
    last_deep_layer = build_deep_layers(net, params)

    column_num, dimension = _check_fm_columns(params['feature_columns'])
    feature_embeddings = tf.reshape(net, (-1, column_num, dimension))  #(batch_size,column_num, embedding_size)

    # sum_square part
    summed_feature_embeddings = tf.reduce_sum(feature_embeddings, 1)  # (batch_size,embedding_size)
    summed_square_feature_embeddings = tf.square(summed_feature_embeddings)

    # squre-sum part
    squared_feature_embeddings = tf.square(feature_embeddings)
    squared_sum_feature_embeddings = tf.reduce_sum(squared_feature_embeddings, 1)

    fm_second_order = 0.5 * tf.subtract(summed_square_feature_embeddings, squared_sum_feature_embeddings)
    #print(tf.shape(fm_second_order))
    #print(fm_second_order.get_shape())

    if params['use_fm']:
        print('--use fm--')
        last_layer = tf.concat([fm_second_order, last_deep_layer], 1)
    else:
        last_layer = last_deep_layer
    #head = tf.contrib.estimator.binary_classification_head(loss_reduction=losses.Reduction.SUM)
    head = head_lib._binary_logistic_or_multi_class_head(  # pylint: disable=protected-access
                    n_classes=2, weight_column=None, label_vocabulary=None, loss_reduction=losses.Reduction.SUM)
    logits = tf.layers.dense(last_layer, units=head.logits_dimension,
                             kernel_initializer=tf.glorot_uniform_initializer())
    optimizer = tf.train.AdagradOptimizer(learning_rate=params['learning_rate'])

    preds = tf.sigmoid(logits)
    #print(tf.shape(preds))
    #print(preds.get_shape())
    user_id = features['user_id']
    label = features['label']
    if mode == tf.estimator.ModeKeys.EVAL:
        accuracy = tf.metrics.accuracy(labels=labels['class'],
                                       predictions=tf.to_float(tf.greater_equal(preds, 0.5)))
        auc = tf.metrics.auc(labels['class'], preds)
        label_mean = metrics_lib.mean(labels['class'])
        prediction_mean = metrics_lib.mean(preds)

        prediction_squared_difference = tf.math.squared_difference(preds, prediction_mean[0])
        prediction_squared_sum = tf.reduce_sum(prediction_squared_difference)
        num_predictions = tf.to_float(tf.size(preds))
        s_deviation = tf.sqrt(prediction_squared_sum/num_predictions), accuracy[0]     #标准差

        c_variation = tf.to_float(s_deviation[0]/prediction_mean[0]), accuracy[0]    #变异系数

        #group_auc = tf.to_float(cal_group_auc(labels['class'], preds, labels['user_id'])), accuracy[0] # group auc

        metrics = {'accuracy': accuracy, 'auc': auc, 'label/mean': label_mean, 'prediction/mean': prediction_mean,
                   'standard deviation': s_deviation, 'coefficient of variation': c_variation}
         #          'group auc': group_auc}
        tf.summary.scalar('accuracy', accuracy[1])
        tf.summary.scalar('auc', auc[1])
        tf.summary.scalar('label/mean', label_mean[1])
        tf.summary.scalar('prediction/mean', prediction_mean[1])
        tf.summary.scalar('s_deviation', s_deviation[1])
        tf.summary.scalar('c_variation', c_variation[1])
        #tf.summary.scalar('group_auc', group_auc[1])

        loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(labels=labels['class'], logits=logits))
        #print(tf.shape(loss))
        #print(loss.get_shape())
        return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)

    if mode == tf.estimator.ModeKeys.PREDICT:
        predictions = {
            'probabilities': preds,
            'user_id': user_id,
            'label': label
        }
        export_outputs = {
            'prediction': tf.estimator.export.PredictOutput(predictions)
        }
        return tf.estimator.EstimatorSpec(mode, predictions=predictions, export_outputs=export_outputs)

    return head.create_estimator_spec(
        features=features,
        mode=mode,
        labels=labels,
        logits=logits,
        train_op_fn=lambda loss: optimizer.minimize(loss, global_step=tf.train.get_global_step())
    )


from copy import deepcopy
from typing import Sequence

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision

class PostProc(nn.Module):
    def __init__(self, num_classes=80, use_focal_loss=True, num_top_queries=300, remap_mscoco_category=False, classes=None, iou_thres=0.25) -> None:
        super().__init__()
        self.use_focal_loss = use_focal_loss
        self.num_top_queries = num_top_queries
        self.num_classes = num_classes
        self.remap_mscoco_category = remap_mscoco_category
        self.classes = classes
        self.iou_thres = iou_thres

    def forward(self, outputs, orig_target_sizes):

        logits, _boxes = outputs['pred_logits'], outputs['pred_boxes']

        bbox_pred = torchvision.ops.box_convert(_boxes, in_fmt='cxcywh', out_fmt='xyxy')
        bbox_pred *= orig_target_sizes.repeat(1, 2).unsqueeze(1)

        output = [None for _ in range(len(logits))]
        if len(output) >= 2:
            print(1)

        if self.use_focal_loss:
            _scores = F.sigmoid(logits)
            _scores, index = torch.topk(_scores.flatten(1), self.num_top_queries, axis=-1)
            _labels = index % self.num_classes
            index = index // self.num_classes
            _boxes = bbox_pred.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, bbox_pred.shape[-1]))
        else:
            _scores = F.softmax(logits)[:, :, :-1]
            _scores, _labels = _scores.max(dim=-1)
            if _scores.shape[1] > self.num_top_queries:
                _scores, index = torch.topk(_scores, self.num_top_queries, dim=-1)
                _labels = torch.gather(_labels, dim=1, index=index)
                _boxes = torch.gather(_boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, _boxes.shape[-1]))

        mask = _scores > self.iou_thres

        detections = torch.cat((_labels.unsqueeze(-1), _boxes, _scores.unsqueeze(-1)), 2)
        detections = detections[mask]

        if self.remap_mscoco_category:
            from ..src.data.coco import mscoco_label2category
            detections[:,-1] = torch.tensor([mscoco_label2category[int(x.item())] for x in detections[:,0].flatten()])\
                .to(_boxes.device).reshape(detections[:,0].shape)

        if self.classes is not None:
            detections = detections[(detections[:, 0] == torch.tensor(self.classes, device=detections.device))]

        if not detections.size(0):
            return None

        results = []
        for _, dets in enumerate(detections):

            # dets[1:-1] = self.convert_bbox_to_standard(dets, orig_target_sizes)

            # dets[1:-1] = x1, y1, x2, y2
            # # TODO
            # # if i == 1:
            # #     print(1)
            # for _det in dets:
            #     try:
            #         if output[0] is None:
            #             output[0] = _det.unsqueeze(0)
            #     except IndexError:
            #         print(1)
                # else:
            results.append(dets)# = torch.cat((output[i], _det.unsqueeze(0)))
                    # result = dict(labels=lab, boxes=box, scores=sco)
                    # results.append(result)

        if not results:
            return None
        return torch.stack(results)

    def convert_bbox_to_standard(bbox, orig_target_size):
        x1, y1, x2, y2 = bbox[1:-1]
        width, height = orig_target_size

def get_model_info(model: nn.Module, tsize: Sequence[int]) -> str:
    from thop import profile

    stride = 640
    img = torch.zeros((1, 3, stride, stride), device=next(model.parameters()).device)
    flops, params = profile(deepcopy(model), inputs=(img,), verbose=False)
    params /= 1e6
    flops /= 1e9
    flops *= tsize[0] * tsize[1] / stride / stride * 2  # Gflops
    info = "Params: {:.2f}M, Gflops: {:.2f}".format(params, flops)
    return info


import json
import json

import networkx as nx
from ..constants.common.attrs.edge.amr_edge_attrs import AMREdgeAttrs
from ..constants.common.attrs.edge.edge_attrs import EdgeAttrs
from ..constants.common.attrs.edge.syntax_edge_attrs import SyntaxEdgeAttrs
from ..constants.common.attrs.node.modal_node_attrs import ModalNodeAttrs
from ..constants.common.attrs.node.node_attrs import NodeAttrs
from ..constants.common.attrs.node.token_node_attrs import TokenNodeAttrs
from ..constants.common.types.edge_types import EdgeTypes
from ..constants.common.types.node_types import NodeTypes
# import matplotlib.pyplot as plt
from pyvis.network import Network

class GraphViewer:

    def token_node_label (self, G, node):
        if TokenNodeAttrs.text in G.nodes[node]:
            label = G.nodes[node][TokenNodeAttrs.text]
        elif TokenNodeAttrs.upos in G.nodes[node]:
            label = G.nodes[node][TokenNodeAttrs.upos]
        else:
            label = node
        return label

    def mdp_node_label (self, G, node):
        if ModalNodeAttrs.special_name in G.nodes[node] and G.nodes[node][ModalNodeAttrs.special_name] != 'Null':
            label = G.nodes[node][ModalNodeAttrs.special_name]
        elif ModalNodeAttrs.modal_node_type in G.nodes[node]:
            label = G.nodes[node][ModalNodeAttrs.modal_node_type]
        else:
            label = node
        return label

    def prepare_networkx_for_visualization(self, G, root_level=0, invert_graph=False):

        roots = [x for x in G if len(G.in_edges(x)) == 0]

        for root in roots:
            self.add_level_to_syntactic_dependency_parse(G, root, level=root_level)

        for node in G:
            node_type = G.nodes[node].get(NodeAttrs.node_type, None)

            if node_type == NodeTypes.modal:
                 G.nodes[node]['label'] = self.mdp_node_label(G,node)
            elif node_type == NodeTypes.amr:
                if 'content' in G.nodes[node]:
                    G.nodes[node]['label'] = G.nodes[node]['content']
                else:
                    G.nodes[node]['label'] = "ANY_AMR_NODE"
            else:
                G.nodes[node]['label'] = self.token_node_label(G, node)

            node_annotation_status = G.nodes[node].get(NodeAttrs.annotated, None)
            event_status = G.nodes[node].get(NodeAttrs.event_trigger, None)
            mention_status = G.nodes[node].get(NodeAttrs.named_entity, None)
            if node_annotation_status or event_status or mention_status:
                G.nodes[node]['color'] = "pink"
            elif node_type == NodeTypes.modal:
                G.nodes[node]['color'] = "red"
            elif node_type == NodeTypes.amr:
                G.nodes[node]['color'] = "orange"
            else: # node_type == NodeTypes.token
                G.nodes[node]['color'] = "blue"

            if event_status:
                G.nodes[node]['label'] = "EventTrigger"
            elif mention_status:
                G.nodes[node]['label'] = mention_status

        for edge in G.edges:
            edge_type = G.edges[edge].get(EdgeAttrs.edge_type, None)
            if edge_type == EdgeTypes.modal_constituent_token or edge_type == EdgeTypes.amr_aligned_token:
                G.edges[edge]['color'] = "purple"
            else:
                G.edges[edge]['color'] = "blue"
            if AMREdgeAttrs.amr_relation in G.edges[edge]:
                G.edges[edge]["label"] = G.edges[edge][AMREdgeAttrs.amr_relation]
            elif SyntaxEdgeAttrs.dep_rel in G.edges[edge]:
                G.edges[edge]["label"] = G.edges[edge][SyntaxEdgeAttrs.dep_rel]
            else:
                G.edges[edge]["label"] = edge_type

        if invert_graph:
            self.invert_node_levels(G)

    def filter_mdp_networkx_by_sentence (self, G, H):
        F = nx.DiGraph()
        # Loop over the nodes from G that are modal nodes
        token_nodes = [x for x in G.nodes if G.nodes[x].get(NodeAttrs.node_type,None) is None]
        sentence_token_nodes = [x for x in token_nodes if x in H.nodes]

        for node in sentence_token_nodes:
            self.add_node_and_ancestors(node, G, F)

        # Loop over the modal nodes in F and add any direct token children from G
        modal_nodes = [x for x in F.nodes if F.nodes[x].get(NodeAttrs.node_type,None) is NodeTypes.modal]
        for node in modal_nodes:
            for edge in G.out_edges(node):
                parent, child = edge
                if G.nodes[child].get(NodeAttrs.node_type,None) is None:
                    F.add_node(child, **G.nodes[child])
                    F.add_edge(parent,child)
        return F

    def add_node_and_ancestors (self, node, Source, Target):
        Target.add_node(node, **Source.nodes[node])
        for edge in Source.in_edges(node):
            parent, child = edge
            self.add_node_and_ancestors (parent, Source, Target)
            Target.add_edge(parent,child,**Source.edges[edge])

    def get_max_level(self, G):
        max_level = 0
        for node in G.nodes:
            l = G.nodes[node]['level']
            if l >= max_level:
                max_level = l
        return max_level

    def invert_node_levels(self, G):
        min_level = 1000000
        max_level = 0
        for node in G.nodes:
            l = G.nodes[node]['level']
            if l <= min_level:
                min_level = l
            if l >= max_level:
                max_level = l
        for node in G.nodes:
            l = G.nodes[node]['level']
            G.nodes[node]['level'] = max_level - l + min_level

    def adjust_level(self, G, n):
        for node in G.nodes:
            G.nodes[node]['level'] += n

    def add_level_to_syntactic_dependency_parse (self, G, node, level=0):
        G.nodes[node]['level'] = level
        for child in G[node]:
            self.add_level_to_syntactic_dependency_parse (G, child, level=level+1)

    def visualize_networkx_graph(self, G, html_file="graph.html", sentence_text=None):
        if sentence_text is not None:
            net = Network(height='1000px', width='1800px', directed=True, layout=True, heading=sentence_text)
        else:
            net = Network(height='1000px', width='1800px', directed=True, layout=True)
        net.from_nx(G, show_edge_weights=False)

        net.toggle_physics(False)

        # warning: due to bug in pyvis, using show_buttons and set_options together
        # throws an error.
        # net.show_buttons(filter_=['physics'])
        # net.show_buttons(True)
        self.set_node_spacing(net, 160, show_buttons=False)

        net.write_html(html_file)

    def set_node_spacing(self, net, node_spacing, show_buttons=False):
        json_dict = {
            # warning: due to bug in pyvis, you must include configure
            "configure": {
                "enabled": show_buttons
            },
            "layout": {
                "hierarchical": {
                    "enabled": True,
                    "nodeSpacing": node_spacing,
                    # "treeSpacing": 290
                }
            },
            "physics": {
                "enabled": False,
                "hierarchicalRepulsion": {
                    "centralGravity": 0
                },
                "minVelocity": 0.75,
                "solver": "hierarchicalRepulsion"
            }
        }
        json_dump = json.dumps(json_dict)
        new_options = "var options = {}".format(json_dump)
        # print(new_options)
        net.set_options(new_options)

# Support function to build a simple graph of tokens in a sentence.
# Consists of root node with token children in surface string order
def token_sequence_to_networkx(sentence):
    '''
    :param serif_sentence: serif.theory.sentence.Sentence
    :return: networkx.classes.digraph.DiGraph.
    '''
    G = nx.DiGraph()

    # Root node
    root_id = "Tokens"
    G.add_node(root_id)
    for token in sentence.token_sequence:
        token_id = "{}__{}".format(token.text, token.id)
        G.add_node(token_id)
        G.add_edge(root_id,token_id)

    return G


from multiprocessing import Process, JoinableQueue
import time, os

# 生产者
def producer(q, name):
    for i in range(3):
        time.sleep(1)
        res = '%s%s' % (name, i)
        q.put(res)
        print('\033[45m<%s> 生产了 [%s]\033[0m' % (os.getpid(), res))
    q.join()  # 等消费者取完就结束

# 消费者
def consumer(q):
    while True:
        res = q.get()
        time.sleep(1.5)
        print('\033[34m<%s> 吃了 [%s]\033[0m' % (os.getpid(), res))
        q.task_done()  # 每取走一个就记一次

if __name__ == '__main__':
    q = JoinableQueue()

    # 生产者们：即厨师们
    p1 = Process(target=producer, args=(q, '包子'))
    # p2 = Process(target=producer, args=(q, '饺子'))
    # p3 = Process(target=producer, args=(q, '馄饨'))

    # 消费者们：即吃货们
    c1 = Process(target=consumer, args=(q,))
    c2 = Process(target=consumer, args=(q,))

    c1.daemon = True  # 设为守护进程，当主进程结束，消费者进程也随之结束
    c2.daemon = True  # 设为守护进程，当主进程结束，消费者进程也随之结束
    p1.start()
    # p2.start()
    # p3.start()
    c1.start()
    c2.start()

    p1.join()  # 主进程等生产者结束

    print('主')


# IMPORT LIBRARIES
# % matplotlib inline # decirle que meta los graficos en el jupnot itself
import numpy as np # import numpy library as np
import matplotlib.pyplot as plt # import pyplot library as plt
plt.style.use('ggplot') # use "ggplot" style for graphs

x = np.linspace(-3, 3) # create array of x from -3 to 3
y = np.sin(x) # create array of sin(x)
plt.plot(x, y) # plot y vs. x
plt.show() # display plot


import unittest, argparse, sys, time
from eosfactory.eosf import *
from eosfactory.core import *

verbosity([Verbosity.INFO, Verbosity.OUT, Verbosity.TRACE, Verbosity.DEBUG])

CONTRACT_WORKSPACE = sys.path[0] + "/../"

INITIAL_RAM_KBYTES = 8
INITIAL_STAKE_NET = 3
INITIAL_STAKE_CPU = 3

class Test(unittest.TestCase):

    def stats():
        print_stats(
            [master, host, piggybankbag, alice, carol,piggybankout],
            [
                "core_liquid_balance",
                "ram_usage",
                "ram_quota",
                "total_resources.ram_bytes",
                "self_delegated_bandwidth.net_weight",
                "self_delegated_bandwidth.cpu_weight",
                "total_resources.net_weight",
                "total_resources.cpu_weight",
                "net_limit.available",
                "net_limit.max",
                "net_limit.used",
                "cpu_limit.available",
                "cpu_limit.max",
                "cpu_limit.used"
            ]
        )

    @classmethod
    def setUpClass(cls):
        SCENARIO('''
        There is the ``master`` account that sponsors the ``piggybankbag``
        account equipped with an instance of the ``piggybank`` smart contract. There
        are three players ``alice`` , ``carol`` and ``piggybankout``. We are testing that they make correct bets and winner get rewards.
        ''')

        testnet.verify_production()

        if  testnet.is_local():
            reset()

        create_master_account("master", testnet)
        if  testnet.is_local():
            create_account("piggybankbag", master,"piggybankbag",
            buy_ram_kbytes=INITIAL_RAM_KBYTES, stake_net=INITIAL_STAKE_NET, stake_cpu=INITIAL_STAKE_CPU)
        create_account("host", master,"eosio.token",
                       buy_ram_kbytes=INITIAL_RAM_KBYTES, stake_net=INITIAL_STAKE_NET, stake_cpu=INITIAL_STAKE_CPU)
        create_account("alice", piggybankbag,
            buy_ram_kbytes=INITIAL_RAM_KBYTES, stake_net=INITIAL_STAKE_NET, stake_cpu=INITIAL_STAKE_CPU)
        create_account("carol", piggybankbag,
            buy_ram_kbytes=INITIAL_RAM_KBYTES, stake_net=INITIAL_STAKE_NET, stake_cpu=INITIAL_STAKE_CPU)
        create_account("piggybankout", piggybankbag,"piggybankout",
            buy_ram_kbytes=INITIAL_RAM_KBYTES, stake_net=INITIAL_STAKE_NET, stake_cpu=INITIAL_STAKE_CPU)

        if not testnet.is_local():
            cls.stats()

        contract = Contract(piggybankbag, CONTRACT_WORKSPACE)
        contract.build(force=False)

        if testnet.is_local():
            tokenContract =  Contract(host, CONTRACT_WORKSPACE+"../eosio.contracts/build/eosio.token")
            tokenContract.build(force=False)
            tokenContract.deploy(payer=master)

        try:
            contract.deploy(payer=master)
        except errors.ContractRunningError:
            pass

    def setUp(self):
        pass

    def test_01(self):

        COMMENT('''
        Issue and transfer EOS for test purpuses.
        ''')

        if  testnet.is_local():
            host.push_action(
            "create",
            {
                "issuer": master,
                "maximum_supply": "1000000000.0000 EOS",
                "can_freeze": "0",
                "can_recall": "0",
                "can_whitelist": "0"
            },
            permission=[(master, Permission.OWNER), (host, Permission.ACTIVE)])

            host.push_action(
            "issue",
            {
                "to": alice, "quantity": "100.0000 EOS", "memo": ""
            },
            master)

            host.push_action(
            "issue",
            {
                "to": piggybankout, "quantity": "100.0000 EOS", "memo": ""
            },
            master)

            host.push_action(
            "issue",
            {
                "to": carol, "quantity": "100.0000 EOS", "memo": ""
            },
            master)

            host.table("accounts", alice)

            host.table("accounts", carol)
            host.table("accounts", piggybankout)

        COMMENT('''
        Init of the contract:
        WARNING: This action should fail due to authority mismatch!
        ''')
        with self.assertRaises(MissingRequiredAuthorityError):
            piggybankbag.push_action(
                "initcontract", {"user":alice}, permission=(alice, Permission.ACTIVE))

        COMMENT('''
        Attempting to init contract.
        ''')

        piggybankbag.push_action(
            "initcontract", {"user":piggybankbag}, permission=(piggybankbag, Permission.ACTIVE))

        try:
            host.push_action(
                "transfer",
                {
                    "from": alice, "to": piggybankbag,
                    "quantity": "0.5000 EOS", "memo":""
                },
                alice)
        except Error as e:
            if "Bet is incorrect. Please check rules" in e.message:
                COMMENT('''
                Bet should be correct bet.
                ''')

        COMMENT('''
        Transfer first transaction and start game.
        ''')

        host.push_action(
        "transfer",
        {
            "from": alice, "to": piggybankbag,
            "quantity": "1.0000 EOS", "memo":""
        },
        alice)

        time.sleep(3)
        table_activebets =  piggybankbag.table("activebets", piggybankbag)
        table_globalvars = piggybankbag.table("globalvars", piggybankbag)
        table_piggybankbag = host.table("accounts", piggybankbag)
        table_piggybankout = host.table("accounts", piggybankout)
        self.assertEqual(
            table_piggybankbag.json["rows"][0]["balance"], '0.8500 EOS',
        '''assertEqual(table_alice.json["rows"][0]["balance"], '0.8500 EOS')''')
        self.assertEqual(
            table_activebets.json["rows"][0]["bettor"], 'alice',
            '''assertEqual(table_bob.json["rows"][0]["bettor"], 'alice')''')
        self.assertEqual(
        table_activebets.json["rows"][0]["bet_amt"], '10000',
        '''assertEqual(table_bob.json["rows"][0]["bet_amt"], '10000')''')
        self.assertEqual(
            table_piggybankout.json["rows"][0]["balance"], '0.1500 EOS',
            '''assertEqual(table_bob.json["rows"][0]["balance"], '0.1500 EOS')''')
        self.assertEqual(
            table_globalvars.json["rows"][0]["winner"], 'alice',
            '''assertEqual(table_bob.json["rows"][0]["winner"], 'alice')''')
        self.assertEqual(
            table_globalvars.json["rows"][0]["amount"], '10000',
            '''assertEqual(table_bob.json["rows"][0]["amount"], '10000')''')
        self.assertEqual(
            table_globalvars.json["rows"][0]["is_Active"], '1',
            '''assertEqual(table_bob.json["rows"][0]["is_Active"], '1')''')

        COMMENT('''
        Attempting to put wrong bet contract.
        ''')

        try:
            host.push_action(
                "transfer",
                {
                    "from": alice, "to": piggybankbag,
                    "quantity": "0.5000 EOS", "memo":""
                },
                alice)
        except Error as e:
            if "Bet is incorrect. Please check rules" in e.message:
                COMMENT('''
                Bet should be correct bet.
                ''')
            else:
                COMMENT('''
                The error is different than expected.
                ''')
                raise Error(str(e))

        COMMENT('''
        Put second bet.
        ''')

        host.push_action(
            "transfer",
            {
                "from": carol, "to": piggybankbag,
                "quantity": "10.0000 EOS", "memo":"test -alice"
            },
            carol)

        table_activebets = piggybankbag.table("activebets", piggybankbag)
        table_globalvars = piggybankbag.table("globalvars", piggybankbag)
        table_piggybankbag = host.table("accounts", piggybankbag)
        table_piggybankout = host.table("accounts", piggybankout)
        table_alice = host.table("accounts", alice)
        self.assertEqual(
         table_piggybankbag.json["rows"][0]["balance"], '9.3500 EOS',
            '''assertEqual(table_alice.json["rows"][0]["balance"], '9.3500 EOS')''')
        self.assertEqual(
         table_activebets.json["rows"][1]["bettor"], 'carol',
         '''assertEqual(table_bob.json["rows"][0]["bettor"], 'carol')''')
        self.assertEqual(
          table_activebets.json["rows"][1]["bet_amt"], '100000',
          '''assertEqual(table_bob.json["rows"][0]["bet_amt"], '100000')''')
        self.assertEqual(
         table_piggybankout.json["rows"][0]["balance"], '101.1500 EOS',
          '''assertEqual(table_bob.json["rows"][0]["balance"], '101.1500 EOS')''')
        self.assertEqual(
          table_globalvars.json["rows"][0]["winner"], 'carol',
          '''assertEqual(table_bob.json["rows"][0]["winner"], 'carol')''')
        self.assertEqual(
          table_globalvars.json["rows"][0]["amount"], '110000',
          '''assertEqual(table_bob.json["rows"][0]["amount"], '110000')''')
        self.assertEqual(
          table_globalvars.json["rows"][0]["is_Active"], '1',
          '''assertEqual(table_bob.json["rows"][0]["is_Active"], '1')''')
        self.assertEqual(
            table_alice.json["rows"][0]["balance"], '99.5000 EOS',
            '''assertEqual(table_bob.json["rows"][0]["balance"], '99.5000 EOS')''')

        try:
            host.push_action(
                "transfer",
                {
                    "from": alice, "to": piggybankbag,
                    "quantity": "7.0000 EOS", "memo":""
                },
                alice)
        except Error as e:
            if "Bet is incorrect. Please check rules" in e.message:
                COMMENT('''
                Bet should be correct bet.
                ''')
            else:
                COMMENT('''
                The error is different than expected.
                ''')
                raise Error(str(e))

        COMMENT('''
        Check winner method.
        ''')

        piggybankbag.push_action(
            "paywinner", {"user":alice})

        table_globalvars = piggybankbag.table("globalvars", piggybankbag)
        self.assertEqual(
            table_globalvars.json["rows"][0]["is_Active"], '0',
            '''assertEqual(table_bob.json["rows"][0]["is_Active"], '1')''')
        table_carol = host.table("accounts", carol)
        self.assertEqual(
            table_carol.json["rows"][0]["balance"], '109.3500 EOS',
            '''assertEqual(table_alice.json["rows"][0]["balance"], '109.3500 EOS')''')
        table_piggybankbag = host.table("accounts", piggybankbag)
        self.assertEqual(
        table_piggybankbag.json["rows"][0]["balance"], '0.0000 EOS',
        '''assertEqual(table_alice.json["rows"][0]["balance"], '0.0000 EOS')''')

        COMMENT('''
        Check new game created.
        ''')

        host.push_action(
            "transfer",
            {
                "from": alice, "to": piggybankbag,
                "quantity": "10.0000 EOS", "memo":""
            },
            alice)

    time.sleep(3)
    table_activebets =  piggybankbag.table("activebets", piggybankbag)
    table_globalvars = piggybankbag.table("globalvars", piggybankbag)
    table_piggybankbag = host.table("accounts", piggybankbag)
    table_piggybankout = host.table("accounts", piggybankout)
    self.assertEqual(
        table_piggybankbag.json["rows"][0]["balance"], '9.8500 EOS',
        '''assertEqual(table_alice.json["rows"][0]["balance"], '9.8500 EOS')''')
    self.assertEqual(
        table_activebets.json["rows"][0]["bettor"], 'alice',
        '''assertEqual(table_bob.json["rows"][0]["bettor"], 'alice')''')
    self.assertEqual(
        table_activebets.json["rows"][0]["bet_amt"], '100000',
        '''assertEqual(table_bob.json["rows"][0]["bet_amt"], '100000')''')
    self.assertEqual(
        table_piggybankout.json["rows"][0]["balance"], '109.6500 EOS',
        '''assertEqual(table_bob.json["rows"][0]["balance"], '109.6500 EOS')''')
    self.assertEqual(
        table_globalvars.json["rows"][1]["winner"], 'alice',
        '''assertEqual(table_bob.json["rows"][0]["winner"], 'alice')''')
    self.assertEqual(
        table_globalvars.json["rows"][1]["amount"], '100000',
        '''assertEqual(table_bob.json["rows"][0]["amount"], '100000')''')
    self.assertEqual(
        table_globalvars.json["rows"][1]["is_Active"], '1',
        '''assertEqual(table_bob.json["rows"][0]["is_Active"], '1')''')

    def tearDown(self):
        pass

    @classmethod
    def tearDownClass(cls):
        if testnet.is_local():
            stop()
        else:
            cls.stats()

testnet = None

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='''
    This is a unit test for the ``piggybank`` smart contract.
    It works both on a local testnet and remote testnet.
    The default option is local testnet.
    ''')

    parser.add_argument(
        "alias", nargs="?",
        help="Testnet alias")

    parser.add_argument(
        "-t", "--testnet", nargs=4,
        help="<url> <name> <owner key> <active key>")

    parser.add_argument(
        "-r", "--reset", action="store_true",
        help="Reset testnet cache")

    args = parser.parse_args()

    testnet = get_testnet(args.alias, args.testnet, reset=args.reset)
    testnet.configure()

    if args.reset and not testnet.is_local():
        testnet.clear_cache()

    unittest.main(argv=[sys.argv[0]])


import os
import sys

from ..plugin import Plugin

class Clean(Plugin):
    """
    Cleans broken symbolic links.
    """

    _directive = "clean"

    def can_handle(self, directive):
        return directive == self._directive

    def handle(self, directive, data):
        if directive != self._directive:
            raise ValueError("Clean cannot handle directive %s" % directive)
        return self._process_clean(data)

    def _process_clean(self, targets):
        success = True
        defaults = self._context.defaults().get(self._directive, {})
        for target in targets:
            force = defaults.get("force", False)
            recursive = defaults.get("recursive", False)
            if isinstance(targets, dict) and isinstance(targets[target], dict):
                force = targets[target].get("force", force)
                recursive = targets[target].get("recursive", recursive)
            success &= self._clean(target, force, recursive)
        if success:
            self._log.info("All targets have been cleaned")
        else:
            self._log.error("Some targets were not successfully cleaned")
        return success

    def _clean(self, target, force, recursive):
        """
        Cleans all the broken symbolic links in target if they point to
        a subdirectory of the base directory or if forced to clean.
        """
        if not os.path.isdir(os.path.expandvars(os.path.expanduser(target))):
            self._log.debug("Ignoring nonexistent directory %s" % target)
            return True
        for item in os.listdir(os.path.expandvars(os.path.expanduser(target))):
            path = os.path.abspath(
                os.path.join(os.path.expandvars(os.path.expanduser(target)), item)
            )
            if recursive and os.path.isdir(path):
                # isdir implies not islink -- we don't want to descend into
                # symlinked directories. okay to do a recursive call here
                # because depth should be fairly limited
                self._clean(path, force, recursive)
            if not os.path.exists(path) and os.path.islink(path):
                points_at = os.path.join(os.path.dirname(path), os.readlink(path))
                if sys.platform[:5] == "win32" and points_at.startswith("\\\\?\\"):
                    points_at = points_at[4:]
                if self._in_directory(path, self._context.base_directory()) or force:
                    self._log.lowinfo("Removing invalid link %s -> %s" % (path, points_at))
                    os.remove(path)
                else:
                    self._log.lowinfo("Link %s -> %s not removed." % (path, points_at))
        return True

    def _in_directory(self, path, directory):
        """
        Returns true if the path is in the directory.
        """
        directory = os.path.join(os.path.realpath(directory), "")
        path = os.path.realpath(path)
        return os.path.commonprefix([path, directory]) == directory


"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统： Ubuntu 18.04
IDE:  VS Code 1.36
工具： python == 3.7.3
"""

"""
思路:
    先用set从长度上判断
    然后再用字典进行判别
结果：
    执行用时 : 56 ms, 在所有 Python3 提交中击败了91.68%的用户
    内存消耗 : 13.2 MB, 在所有 Python3 提交中击败了87.42%的用户
"""

class Solution:
    def isIsomorphic(self, s, t):
        d = {}
        if len(set(s)) != len(set(t)) or len(s) != len(t):
            return False
        for i in range(len(s)):
            if d.__contains__(s[i]):
                if d[s[i]] != t[i]:
                    return False
                else:
                    continue
            d[s[i]] = t[i]
        return True

if __name__ == "__main__":
    s = "ab"
    t = "aa"
    answer = Solution().isIsomorphic(s, t)
    print(answer)


# 18강 시작!
# AND, OR, NAND, XOR 논리테이블(Logic Table)은 입력데이터 (x1,x2), 정답데이터 t (0 또는 1)
# 인 머신러닝 Training Data와 개념적으로 동일함
# -> 즉, 논리게이트는 손실함수로 cross-entropy를 이용해서 Logistic Regression (Classification)
# 알고리즘으로 데이터를 분류하고 결과를 예측할 수 있음

# AND연산을 살펴보면
# X1, X2 값이 REGRESSION X*W+b를 만들고 sigmoid 함수를 이용해 y = sigmoid(z) 식이 만들어진다.

# LogicGate Class - AND, OR, NAND, XOR 검증방법
import numpy as np

# 1. external function
def sigmoid(x): # 0또는 1을 출력하기 위한 sigmoid 함수
    return 1/(1+np.exp(-x))
def numerical_derivative(f,x): # 수치미분함수
    delta_x = 1e-4
    grad = np.zeros_like(x)

    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])

    while not it.finished:
        idx = it.multi_index
        tmp_val = x[idx]
        x[idx] = float(tmp_val)+delta_x
        fx1 = f(x)
        x[idx] = float(tmp_val)-delta_x
        fx2 = f(x)

        grad[idx] = (fx1-fx2) / (2*delta_x)
        x[idx] = tmp_val
        it.iternext()

    return grad

# 2.LogicGate Class
class LogicGate:
    def __init__(self, gate_name, xdata, tdata): #___xdata, __tdata, __W, __b 초기화
        self.name = gate_name

        #이제부터 모두 __으로 private 선언
        # 입력 데이터, 정답 데이터 초기화
        self.__xdata = xdata.reshape(4,2)
        self.__tdata = tdata.reshape(4,1)

        # 가중치 W, 바이어스 b 초기화
        self.__W = np.random.rand(2,1)
        self.__b = np.random.rand(1)

        # 학습율 learning_rate 초기화
        # 만약 손실함수계산중에 최소값이 안나오고 발산하면 더 작은값으로 세팅해줘야 함
        self.__learning_rate = 1e-2

    # 손실함수
    def __loss_func(self):  # 손실함수 cross-entropy

        delta = 1e-7 # log 값 무한대 발산 방지

        z = np.dot(self.__xdata, self.__W) + self.__b
        y = sigmoid(z)

        #cross-entropy
        return -np.sum(self.__tdata*np.log(y+delta) + (1- self.__tdata)*np.log((1-y)+delta))

    def error_val(self): # 손실함수 값 계산
        delta = 1e-7 # log 값 무한대 발산 방지

        z = np.dot(self.__xdata, self.__W) + self.__b
        y = sigmoid(z)

        #cross-entropy
        return -np.sum(self.__tdata*np.log(y+delta) + (1-self.__tdata)*np.log((1-y)+delta))

    def train(self): # 수치미분을 이용하여 손실함수 최소값 찾는 method
        f = lambda x : self.__loss_func()
        print("Initial error value = ", self.error_val())
        for step in range(8001):
            self.__W -= self.__learning_rate * numerical_derivative(f, self.__W)
            self.__b -= self.__learning_rate * numerical_derivative(f, self.__b)
            if (step % 100 == 0):
                print("step = ", step, "error value = ", self.error_val())
    def predict(self, input_data): # 미래값 예측 method
        z = np.dot(input_data, self.__W) + self.__b
        y = sigmoid(z)

        if y > 0.5:
            result = 1 #True
        else:
            result = 0 #False

        return y, result
# 3.usage
# AND Gate 검증
xdata = np.array([[0,0],[0,1],[1,0],[1,1]]) #입력데이터 생성
tdata = np.array([0,0,0,1]) #정답 데이터 생성 (AND 예시)

AND_obj = LogicGate("AND_GATE",xdata,tdata) #LogicGate 객체생성
AND_obj.train() #손실함수 최소값 갖도록 학습

#임의 데이터에 대해 결과 예측
print(AND_obj.name, "\n")
test_data = np.array([[0,0],[0,1],[1,0],[1,1]])
for input_data in test_data:
    (sigmoid_val, logical_val) = AND_obj.predict(input_data)
    print(input_data, "=",logical_val,"\n")

#OR Gate 검증
xdata = np.array([[0,0],[0,1],[1,0],[1,1]]) #입력데이터 생성
tdata = np.array([0,1,1,1]) #정답 데이터 생성 (or 예시)
OR_obj = LogicGate("OR_GATE",xdata,tdata)
OR_obj.train()

print(OR_obj.name,"\n")
test_data = np.array([[0,0],[0,1],[1,0],[1,1]])
for input_data in test_data:
    (sigmoid_val, logical_val) = OR_obj.predict(input_data)
    print(sigmoid_val,"    ",input_data, "=",logical_val,"\n")

# NAND Gate 검증
xdata = np.array([[0,0],[0,1],[1,0],[1,1]]) #입력데이터 생성
tdata = np.array([1,1,1,0]) #정답 데이터 생성 (AND 예시)

NAND_obj = LogicGate("NAND_GATE",xdata,tdata) #LogicGate 객체생성
NAND_obj.train() #손실함수 최소값 갖도록 학습

#임의 데이터에 대해 결과 예측
print(NAND_obj.name, "\n")
test_data = np.array([[0,0],[0,1],[1,0],[1,1]])
for input_data in test_data:
    (sigmoid_val, logical_val) = NAND_obj.predict(input_data)
    print(input_data, "=",logical_val,"\n")

#XOR Gate 검증
xdata = np.array([[0,0],[0,1],[1,0],[1,1]]) #입력데이터 생성
tdata = np.array([0,1,1,0]) #정답 데이터 생성 (or 예시)
XOR_obj = LogicGate("OR_GATE",xdata,tdata)
XOR_obj.train()

print(XOR_obj.name,"\n")
test_data = np.array([[0,0],[0,1],[1,0],[1,1]])
for input_data in test_data:
    (sigmoid_val, logical_val) = XOR_obj.predict(input_data)
    print(sigmoid_val,"    ",input_data, "=",logical_val,"\n")

# XOR GATE는 LOGISTIC REGRESSION 알고리즘으로는 데이터를 분류할 수 없어보인다..!!
# 0,1 이 들어간 각각의 입력값에 NAND와 OR을 한 데이터 생성후 두 부류의 데이터에
# AND 연산을 가하면 XOR 출력이 가능하다!!

input_data = np.array([[0,0],[0,1],[1,0],[1,1]])

s1 = []  # NAND 출력
s2 = []  # OR 출력

new_input_data = [] # AND 입력
fianl_output = [] # AND 출력

for index in range(len(input_data)):

    s1 = NAND_obj.predict(input_data[index]) # NAND 출력
    s2 = OR_obj.predict(input_data[index])

    new_input_data.append(s1[-1])
    new_input_data.append(s2[-1])

    (sigmoid_val, logical_val) = AND_obj.predict(np.array(new_input_data))

    fianl_output.append(logical_val)
    new_input_data = []

for index in range(len(input_data)):
    print(input_data[index], "=", fianl_output[index], end='')
    print('\n')

# 머신러닝 XOR 문제는 다양한 Gate 조합인 Multi-Layer로 해결할 수 있음
# Layer : 데이터를 처리하거나 계산이 이루어 지는 단위
# 각각의 Gate(NAND, OR, AND)는 Logistic Regression(Classification) 시스템으로 구성됨
# 이전 Gate 모든 출력은 (previous output) 다음 Gate 입력 (next input)으로 들어감

# => insight => 신경망(Neural Network)기반의 딥러닝(Deep Learning)의 핵심 아이디어!!!

# 19강 시작!!
# Review - XOR문제
# 1개의 LOGOISTIC REGRESSION 으로 구현된 XOR은 잘 작동하지않음!
# 따라서 여러개의 Logistic Regression으로 구현된 XOR은 잘 작동한다.
# 이러한 과정은 인간의 신경세포 뉴런(neuron)으로 연결된 신경망 동작원리와 유사함!

# 신경망(Neural Network) - concept(1)
# >신경 세포 뉴런(neuron)은 이전 뉴런으로부터 입력신호를 받아 또 다른 신호를 발생시킨다.
# >그러나 입력에 비례해서 출력을 나타내는 형태 (y=Wx)가 아니라, 입력 값들의 모든 합이
# 어느 임계점(threshold)에 도달해야만 출력 신호를 발생시킨다.
# >이처럼 입력신호를 받아 특정 값의 임계점을 넘어서는 경우에, 출력을 생성해주는 함수를
# 활성화 함수(activation function)라고 하는데, 지금까지 사용해왔던 Logistic Regression 시스템의
# sigmoid 함수가 대표적인 활성화함수이다. 즉, sigmoid에서의 임계점은 0.5로서, 입력값 합이
# 0.5 보다 크다면 1을 출력으로 내보내고, 0.5 보다 값이 작으면 출력을 내보내지 않는다고 볼 수 있다.
# (0은 출력이 없는 상태)
# 활성화함수의 종류 - Sigmoid, ReLU, Leaky ReLU, tangent(tanh)...

# 신경망(Neural Network) - concept(2)
# 인간의 신경 세포인 뉴런 동작원리를 머신러닝에 적용하기 위해서는,
# 1. 입력 신호와 가중치를 곱하고 적당한 바이어스를 더한 후(Linear Regression)
# 2. 이 값을 활성화 함수(sigmoid) 입력으로 전달(Classification) 해서 sigmoid함수
# 임계점 0.5를 넘으면 1을, 아니면 0을 다음 뉴런으로 전달해주어
# multi-variable Logistic Regression 시스템을 구축한다.
# ->입력값이 여러개의 logistic regression을 거쳐서 출력값을 생성함

# 딥러닝(Deep Learning) - concept
# 노드(node) : 1개의 logistic regression을 나타냄
# 노드가 연결되어 있는 신경망 구조를 바탕으로 입력층(Input Layer),
# 1개 이상의 은닉층(Hidden Layer), 출력층(Output Layer)을 구축하고, 출력층(Output Layer)에서의
# 오차를 기반으로 각 노드(뉴런)의 가중치(Weight)를 학습하는 머신러닝 한 분야

# 참고) 딥러닝 구조에서 1개 이상의 은닉층(hidden layer)을 이용하여 학습시키면 정확도가
# 높은 결과를 얻을 수 있다고 알려져 있음, 즉 은닉층을 깊게(Deep) 할수록 정확도가 높아진다고
# 해서 딥(Deep)러닝이라는 용어가 사용되고 있다.

# 가중치 W21 => 특정 계층의 노드 1에서 다음계층의 노드 2로 전달 되는 신호를 강화 또는
# 약화 시키는 가중치(즉, 다음계층의 노드 번호가 먼저 나옴)
# 만약 Wmn이면 n에서 m으로 전달되는 신호를 강화 약화시키는 가중치!

# 이러한 가중치 값들은, 층과 층사이의 모든 노드에 초기화 되어 있으며, 데이터가 입력층에서
# 출력층으로 전파(propagation) 될 때, 각 층에 있는 노드의 모든 가중치(W11,W12,...Wlk등)는
# 신호를 약화시키거나(낮은 가중치) 또는 신호를 강화(높은 가중치)시키며, 최종적으로는
# 오차가 최소 값이 될 때 최적의 값을 가지게 됨.

# 20강 시작!
# 신경망에서 데이터를 입력층부터 최종 출력으로 전달하는 방식인 feed forward와
# 출력층에서 손실함수 값을 바탕으로 신경망에 가중치 w와 바이어스 b를 업데이트 하는방법에 대해 알아볼예정

# 아키텍처 비교 - logistic regression vs. deep learning
# 1. logistic regression은 input 데이터를 regression으로 바꿔주고
# classification sigmoid(z)를 거쳐서 결과값을 출력함 output
# 2. 신경망을 기반으로 한 Deep learning은 입력층 한개, 여러개의 은닉층, 출력층 한개로
# 각각의 층에는 내부적으로 logistic regression이 구현된 여러개의 노드들로 구현되어있다.
# 은닉층에서의 이전층의 출력이 다음층의 입력으로 들어가는 구조로 되어 있으며
# 이처럼 데이터가 지속적으로 전달되는 흐름을 feed foward 방식이라고 한다!

# 피드포워드 (feed forward) - 표기법(notation)
# 가장 기본적으로 3개의 층과 각 층에 두개의 노드로 구성된 신경망을 생각해보자.
# 1. 계층간 가중치 표기법 (weight notation)
# 가중치 w(2)21 => 계층 2의 노드에 적용되는 가중치로서, 1계층의 노드 1에서 2계층의 노드 2로
# 전달되는 신호를 강화 또는 약화시키는 가중치(즉, 가중치에서의 아래숫자는 다음계층의 노드 번호가 먼저 나옴)
# 2. 노드의 바이어스 표기법 (bias notation)
# 바이어스 b(2)1 => 계층 2에 있는 첫번째 노드(node 1)에 적용되는 바이어스
# 3. 노드의 선형회귀 계산 값 표기법 (linear regression notation)
# 선형회귀 계산값 z(2)2 => 계층 2의 두번째 노드(node 2) 선형회귀 계산 값
# 풀어쓰면 (z(2)2 = x1w(2)21 + x2w(2)22 + b(2)2) 가 된다.
# 4. 노드의 출력 표기법 (node output notation)
# 노드의 출력 값 a(2)2 => 계층 2의 두번째 노드 (node 2) 출력값으로서, logistic regression 계산 값.
# 활성화함수(activation function)로서 sigmoid를 사용한다면 a(2)2 = sigmoid(z(2)2)가 된다.

# 피드포워드 (feed forward) - 동작방식(1)
# 피드포워드란? 입력층(input layer)으로 데이터가 입력되고, 1개 이상으로 구성되는
# 은닉층(hidden layer)을 거쳐서 마지막에 있는 출력 층(output layer)으로 출력 값을 내보내는 과정
# 딥러닝에서는 이전 층(pervious layer)에서 나온 출력 값 => 층과 층 사이에 적용되는
# 가중치(weight) 영향을 받은 다음 => 다음 층(next layer)의 입력 값으로 들어가는 것을 의미함

# 입력 층(input layer) 출력이란? 딥러닝 입력 층에서는 활성화 함수인 sigmoid를
# 적용하지 않고, 입력 값 그대로 출력으로 내보내는 것이 관례화 되어 있음.
# 예시) a(1)1 = x1, a(1)2 = x2 행렬식으로 표현하면 (a(1)1 a(1)2) = (x1 x2)

# 피드포워드 (feed forward) - 동작방식(2)
# 은닉 층(hidden layer)에서의 선형회귀값 z1 z2는 각각
# z(2)1 = a(1)1*W(2)11 + a(1)2*W(2)12 + b(2)1
# z(2)2 = a(1)1*W(2)21 + a(1)2*W(2)22 + b(2)2
# 이러한 값을 행렬식으로 바꿔준다! (1*2 a입력층값)dot(2*2 W가중치값)+(1*2 b바이어스)
# 은닉 층(hidden layer) 출력
# a(2)1 = sigmoid(z(2)1)

# 피드포워드 (feed forward) - 동작방식(3)
# 츨력층(output layer) 선형회귀 값
# 일반식 : z(3)1 = a(2)1*w(3)11 + a(2)2*w(3)12 + b(3)1
# 행렬식 : (z(3)1) = (1*2의 a은닉층값)dot(2*1 W가중치값)+(1*1 b바이어스)

# 출력 층 (output layer) 출력
# y = a(3)1 = sigmoid(z(3)1)
# 출력값 a1은, 입력 데이터에 대해 최종적으로 계산해야 하는 y값 이며, 이러한 y값과
# 정답 t 와의 차이인 오차(loss)를 통해서 가중치와 바이어스를 학습해야 하는것을 의미함

# ***즉 딥러닝 에서는 출력 층(output layer)에서의 출력값(y)과 정답(t)과의 차이를 이용하여,
# 오차가 최소가 되도록 각 층에 있는 가중치와 바이어스를 최적화 해야 함

# 딥러닝 에서의 [W,b] 계산 프로세스
# 1.input 2.feed forward 3.y(E(W,b)가 최소값이면 학습종료 아니면 4.수행)
# 4.update W(2),b(2),W(3),b(3) => repeat(1.)


from django.shortcuts import render,redirect,HttpResponse,reverse
from crm import models
from crm.forms import ConsultForm
from django.views import View

from django.db.models import Q

from crm.utils.pagination import Pagination

from crm.utils.urls import reverse_url

class Consultlist(View):

    def get(self, request,customer_id):
        # query = request.GET.get('query', '')

        q = self.search([])
        if customer_id == '0':
            all_consult = models.ConsultRecord.objects.filter(q,delete_status=False,
                                                              consultant=request.user_obj).order_by('-date')

        else:
            all_consult = models.ConsultRecord.objects.filter(q,delete_status=False,
                                                              consultant=request.user_obj,customer_id=customer_id).order_by('-date')

        page = Pagination(request.GET.get('page'),request.GET.copy(),all_consult.count(),2)

        return render(request, 'consult_list.html',{'all_consult': all_consult[page.start:page.end], 'page_html': page.page_html})

    def post(self, request,customer_id):
        action = request.POST.get('action')

        if not hasattr(self, action):
            return HttpResponse('非法操作')
        getattr(self, action)()
        return self.get(request,customer_id)

    def search(self, filed_list):
        query = self.request.GET.get('query', '')
        # q = Q(Q(qq__contains=query) | Q(name__contains=query))
        q = Q()
        q.connector = 'OR'
        for field in filed_list:
            # q.children.append(Q(qq__contains=query))
            q.children.append(Q(('{}__contains'.format(field), query)))
        return q

def add_consult(request):
    obj = models.ConsultRecord(consultant=request.user_obj)

    form_obj = ConsultForm(instance=obj)

    if request.method == 'POST':
        form_obj = ConsultForm(request.POST,instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse_url(request,'consult_list'))

    return render(request,'add_consult.html',{'form_obj':form_obj})

def edit_consult(request,edit_id):
    obj = models.ConsultRecord.objects.filter(pk=edit_id).first()

    form_obj = ConsultForm(instance=obj)

    if request.method == 'POST':
        form_obj = ConsultForm(request.POST,instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse_url(request,'consult_list'))

    return render(request,'edit_consult.html',{'form_obj':form_obj})


from porcupine.config import settings
from porcupine import context
from porcupine.db import _db

def get_handle(**kwargs):
    if _db._db_handle is None or not _db._db_handle.is_open():
        # clear rep_config
        settings.settings['store']['rep_config'] = None
        # open database
        kwargs.setdefault('maintain', False)
        kwargs.setdefault('recover', 0)
        _db.open(**kwargs)
        identity = kwargs.get('identity', _db.get_item('system'))
        if isinstance(identity, basestring):
            identity = _db.get_item(identity)
        context.user = identity
    return _db

def close():
    _db.close(clear_env=True)


import os

#读取档案
products = []
if os.path.isfile('products.csv'):
	print('yeah!找到档案了！')
	with open('products.csv', 'r', encoding = 'utf-8') as f:
		for line in f:
			if '商品,价格' in line:
				continue
		name, price = line.split().split(',')
		products.append([name,price])
	print(products)
else:
	print('档案不存在。。。。。')

print(products)

# 让使用者输入
while True:
	name = input('请输入商品名称:')
	if name == 'q':
		break
	price = input('请输入价格：')
	price = int(price)
	products.append([name,  price])
print(products)

# 印出所有购买记录
for p in products:
	print(p[0], '的价格是', p[1])

# 写入档案
with open ('products.csv ','w', encoding = 'utf-8') as f :
	f.write('商品,价格\n')
	for p in products:
		f.write (p[0] + ',' + str(p[1]) + '\n')