""" Задание №1 """

list_age = [0]*8
for i in range(2, 100):
    for j in range(2, 10):
        if i % j == 0:
            list_age[j-2] += 1
i = 0
while i < len(list_age):
    print(i+2, ' - ', list_age[i])
    i += 1

""" Задание №2 """

from random import random
N = 10
arr = [0]*N
even = []
for i in range(N):
    arr[i] = int(random() * 10) + 10
    if arr[i] % 2 == 0:
        even.append(i)
print(arr)
print('Индексы четных элементов: ', even)

""" Задание №3 """

from random import random

N = 15
arr = [0] * N
for i in range(N):
    arr[i] = int(random() * 100)
    print(arr[i], end=' ')
print()

mn = min(arr)
mx = max(arr)
imn = arr.index(mn)
imx = arr.index(mx)
print('arr[%d]=%d arr[%d]=%d' % (imn + 1, mn, imx + 1, mx))
arr[imn], arr[imx] = arr[imx], arr[imn]
for i in range(15):
    print(arr[i],end=' ')
print()

""" Задание №4 """

from random import random

number = 15
arr = [0] * number
for i in range(number):
    arr[i] = int(random() * 20)
print(arr)

num = arr[0]
max_frq = 1
for i in range(number - 1):
    frq = 1
    for k in range(i + 1, number):
        if arr[i] == arr[k]:
            frq += 1
    if frq > max_frq:
        max_frq = frq
        num = arr[i]

if max_frq > 1:
    print(max_frq, 'раз(а) встречается число', num)
else:
    print('Все элементы уникальны')

""" Задание №5 """
from random import random

number = 15
arr = []
for i in range(number):
    arr.append(int(random() * 100) - 50)
print(arr)

i = 0
index = -1
while i < number:
    if arr[i] < 0 and index == -1:
        index = i
    elif arr[i] < 0 and arr[i] > arr[index]:
        index = i
    i += 1

print(index + 1, ':', arr[index])

""" Задание №6 """
from random import random

number = 10
number_list = [0] * number
for i in range(number):
    number_list[i] = int(random()*50)
    print('%3d' % number_list[i], end='')
print()

min_id = 0
max_id = 0
for i in range(1, number):
    if number_list[i] < number_list[min_id]:
        min_id = i
    elif number_list[i] > number_list[max_id]:
        max_id = i
print(number_list[min_id], number_list[max_id])

if min_id > max_id:
    min_id, max_id = max_id, min_id

summa = 0
for i in range(min_id+1, max_id):
    summa += number_list[i]
print(summa)
""" Задание №7 """
from random import random

number = 10
a = []
for i in range(number):
    a.append(int(random() * 100))
    print("%3d" % a[i], end='')
print()

if a[0] > a[1]:
    min1 = 0
    min2 = 1
else:
    min1 = 1
    min2 = 0

for i in range(2, number):
    if a[i] < a[min1]:
        b = min1
        min1 = i
        if a[b] < a[min2]:
            min2 = b
    elif a[i] < a[min2]:
        min2 = i

print("№%3d:%3d" % (min1 + 1, a[min1]))
print("№%3d:%3d" % (min2 + 1, a[min2]))

""" Задание №8 """
M = 5
N = 4
a = []
for i in range(N):
    b = []
    s = 0
    print("%d-я строка:" % i)
    for j in range(M - 1):
        n = int(input())
        s += n
        b.append(n)
    b.append(s)
    a.append(b)

for i in a:
    print(i)

""" Задание №9 """
from random import random

M = 10
N = 5
a = []
for i in range(N):
    b = []
    for j in range(M):
        n = int(random() * 200)
        b.append(n)
        print('%4d' % n, end='')
    a.append(b)
    print()

mx = -1
for j in range(M):
    mn = 200
    for i in range(N):
        if a[i][j] < mn:
            mn = a[i][j]
    if mn > mx:
        mx = mn
print("Максимальный среди минимальных: ", mx)


import os
import sys
import shutil
import torch
import clip

from rvt.libs.peract.helpers.utils import extract_obs
from rvt.utils.rvt_utils import ForkedPdb
from rvt.utils.dataset import create_replay, fill_replay
from rvt.utils.peract_utils import (
    CAMERAS,
    SCENE_BOUNDS,
    EPISODE_FOLDER,
    VARIATION_DESCRIPTIONS_PKL,
    DEMO_AUGMENTATION_EVERY_N,
    ROTATION_RESOLUTION,
    VOXEL_SIZES,
)
from yarr.replay_buffer.wrappers.pytorch_replay_buffer import PyTorchReplayBuffer

def get_dataset(
    tasks,
    BATCH_SIZE_TRAIN,
    BATCH_SIZE_TEST,
    TRAIN_REPLAY_STORAGE_DIR,
    TEST_REPLAY_STORAGE_DIR,
    DATA_FOLDER,
    NUM_TRAIN,
    NUM_VAL,
    refresh_replay,
    device,
    num_workers,
    only_train,
    sample_distribution_mode="transition_uniform",
):

    train_replay_buffer = create_replay(
        batch_size=BATCH_SIZE_TRAIN,
        timesteps=1,
        disk_saving=True,
        cameras=CAMERAS,
        voxel_sizes=VOXEL_SIZES,
    )
    if not only_train:
        test_replay_buffer = create_replay(
            batch_size=BATCH_SIZE_TEST,
            timesteps=1,
            disk_saving=True,
            cameras=CAMERAS,
            voxel_sizes=VOXEL_SIZES,
        )

    # load pre-trained language model
    try:
        clip_model, _ = clip.load("RN50", device="cpu")  # CLIP-ResNet50
        clip_model = clip_model.to(device)
        clip_model.eval()
    except RuntimeError:
        print("WARNING: Setting Clip to None. Will not work if replay not on disk.")
        clip_model = None

    for task in tasks:  # for each task
        # print("---- Preparing the data for {} task ----".format(task), flush=True)
        EPISODES_FOLDER_TRAIN = f"train/{task}/all_variations/episodes"
        EPISODES_FOLDER_VAL = f"val/{task}/all_variations/episodes"
        data_path_train = os.path.join(DATA_FOLDER, EPISODES_FOLDER_TRAIN)
        data_path_val = os.path.join(DATA_FOLDER, EPISODES_FOLDER_VAL)
        train_replay_storage_folder = f"{TRAIN_REPLAY_STORAGE_DIR}/{task}"
        test_replay_storage_folder = f"{TEST_REPLAY_STORAGE_DIR}/{task}"

        # if refresh_replay, then remove the existing replay data folder
        if refresh_replay:
            print("[Info] Remove exisitng replay dataset as requested.", flush=True)
            if os.path.exists(train_replay_storage_folder) and os.path.isdir(
                train_replay_storage_folder
            ):
                shutil.rmtree(train_replay_storage_folder)
                print(f"remove {train_replay_storage_folder}")
            if os.path.exists(test_replay_storage_folder) and os.path.isdir(
                test_replay_storage_folder
            ):
                shutil.rmtree(test_replay_storage_folder)
                print(f"remove {test_replay_storage_folder}")

        # print("----- Train Buffer -----")
        fill_replay(
            replay=train_replay_buffer,
            task=task,
            task_replay_storage_folder=train_replay_storage_folder,
            start_idx=0,
            num_demos=NUM_TRAIN,
            demo_augmentation=True,
            demo_augmentation_every_n=DEMO_AUGMENTATION_EVERY_N,
            cameras=CAMERAS,
            rlbench_scene_bounds=SCENE_BOUNDS,
            voxel_sizes=VOXEL_SIZES,
            rotation_resolution=ROTATION_RESOLUTION,
            crop_augmentation=False,
            data_path=data_path_train,
            episode_folder=EPISODE_FOLDER,
            variation_desriptions_pkl=VARIATION_DESCRIPTIONS_PKL,
            clip_model=clip_model,
            device=device,
        )

        if not only_train:
            # print("----- Test Buffer -----")
            fill_replay(
                replay=test_replay_buffer,
                task=task,
                task_replay_storage_folder=test_replay_storage_folder,
                start_idx=0,
                num_demos=NUM_VAL,
                demo_augmentation=True,
                demo_augmentation_every_n=DEMO_AUGMENTATION_EVERY_N,
                cameras=CAMERAS,
                rlbench_scene_bounds=SCENE_BOUNDS,
                voxel_sizes=VOXEL_SIZES,
                rotation_resolution=ROTATION_RESOLUTION,
                crop_augmentation=False,
                data_path=data_path_val,
                episode_folder=EPISODE_FOLDER,
                variation_desriptions_pkl=VARIATION_DESCRIPTIONS_PKL,
                clip_model=clip_model,
                device=device,
            )

    # delete the CLIP model since we have already extracted language features
    del clip_model
    with torch.cuda.device(device):
        torch.cuda.empty_cache()

    # wrap buffer with PyTorch dataset and make iterator
    train_wrapped_replay = PyTorchReplayBuffer(
        train_replay_buffer,
        sample_mode="random",
        num_workers=num_workers,
        sample_distribution_mode=sample_distribution_mode,
    )
    train_dataset = train_wrapped_replay.dataset()

    if only_train:
        test_dataset = None
    else:
        test_wrapped_replay = PyTorchReplayBuffer(
            test_replay_buffer,
            sample_mode="enumerate",
            num_workers=num_workers,
        )
        test_dataset = test_wrapped_replay.dataset()
    return train_dataset, test_dataset


#!/user/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from deeplearning.approximation.interface.approximate_interface import ApproximateInterface

class ContrastiveDivergence(ApproximateInterface):
    '''
    Contrastive Divergence法
    Numpy版

    概念的にはpositive phaseとnegative phaseの区別を
    wakeとsleepの区別に対応付けて各メソッドを命名している。

    '''

    # ニューロンのグラフ
    __graph = None
    # 学習率
    __learning_rate = 0.5

    def approximate_learn(self, graph, learning_rate, observed_data_matrix, traning_count=1000):
        '''
        インターフェイスの実現
        近似による学習
        目覚めと眠りのフェーズを逐次実行して学習する

        Args:
            graph:                ニューロンのグラフ
            learning_rate:        学習率
            observed_data_matrix: 観測データ点
            traning_count:        訓練回数

        Returns:
            グラフ
        '''
        self.__graph = graph
        self.__learning_rate = learning_rate
        [self.__wake_and_sleep(observed_data_list) for observed_data_list in observed_data_matrix]
        return self.__graph

    def __wake_and_sleep(self, observed_data_list):
        '''
        目覚めと夢見のリズム

        Args:
            observed_data_list:      観測データ点
        '''
        self.__wake(observed_data_list)
        self.__sleep()
        self.__learn()

    def __wake(self, observed_data_list):
        '''
        目覚めと眠りのフェーズを逐次実行して学習する

        Args:
            observed_data_list:      観測データ点
        '''
        # 観測データ点を可視ニューロンに入力する
        for i in range(len(observed_data_list)):
            self.__graph.visible_neuron_list[i].observe_data_point(observed_data_list[i])

        # 隠れ層のニューロンの発火状態を更新する
        self.__update_hidden_spike()

        # ヘブ規則によりリンクの重みを更新する
        self.__graph.update(self.__learning_rate)

        # 可視層のバイアスを更新する
        for i in range(len(self.__graph.visible_neuron_list)):
            self.__graph.visible_neuron_list[i].update_bias(self.__learning_rate)

        # 隠れ層のバイアスを更新する
        for j in range(len(self.__graph.hidden_neuron_list)):
            self.__graph.hidden_neuron_list[j].update_bias(self.__learning_rate)

    def __sleep(self):
        '''
        夢を見る
        自由連想
        '''
        # 可視層のニューロンの発火状態を更新する
        self.__update_visible_spike()

        # 隠れ層のニューロンの発火状態を更新する
        self.__update_hidden_spike()

        # ヘブ規則によりリンクの重みを逆更新する
        self.__graph.update((-1) * self.__learning_rate)

        # 可視層のバイアスを更新する
        for i in range(len(self.__graph.visible_neuron_list)):
            self.__graph.visible_neuron_list[i].update_bias((-1) * self.__learning_rate)

        # 隠れ層のバイアスを更新する
        for j in range(len(self.__graph.hidden_neuron_list)):
            self.__graph.hidden_neuron_list[j].update_bias((-1) * self.__learning_rate)

    def __update_visible_spike(self):
        '''
        可視層のニューロンの発火状態を更新する
        '''
        hidden_activity_arr = np.array([[self.__graph.hidden_neuron_list[j].activity] * self.__graph.weights_arr.T.shape[1] for j in range(len(self.__graph.hidden_neuron_list))])
        link_value_arr = self.__graph.weights_arr.T * hidden_activity_arr
        visible_activity_arr = link_value_arr.sum(axis=0)
        for i in range(visible_activity_arr.shape[0]):
            self.__graph.visible_neuron_list[i].visible_update_state(visible_activity_arr[i])
            self.__graph.normalize_visible_bias()

    def __update_hidden_spike(self):
        '''
        隠れ層のニューロンの発火状態を更新する
        '''
        visible_activity_arr = np.array([[self.__graph.visible_neuron_list[i].activity] * self.__graph.weights_arr.shape[1] for i in range(len(self.__graph.visible_neuron_list))])
        link_value_arr = self.__graph.weights_arr * visible_activity_arr
        hidden_activity_arr = link_value_arr.sum(axis=0)
        for j in range(hidden_activity_arr.shape[0]):
            self.__graph.hidden_neuron_list[j].hidden_update_state(hidden_activity_arr[j])
            self.__graph.normalize_hidden_bias()

    def __learn(self):
        '''
        バイアスと重みを学習する
        '''
        # 可視層のバイアスの学習
        for i in range(len(self.__graph.visible_neuron_list)):
            self.__graph.visible_neuron_list[i].learn_bias()

        # 隠れ層のバイアスの学習
        for j in range(len(self.__graph.hidden_neuron_list)):
            self.__graph.hidden_neuron_list[j].learn_bias()

        # リンクの重みの学習
        self.__graph.learn_weights()

    def recall(self, graph, observed_data_matrix):
        '''
        記憶から自由連想する

        Args:
            graph:                  自由連想前のグラフ
            observed_data_matrix:   観測データ点

        Returns:
            自由連想後のグラフ

        '''
        self.__graph = graph
        [self.__wake_and_sleep(observed_data_list) for observed_data_list in observed_data_matrix]
        return self.__graph


class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        used = [False] * len(candidates)
        mp = defaultdict(int)
        ans = []
        def solve(nums , remain, index):
            if remain == 0:
                ans.append(nums[::])
                return
            for next_cur in range(index, len(candidates)):
                if next_cur > index and candidates[next_cur] == candidates[next_cur - 1]:
                    continue
                pick = candidates[next_cur]
                if remain - pick < 0:
                    break
                nums.append(pick)
                solve(nums, remain - pick, next_cur + 1)
                nums.pop()
        candidates.sort()
        solve([] , target, 0)
        return ans


#########################################
##  Do not change this file            ##
## Your codes must work with this file ##
#########################################

import math
import random
import string
import warnings
import pyprimes
# These are the modules needed for elliptic curve cryptography
from ecpy.curves import Curve,Point
from ecpy.keys import ECPublicKey, ECPrivateKey
from ecpy.ecdsa import ECDSA
from ecpy.formatters import decode_sig, encode_sig
######
import TxECDSA       # You have to submit this file, which is the new version that works with ECDSA
import PoWECDSA      # You have to submit this file, which is the new version that works with ECDSA
import ChainGen      # You have to submit this file
import os.path
import hashlib
import sys

if sys.version_info < (3, 6):
    import sha3

def random_string(size=6, chars=string.ascii_uppercase + string.ascii_lowercase+ string.digits):
    return ''.join(random.choice(chars) for x in range(size))

def CheckBlock(filename, curve):
    if os.path.isfile(filename):
        f = open(filename, "r")
        block = f.readlines()
        if len(block)%9 != 0:
            print("Incorrect file format")
            f.close()
            return -10000
        block_count = len(block)//9
        for i in range(0, block_count):
            # coordinates of the public key point
            x1 = int(block[i*9+2][22:-1])
            y1 = int(block[i*9+3][22:-1])
            r = int(block[i*9+7][15:-1])
            s = int(block[i*9+8][15:-1])
            tx = "".join(block[i*9: i*9+7])
            # For the signature verfication
            payer = ECDSA()
            payer_pk = ECPublicKey(Point(x1, y1, curve))
            signature = encode_sig(r, s)
            try:
                assert(payer.verify(tx.encode('UTF-8'), signature, payer_pk))
                ver = 0
                f.close()
                return ver
            except:
                ver = -i-1
                f.close()
                return ver
        return 0
    else:
        print("File does not exist")
        return -10000

##############
# Student Part

# This is for generating random transactions
# You should have a function with the name "Tx.gen_random_tx()" in "Tx.py"
curve = Curve.get_curve('secp256k1') # The curve used for signing bitcoin transactions
tx_blk = open("transactions.txt", "w")
for i in range(0,32):
    tx_blk.write(TxECDSA.gen_random_tx(curve))
tx_blk.close()

# Test I
# Verify the signatures of all your transactions in a block
ReturnCode = CheckBlock("transactions.txt", curve)
if ReturnCode == -10000:
    print("File Problem")
elif(ReturnCode < 0):
    print("Signtature Problem in Transaction number", -ReturnCode)
elif ReturnCode == 0:
    print("All transactions verify")
else:
    print("Unexpected branching")

# This is for generating a PoW for the block in transactions.txt
# You should have a function called "PoW" in file PoW.py
PoWLen = 3   # The number of 0 hexadecimal digits; i.e. PoWLen = x/4
block = PoWECDSA.PoW(PoWLen, "transactions.txt")
f = open("block.txt", "w")
f.write(block)
f.close()

# Test II
# Check PoW
f = open("block.txt", "r")
block = f.readlines()
block = "".join(block)
blockHash = hashlib.sha3_256(block.encode('UTF-8')).hexdigest()
if blockHash[0:PoWLen] == "0"*PoWLen:
    print("Proof-of-Work test: passed")
else:
    print("Proof-of-Work test: failed")
f.close()

# Test III
# Generate the blockchain
BlockLen = 2   # number of transactions in a block
ChainLen = 4    # number of blocks
filename = "Block"
ctr = 0
# block candidate contains only the transactions; not Previous Hash nor PoW
block_candidate = TxECDSA.gen_random_tx(curve)
for j in range(0, BlockLen):
    block_candidate += TxECDSA.gen_random_tx(curve)
PrevBlock = ChainGen.AddBlock2Chain(PoWLen, 0, block_candidate)
f = open(filename + "0.txt", "w")
f.write(PrevBlock)
f.close()
for i in range(1, ChainLen):
    block_candidate = TxECDSA.gen_random_tx(curve)
    for j in range(0, BlockLen):
        block_candidate += TxECDSA.gen_random_tx(curve)
    NewBlock = ChainGen.AddBlock2Chain(PoWLen, PrevBlock, block_candidate)
    f = open(filename + str(i) + ".txt", "w")
    f.write(NewBlock)
    f.close()
    PrevBlock = NewBlock

# Check the blockchain
# First block
chck = 0
f = open(filename + "0.txt", "r")
block = f.readlines()
NewHash = hashlib.sha3_256("".join(block).encode('UTF-8')).hexdigest()
# Check the Pow for the current block
if NewHash[0:PoWLen] != "0"*PoWLen:
    print("PoW error in block no 0")
    chck += 1
f.close()
PrevHash = NewHash
for i in range(1, ChainLen):
    f = open(filename + str(i) + ".txt", "r")
    block = f.readlines()
    if(PrevHash != block[-2][15:-1]):
        print("The current block does not include the hash of the previous block")
        chck += 1
    NewHash = hashlib.sha3_256("".join(block).encode('UTF-8')).hexdigest()
    if NewHash[0:PoWLen] != "0"*PoWLen:
        print("PoW error in block no " + str(i))
        chck += 1
    f.close()
    PrevHash = NewHash
if chck == 0:
    print("Blockchain test: passed")
else:
    print("Blockchain test: failed")


def pgen():
    D = {}
    q = 2
    while True:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        q += 1

S, P, s, p = {}, pgen(), 0, 0
while p < 1000000:
    p = next(P)
    s += p
    S[p] = s

for _ in range(int(input().strip())):
    n = int(input().strip())
    while S.get(n) == None:
        n -= 1
    print(S.get(n))


import pytest
from pythonic_garage_band import __version__
from pythonic_garage_band.pythonic_garage_band import Band,Guitarist,Bassist,Drummer,Musician

def test_version():
    assert __version__ == '0.1.0'

@pytest.fixture
def allData():

    bryan = Bassist("bryan","Bassist")
    Yiannis_Chryssomallis = Guitarist("Yiannis_Chryssomallis")
    Charlie_Adams = Drummer("Charlie_Adams")
    George = Band("George X",[bryan,Yiannis_Chryssomallis,Charlie_Adams],"Careless Whisper")
    return {'bryan':bryan, 'Yiannis_Chryssomallis':Yiannis_Chryssomallis, 'Charlie_Adams':Charlie_Adams , 'George': George}

def test_play_solos(allData):
    expected = ['dan dan dan',
    'tram tram tram',
    'bummm bummm']
    actual = allData['George'].play_solos()
    assert expected == actual

def test_get_instrument(allData):
    expected = 'Guitar'
    actual = allData['Yiannis_Chryssomallis'].get_instrument()
    assert expected == actual

def test_play_solo(allData):
    expected = 'dan dan dan'
    actual = allData['bryan'].play_solo()
    assert expected == actual

def test_to_list(allData):
    expected = Band.to_list()
    actual = allData['George'].to_list()
    assert expected == actual


textFile = open('2022/1-2022-text.txt', 'r')
textLines = textFile.readlines()

totalCals = list()
elfCals = 0
largestElfCals = 0
largestElfIndex = 0
grandTotalCals = 0

for line in textLines:
    if len(line) > 2:
        elfCals += int(line.strip())
    else:
        totalCals.append(elfCals)
        elfCals = 0

for i in range(len(totalCals)):
    if totalCals[i] > largestElfCals:
        largestElfCals = totalCals[i]
        largestElfIndex = i

totalCals.sort(reverse=True)
grandTotalCals = totalCals[0] + totalCals[1] + totalCals[2]
print(largestElfCals)
print(largestElfIndex)
print(grandTotalCals)


# A+B - 5
# 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

result = []

while True:
    a, b = map(int, input().split())

    if a == 0 and b == 0:
        break

    result.append(a + b)

for i in result:
    print(i)


from PyQt4 import QtCore,QtGui
from controls import Control, ScanControl
import threading as th
import numpy as np
import time
from graph import Graph, VoltGraph

class OptimizerWidget(QtGui.QMainWindow):
    """docstring for OptimizerWidget"""
    closed = QtCore.Signal()
    def __init__(self,parent,beamline):
        super(OptimizerWidget, self).__init__(parent)

        self.beamline = beamline
        self.subset = []
        self.cont = False

        self.controls = {}
        self.hotkeyManager = parent.hotkeyManager
        self.voltGraphs = {}

        self.init_UI()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(50)

        ok = self.chooseControls()
        if ok:
            self.show()
        else:
            self.close()

    def init_UI(self):
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)
        self.layout = QtGui.QGridLayout(widget)

        self.makeMenuBar()

    def makeMenuBar(self):
        menubar = self.menuBar()

        self.chooseAction = QtGui.QAction('&Choose Controls',self)
        self.chooseAction.setShortcut('Ctrl+C')
        self.chooseAction.triggered.connect(self.chooseControls)

        self.setOptimalAction = QtGui.QAction('Set to &Optimal',self)
        self.setOptimalAction.setShortcut('Ctrl+O')
        self.setOptimalAction.triggered.connect(self.beamline.setToOptimal)

        settingsMenu = menubar.addMenu('&Settings')
        settingsMenu.addAction(self.chooseAction)
        settingsMenu.addAction(self.setOptimalAction)

        self.scanAction = QtGui.QAction('&Scan',self)
        self.scanAction.setShortcut('Ctrl+S')
        self.scanAction.triggered.connect(self.startScan)

        self.stopAction = QtGui.QAction('S&top',self)
        self.stopAction.setShortcut('Ctrl+T')
        self.stopAction.triggered.connect(self.stopScan)

        scanMenu = menubar.addMenu('&Scanning')
        scanMenu.addAction(self.scanAction)
        scanMenu.addAction(self.stopAction)

        self.optimizeBayesAction = QtGui.QAction('&Bayesian Optimize',self)
        self.optimizeBayesAction.setShortcut('Ctrl+B')
        self.optimizeBayesAction.triggered.connect(self.optimize)

        self.optimizeMCMCAction = QtGui.QAction('&MCMC Optimize',self)
        self.optimizeMCMCAction.setShortcut('Ctrl+M')
        self.optimizeMCMCAction.triggered.connect(self.optimize)

        self.optimizeMyMCMCAction = QtGui.QAction('&My MCMC Optimize',self)
        self.optimizeMyMCMCAction.setShortcut('Ctrl+N')
        self.optimizeMyMCMCAction.triggered.connect(self.optimize)

        optimizeMenu = menubar.addMenu('&Optimizer')
        optimizeMenu.addAction(self.optimizeBayesAction)
        optimizeMenu.addAction(self.optimizeMCMCAction)
        optimizeMenu.addAction(self.optimizeMyMCMCAction)

    def chooseControls(self):
        ok,controls = modePrompt.mode(self,
            [n for n in self.beamline.voltages.keys()],self.subset)

        self.subset = controls

        self.addControls()

        return ok

    def addControls(self):
        try:
            self.layout.removeWidget(self.controlsWidget)
            self.controlsWidget.setParent(None)
            self.controls = {}
            self.voltGraphs = {}
        except:
            pass

        self.controlsWidget = QtGui.QWidget()
        controlsLayout = QtGui.QGridLayout(self.controlsWidget)

        i = 0
        for n,v in self.beamline.voltages.items():
            if n in self.subset:
                control = ScanControl(v)
                self.controls[n] = control
                controlsLayout.addWidget(control,2*(i%2),i//2)

                self.voltGraphs[n] = VoltGraph(self,n)
                controlsLayout.addWidget(self.voltGraphs[n],1+2*(i%2),i//2)

                i = i + 1

        self.layout.addWidget(self.controlsWidget,0,1,1,2)

    def update(self):
        for c in self.controls.values():
            c.update()

        for g in self.voltGraphs.values():
            g.updateGraph()

    def startScan(self):
        for c in self.controls.values():
            c.defineScan()

        self.beamline.startScan(self.subset)

    def stopScan(self):
        self.beamline.stopScan()

    def optimize(self):
        for c in self.controls.values():
            c.defineScan()

        if self.sender() == self.optimizeBayesAction:
            self.beamline.optimize(self.subset,'bayes')
        elif self.sender() == self.optimizeMyMCMCAction:
            self.beamline.optimize(self.subset,'my mcmc')
        else:
            self.beamline.optimize(self.subset,'mcmc')

    def keyPressEvent(self,e):
        self.hotkeyManager.keyPressed(e)
        super(QtGui.QMainWindow,self).keyPressEvent(e)

    def closeEvent(self,event):
        self.stopScan()
        self.closed.emit()
        super(OptimizerWidget,self).close()

class modePrompt(QtGui.QDialog):
    """docstring for modePrompt"""
    def __init__(self,parent,names,subset):
        super(modePrompt, self).__init__(parent)
        self.names = names

        layout = QtGui.QGridLayout(self)

        # self.modes = QtGui.QComboBox()
        # self.modes.addItems(['Optimizer'])
        # layout.addWidget(self.modes,0,0)

        self.modeWidget = QtGui.QWidget()
        self.layout = QtGui.QGridLayout(self.modeWidget)
        layout.addWidget(self.modeWidget,1,0)

        buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons,20,0)

        self.checks = {}

        for i,n in enumerate(self.names):
            self.checks[n] = QtGui.QCheckBox(n)
            if n in subset:
                self.checks[n].setChecked(True)
            layout.addWidget(self.checks[n],i,0)

    @staticmethod
    def mode(parent,names, subset):
        modes = modePrompt(parent,names,subset)
        result = modes.exec_()
        return result == QtGui.QDialog.Accepted,\
                [n for n,c in modes.checks.items() if c.checkState()]


num_dict = {2 : ['A', 'B', 'C']
           ,3 : ['D', 'E', 'F']
           ,4 : ['G', 'H', 'I']
           ,5 : ['J', 'K', 'L']
           ,6 : ['M', 'N', 'O']
           ,7 : ['P', 'Q', 'R', 'S']
           ,8 : ['T', 'U', 'V']
           ,9 : ['W', 'X', 'Y', 'Z']}

# UNUCIC
alphabet_list = list(input())
number_list = []

# [number for number, alhphabet in num_dict.items() if alhphabet = 'Something']
for input_alphabet in alphabet_list:
    for number, alphabet_keys in num_dict.items():
        if(input_alphabet in alphabet_keys):
            number_list.append(number)

#1을 걸려면 2초, 2를 걸려면 3초 ... 9를 걸려면 10초.
print(sum(number_list)+len(number_list))


# 개인정보 수집 유효기간
from datetime import datetime

def solution(today, terms, privacies):
    # 결과를 저장할 배열
    answer = []
    # 각 약관별 유효기간을 저장할 딕셔너리
    term = {}
    # 오늘 날짜 today를 날짜 객체로 변환
    today = datetime.strptime(today, '%Y.%m.%d')

    # 약관별 유효기간 저장
    for i in range(len(terms)):
        term_name, month = terms[i].split()
        term[term_name] = int(month)

    # 유효기간이 지났는지 확인하는 반복문
    for i in range(len(privacies)):
        # 개인정보 수집 일자를 공백으로 구분해 입력받고 날짜 객체로 변환
        collection = datetime.strptime(privacies[i].split()[0], '%Y.%m.%d')

        # 일 수는 해당하는 약관의 유효기간 * 28(한 달이 28일이라 가정했으므로)
        day = term.get(privacies[i].split()[1]) * 28
        # 수집 일자의 연도
        year = collection.year
        # 수집 일자의 달
        month = collection.month
        # 수집 일자의 일 수
        ex_day = collection.day

        # 일 수가 0이 될 때까지 반복
        while day != 0:
            # 만약 12월 28일이면 다음 연도로 넘겨주고 1월 1일로 초기화
            if month == 12 and ex_day == 28:
                year += 1
                month = 1
                ex_day = 1
            # 28일이면 다음 달로 넘겨주고 1일로 초기화
            elif ex_day == 28:
                month += 1
                ex_day = 1
            # 두 경우 다 아니면 하루 증가
            else:
                ex_day += 1
            # 일 수 1 감소
            day -= 1
        # 만료 날짜(보관 가능한 마지막 날짜 다음 일자를 저장)
        expiration = datetime(year, month, ex_day)
        # 만료 날짜가 오늘보다 작거나 같으면 answer에 해당 인덱스 + 1 저장
        if expiration <= today:
            answer.append(i + 1)
    return answer

print(solution("2022.05.19", ["A 6", "B 12", "C 3"], ["2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C"]))
print(solution("2020.01.01", ["Z 3", "D 5"], ["2019.01.01 D", "2019.11.15 Z", "2019.08.02 D", "2019.07.01 D", "2018.12.28 Z"]))


import random
import sys
import time

# if no arguments, the human tries to guess
# C++: const bool human_guess = (argc == 1);

human_guess = (len(sys.argv) == 1)

if human_guess:

    # srand(time(NULL));
    random.seed(time.clock)
    # const unsigned int n = rand() % 100;
    n = random.randint(1,100)

    while True:
        # ask the user for a number
        #    cout << "Please enter a number: ";
        #    cin >> m;
        m = input('Please enter a number (1-100): ')

        if m == n:
            print("That's it, congratulations")
            break
        elif m < n:
            print("Too small")
        else:
            print("Too large")

else:
    lower = 1
    upper = 100

    while True:

        # guess = 0.5*(lower + upper)
        guess = int(0.5*(lower + upper))

        print("   0 if ok, 1 if too small, 2 if too large")
        response = input("Is it " + str(guess) + "? - ")

        if response == 0:
            print(" I knew it!")
            break
        elif lower == upper:
            print("I think you are cheating")
            break
        elif response == 1:
            lower = guess +1
        else:
            upper = guess -1


# Given an array of integers, we would like to determine whether the array is monotonic (non-decreasing/non-
# increasing) or not.

def is_monotonic(arr):
    if not arr or len(arr) == 1:
        return True

    increasing = True if arr[0] < arr[-1] else False
    prev = arr[0]
    for i, item in enumerate(arr[1:]):
        if item < prev and increasing:
            return False
        elif item > prev and not increasing:
            return False
        prev = item
    return True

# Solution: Compare the first and the last element to see if the array should be
# mononically increasing or decreasing. Store the first element as the previous
# element. Iterate through the array and for each element, if the element is greater
# than the previous one but the array is decreasing, or if the element is less
# than the previous one but the array is increasing, return False. Else, update
# the previous element to be the currrent element and keep going. Return True
# if you make it to the end with no errors.


from ivr_payment.celery import app
from logs.models import ResponseLog, RequestLog

@app.task
def response_log_create(data):
    log_instance = RequestLog.objects.get(id=data['request'])
    data['request'] = log_instance
    ResponseLog.objects.create(**data)
    return {'message': 'response_log created'}

@app.task
def request_log_create(data):
    request_log = RequestLog.objects.create(**data)
    return request_log


import d_m as dm
from keras.models import load_model, model_from_json
import os
import numpy as np
import generator as gen
import naive as nai

# File paths
data_file = os.path.join('data', 'data_labeled.txt')
data_stripped = os.path.join('data', 'data_stripped.txt')
file_unlabeled = os.path.join('data', 'data_unlabeled.txt')
file_unlabel = os.path.join('data', 'unlabeled_reviews.txt')
settings = dm.read_settings('settings.txt')

# Strip data files to text
dm.strip_data(file_unlabeled, file_unlabel)
dm.strip_data(data_file, data_stripped)

# Get Files
max_len, tokenizer, X_data, _, Y_data, _, _rev_data, _, _val_data, _ = dm.train_data(data_file, 1)
unlabeled, _unlabeled = dm.open_doc(file_unlabel, True)

path = settings['path']
model_name = settings['model_name']
model_name = os.path.join(path, model_name)
model = None
def model_load():
    global model
    print('Loading model...', end = '')
    json_file = open(model_name + '.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    model = model_from_json(loaded_model_json)
    model.load_weights(model_name + '.h5')
    print('\rLoaded model from disk')

char_to_display = settings['char_to_display']
allowed_difference = 0.1
def generate_set(X_data, _rev_data):
    print("----------------------------------------     Data Set     ----------------------------------------")
    print('Model: ' + model_name)
    z = []
    for data in X_data:
        z.append(dm.data_to_input(data)[0])
    X_data = np.array(z)

    prediction = model.predict(X_data)

    for i in range(len(_rev_data)):
        predict = prediction[i][0]

        predict_stars = dm.to_stars(predict)

        text = str(i + 1) + ') ' + _rev_data[i]

        print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars)

def generate_set_vals(X_data, Y_data, _rev_data, pr = True):
    print("----------------------------------------     Data Set     ----------------------------------------")
    print('Model: ' + model_name)
    prediction = model.predict(X_data)

    total = 0
    right = 0
    for i in range(len(X_data)):
        predict = prediction[i][0]

        difference = abs(predict - Y_data[i])

        predict_stars = dm.to_stars(predict)
        actual_stars = dm.to_stars(Y_data[i])

        text = str(i + 1) + ') ' + _rev_data[i]

        if difference <= allowed_difference:
            if pr:
                print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars + '----- actually ' + actual_stars)
            right += 1
        else:
            if pr:
                print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars + '----- actually ' + actual_stars + ' *****')
        total += 1

    print('Accuracy:', str(right / total * 100) + '% |', str(right) + '/' + str(total))

stop_words = ['--e', '--n', '--q']
def generate(forever = False):
    inp = ''
    print('Model: ' + model_name)
    while forever or not any(inp == w for w in stop_words):
        inp = input('Sample review:\n')

        z = dm.data_to_input(inp)

        prediction = model.predict(z)
        predict = prediction[0][0]

        predict_stars = dm.to_stars(predict)

        print(dm.truncate_text('', char_to_display) + ' ----- predicted ' + predict_stars)

def generate_set_naive(X_data):
    print("----------------------------------------     Data Set     ----------------------------------------")
    print('Model: ' + model_name)
    prediction = naive_predict_data(X_data)

    for i in range(len(X_data)):
        predict = prediction[i]

        predict_stars = dm.to_stars(predict)

        text = str(i + 1) + ') ' + X_data[i]

        print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars)

def generate_set_vals_naive(X_data, Y_data, pr = True):
    print("----------------------------------------     Data Set     ----------------------------------------")
    print('Model: ' + model_name)
    prediction = naive_predict_data(X_data)

    total = 0
    right = 0
    for i in range(len(X_data)):
        predict = prediction[i]

        difference = abs(predict - Y_data[i])

        predict_stars = dm.to_stars(predict)
        actual_stars = dm.to_stars(Y_data[i])

        text = str(i + 1) + ') ' + X_data[i]

        if difference <= allowed_difference:
            if pr:
                print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars + '----- actually ' + actual_stars)
            right += 1
        else:
            if pr:
                print(dm.truncate_text(text, char_to_display) + ' ----- predicted ' + predict_stars + '----- actually ' + actual_stars + ' *****')
        total += 1

    print('Accuracy:', str(right / total * 100) + '% |', str(right) + '/' + str(total))

stop_words = ['--e', '--n', '--q']
def generate_naive(forever = False):
    inp = ''
    print('Model: ' + model_name)
    while forever or not any(inp == w for w in stop_words):
        inp = input('Sample review:\n')

        prediction = naive_predict(inp)
        print(dm.truncate_text('', char_to_display) + ' ----- predicted ' + prediction)

def predict_data(data):
    z = []
    for d in data:
        z.append(dm.data_to_input(d)[0])
    z = np.array(z)

    prediction = zip(z, model.predict(data))

    return prediction

def predict(txt):
    inp = dm.data_to_input(txt)

    prediction = model.predict(inp)
    predict = prediction[0][0]
    predict_stars = dm.to_stars(predict)

    return predict_stars

def naive_predict(txt):
    return nai.to_stars(nai.get_val(txt))

def naive_predict_data(data):
    prediction = []

    for val in data:
        prediction.append(nai.get_val(val))
    return prediction

# NN models
models_to_test = ['model_cnn', 'model_lstm', 'model_bidir']
for model_nam in models_to_test:
    model_name = os.path.join(path, model_nam)
    model_load()

    #Generate Vals
    #generate_set_vals(X_data, Y_data, _rev_data, False)
    # generate_set(unlabeled, _unlabeled)
    generate(False)

# Naive model
model_name = 'Naive'
#generate_set_vals_naive(_rev_data, Y_data, False)
# generate_set_naive(_unlabeled)
generate_naive(False)

generate = True
# Generate Text
if generate:
    while True:
        input('\nPress Enter to Generate Review:\n')
        txt = gen.generate_text(4, 20)
        stars = predict(txt)
        print(stars)
        print(txt)


"""Autor: Orlando Urbano Trejo (Lando)
   Fecha: 13-07-2023
   Correo: urbanoorlando79@gmail.com

Ejercicio: Calcula el precio de un boleto de viaje, tomando en cuenta el numero de kilometros que se van a recorrer. El precio por kilometro es de $20.50"""

Precio_Boleto = 20.50

Num_Kilometros = float(input("Número de kilómetros a recorrer: "))
Precio = Precio_Boleto * Num_Kilometros

print("El precio de tu boleto es de: ${:.2f}".format(Precio))


#!/usr/bin/env python3
import inspect
import os

import setuptools

__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))

def __read_version(package):
    with open(os.path.join(package, '__init__.py'), 'r') as fd:
        for line in fd:
            if line.startswith('__version__ = '):
                return line.split()[-1].strip().strip("'")

NAME = 'logdd'
MAIN_PACKAGE = 'logdd'
VERSION = __read_version(MAIN_PACKAGE)
DESCRIPTION = 'Extract metrics from logs and pass it to datadog statsd'
LICENCE = 'MIT License'
URL = 'https://github.com/facemetric/logdd'
AUTHOR = 'Dmitry Sorokin'
EMAIL = 'dmitry.sorokin@gmail.com'
KEYWORDS = 'datadog statsd log'

CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Environment :: Console',
    'Intended Audience :: Developers',
    'Intended Audience :: System Administrators',
    'License :: OSI Approved :: MIT License',
    'Operating System :: POSIX :: Linux',
    'Programming Language :: Python',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: Implementation :: CPython',
]

CONSOLE_SCRIPTS = [
    'logdd=logdd.cli:cli'
]

def __read(fname):
    with open(os.path.join(__location__, fname)) as f:
        return f.read()

def setup_package():
    setuptools.setup(
        name=NAME,
        version=VERSION,
        url=URL,
        description=DESCRIPTION,
        author=AUTHOR,
        author_email=EMAIL,
        license=LICENCE,
        keywords=KEYWORDS,
        classifiers=CLASSIFIERS,
        packages=setuptools.find_packages(exclude=['test', 'tests', 'tests.*']),
        install_requires=[req for req in __read('requirements.txt').split('\\n') if req != ''],
        entry_points={
            'console_scripts': CONSOLE_SCRIPTS,
        }
    )

if __name__ == '__main__':
    setup_package()


# prime number checker function
# prime number is a number that can be divided by itself and 1 and no other number

# my first attempt
# def prime_checker(number):
#     count = 0
#     for num in range(100):
#         if num / number == 1 or num / number == number:
#             count += 1
#     if count == 1:
#         print("It's a prime number.")
#     else:
#         print("It's not a prime number.")

def prime_checker(number):
    # toggle to False if code detects if not a prime number
    is_prime = True
    # check if prime number, starting from 2 since a prime number is a number that can only be divided by itself and 1 cleanly
    # that's why not increasing by 1 at the end too
    for i in range(2, number):
        # print("i", i)
        # print("modulus", number % i)
        if number % i == 0:
            is_prime = False
    #     print("ip in for", is_prime)
    # print("ip out for", is_prime)
    if is_prime:
        print("It's a prime number.")
    else:
        print("It's not a prime number.")

n = int(input())
prime_checker(number=n)


from functools import reduce

#2. Para a lista Utilizando apenas função lambda e as funções map , reduce e filter .
#  Crie um script que some todas as idades das pessoas com menos de 18 anos:

pessoas = [
    {'nome': 'Pedro', 'idade': 11},
    {'nome': 'Mariana', 'idade': 18},
    {'nome': 'Arthur', 'idade': 26},
    {'nome': 'Rebeca', 'idade': 6},
    {'nome': 'Tiago', 'idade': 19},
    {'nome': 'Gabriela', 'idade': 17}
]

print(reduce(lambda idade, pessoa: idade + pessoa['idade'], filter(lambda p: p['idade'] < 17, pessoas), 0))


import bpy
import bmesh

from mathutils import Vector, Matrix

from ..... utility import addon, mesh
from ..... utility.modifier import apply, sort, new, unmodified_bounds, bevels, move_to_index

sort_types = [
    'ARRAY',
    'MIRROR',
    'BEVEL',
    'SOLIDIFY',
    'DISPLACE',
    'LATTICE',
    'DECIMATE'
    'SCREW',
]

if bpy.app.version[:2] >= (2, 82):
    sort_types.insert(4, 'WELD')

def shape_bool(obj):
    bc = bpy.context.scene.bc

    if obj:
        for mod in reversed(obj.modifiers):
            if mod.type == 'BOOLEAN' and mod.object == bc.shape and (not hasattr(mod, 'operand_type') or mod.operand_type != 'COLLECTION'):
                return mod

    return None

def update(op, context, force_edit_mode=True):
    bc = context.scene.bc
    original_active = context.active_object

    slices = op.datablock['slices']
    targets = op.datablock['targets']

    if not op.datablock['overrides']:
        bpy.ops.mesh.select_all(action='DESELECT')
        overrides = targets + slices

        for obj in overrides:
            bm = bmesh.from_edit_mesh(obj.data)
            obj.update_from_editmode()

        op.datablock['overrides'] = [obj.data.copy() for obj in overrides]

        for obj in op.datablock['slices']:
            for mod in obj.modifiers:
                if mod.type == 'BOOLEAN' and mod.object == bc.shape:
                    mod.show_viewport = True

    evaluated_objs = []

    evaluated = bc.shape.evaluated_get(context.evaluated_depsgraph_get())
    mesh = evaluated.to_mesh()
    evaluated_objs.append(evaluated)

    for poly in mesh.polygons:
        poly.select = True

    for index, obj in enumerate(targets):
        override = op.datablock['overrides'][index]

        bm = bmesh.from_edit_mesh(obj.data)
        cutter_mesh = mesh
        matrix = obj.matrix_world.inverted() @ bc.shape.matrix_world

        if op.mode == 'INSET':
            evaluated = op.datablock['insets'][index].evaluated_get(context.evaluated_depsgraph_get())
            cutter_mesh = evaluated.to_mesh()
            matrix = Matrix()

            for poly in cutter_mesh.polygons:
                poly.select = True

            evaluated_objs.append(evaluated)

        bmesh.ops.delete(bm, geom=bm.verts, context='VERTS')

        bm.from_mesh(cutter_mesh)

        bevel = bm.edges.layers.bevel_weight.verify()

        for edge in bm.edges:
            edge[bevel] = False

        bmesh.ops.transform(bm, matrix=matrix, verts=bm.verts)
        bm.from_mesh(override)
        bm.faces.active = None # XXX: prevents active face flicker
        bmesh.update_edit_mesh(obj.data)

    operation = 'UNION' if op.mode == 'JOIN' else 'INTERSECT'

    if op.mode in {'CUT', 'INSET', 'SLICE', 'EXTRACT'}:
        operation = 'DIFFERENCE'

    # elif op.mode == 'JOIN':
    #     operation = 'UNION'

    # elif op.mode == 'INTERSECT':
    #     operation = 'INTERSECT'

    if bpy.app.version[:2] < (2, 91):
        bpy.ops.mesh.intersect_boolean(operation=operation)
    else:
        bpy.ops.mesh.intersect_boolean(operation=operation, solver='FAST')

    if op.mode in {'SLICE', 'EXTRACT', 'INSET'}:
        evaluated = bc.shape.evaluated_get(context.evaluated_depsgraph_get())
        mesh = evaluated.to_mesh()

        for poly in mesh.polygons:
            poly.select = True

        overrides = op.datablock['overrides'][len(slices)-1:]

        for index, obj in enumerate(slices):
            override = overrides[index]

            bm = bmesh.from_edit_mesh(obj.data)
            cutter_mesh = mesh
            matrix = obj.matrix_world.inverted() @ bc.shape.matrix_world

            if op.mode == 'INSET':
                evaluated = op.datablock['insets'][index].evaluated_get(context.evaluated_depsgraph_get())
                cutter_mesh = evaluated.to_mesh()
                matrix = Matrix()

                for poly in cutter_mesh.polygons:
                    poly.select = True

                evaluated_objs.append(evaluated)

            bmesh.ops.delete(bm, geom=bm.verts, context='VERTS')

            bm.from_mesh(cutter_mesh)

            bevel = bm.edges.layers.bevel_weight.verify()

            for edge in bm.edges:
                edge[bevel] = False

            bmesh.ops.transform(bm, matrix=matrix, verts=bm.verts)
            bm.from_mesh(override)
            bm.faces.active = None # XXX: prevents active face flicker
            bmesh.update_edit_mesh(obj.data)

        if bpy.app.version[:2] < (2, 91):
            bpy.ops.mesh.intersect_boolean(operation='INTERSECT')

        else:
            bpy.ops.mesh.intersect_boolean(operation='INTERSECT', solver='FAST')

    for obj in evaluated_objs:
        obj.to_mesh_clear()

    context.view_layer.objects.active = original_active

    if not force_edit_mode:
        bpy.ops.object.mode_set(mode='OBJECT')

def clean(op, modifier_only=False):
    for obj in op.datablock['targets']:
        if shape_bool(obj):
            obj.modifiers.remove(shape_bool(obj))

    if not modifier_only:
        for obj in op.datablock['slices']:
            bpy.data.meshes.remove(obj.data)

        for obj in op.datablock['insets']:
            bpy.data.meshes.remove(obj.data)

        op.datablock['slices'] = list()
        op.datablock['insets'] = list()

# TODO: move array here
class create:

    def __init__(self, op):
        self.boolean(op)

    @staticmethod
    def boolean(op, show=False):
        wm = bpy.context.window_manager
        preference = addon.preference()
        bc = bpy.context.scene.bc

        if not op.datablock['targets'] or (not op.live and not show):
            return

        if shape_bool(op.datablock['targets'][0]):
            for obj in op.datablock['targets']:
                if shape_bool(obj):
                    obj.modifiers.remove(shape_bool(obj))

            for obj in op.datablock['slices']:
                bpy.data.meshes.remove(obj.data)

            for obj in op.datablock['insets']:
                bpy.data.meshes.remove(obj.data)

            op.datablock['slices'] = []
            op.datablock['insets'] = []

        bc.shape.display_type = 'WIRE' if op.mode != 'MAKE' else 'TEXTURED'
        bc.shape.hide_set(True)

        for obj in op.datablock['targets']:
            if not op.active_only or obj == bpy.context.view_layer.objects.active:
                mod = obj.modifiers.new(name='Boolean', type='BOOLEAN')

                if hasattr(mod, 'solver'):
                    mod.solver = addon.preference().behavior.boolean_solver

                mod.show_viewport = show
                mod.show_expanded = False

                if bpy.app.version[:2] >= (2, 91):
                    mod.show_in_editmode = True

                mod.object = bc.shape
                mod.operation = 'DIFFERENCE' if op.mode not in {'JOIN', 'INTERSECT'} else 'UNION' if op.mode == 'JOIN' else 'INTERSECT'

                if op.mode != 'EXTRACT' or (op.mode == 'EXTRACT' and not preference.behavior.surface_extract):
                    ignore_weight = preference.behavior.sort_bevel_ignore_weight
                    ignore_vgroup = preference.behavior.sort_bevel_ignore_vgroup
                    ignore_verts = preference.behavior.sort_bevel_ignore_only_verts
                    props = {'use_only_vertices': True} if bpy.app.version[:2] < (2, 90) else {'affect': 'VERTICES'}
                    bvls = bevels(obj, weight=ignore_weight, vertex_group=ignore_vgroup, props=props if ignore_verts else {})
                    sort(obj, option=preference.behavior, ignore=bvls, sort_depth=preference.behavior.sort_depth)
                else:
                    sort(obj, sort_types={'WEIGHTED_NORMAL'})

                if op.mode in {'INSET', 'SLICE', 'EXTRACT'}:
                    new = obj.copy()
                    new.data = obj.data.copy()

                    if op.mode in {'SLICE', 'EXTRACT'}:
                        if obj.users_collection:
                            for collection in obj.users_collection:
                                if bpy.context.scene.rigidbody_world and collection == bpy.context.scene.rigidbody_world.collection:
                                    continue

                                collection.objects.link(new)
                        else:
                            bpy.context.scene.collection.objects.link(new)

                        bc.slice = new

                    else:
                        bc.collection.objects.link(new)
                        new.bc.inset = True

                    new.select_set(True)

                    new.name = op.mode.title()
                    new.data.name = op.mode.title()

                    if op.mode == 'SLICE' and preference.behavior.recut:
                        for mod in new.modifiers:
                            if mod.type == 'BOOLEAN' and mod != shape_bool(new):
                                new.modifiers.remove(mod)

                    if op.mode not in {'SLICE', 'EXTRACT'}:
                        new.hide_set(True)

                    shape_bool(new).operation = 'INTERSECT'

                    if op.mode == 'INSET':
                        if op.original_mode == 'EDIT_MESH' or preference.behavior.recut:
                            new.modifiers.clear()

                        else:
                            for mod in reversed(new.modifiers):
                                if mod.type == 'BOOLEAN' and mod.object == bc.shape:
                                    new.modifiers.remove(mod)
                                    break
                                new.modifiers.remove(mod)

                            apply(new)

                    if op.mode == 'INSET':
                        new.display_type = 'WIRE'
                        new.hide_render = True
                        # new.data.use_customdata_vertex_bevel = False
                        # new.data.use_customdata_edge_bevel = False
                        # new.data.use_customdata_edge_crease = False

                        if hasattr(new, 'cycles_visibility'):
                            new.cycles_visibility.camera = False
                            new.cycles_visibility.diffuse = False
                            new.cycles_visibility.glossy = False
                            new.cycles_visibility.transmission = False
                            new.cycles_visibility.scatter = False
                            new.cycles_visibility.shadow = False
                            new.cycles.is_shadow_catcher = False
                            new.cycles.is_holdout = False

                        solidify = new.modifiers.new(name='Solidify', type='SOLIDIFY')
                        solidify.thickness = op.last['thickness']
                        solidify.offset = 0
                        solidify.show_on_cage = True
                        solidify.use_even_offset = True
                        solidify.use_quality_normals = True

                        default_boolean = shape_bool(new)

                        if default_boolean:
                            new.modifiers.remove(default_boolean)

                        mod = new.modifiers.new(name='Boolean', type='BOOLEAN')
                        mod.show_viewport = show
                        mod.show_expanded = False
                        if bpy.app.version[:2] >= (2, 91):
                            mod.show_in_editmode = True
                        mod.object = bc.shape
                        mod.operation = 'INTERSECT'

                        for mod in bc.shape.modifiers:
                            if mod.type == 'SOLIDIFY':
                                bc.shape.modifiers.remove(mod)

                        bool = None
                        for mod in reversed(obj.modifiers):
                            if mod.type == 'BOOLEAN' and mod.object == new:
                                bool = mod
                                break

                        if not bool:
                            mod = obj.modifiers.new(name='Boolean', type='BOOLEAN')

                            if hasattr(mod, 'solver'):
                                mod.solver = addon.preference().behavior.boolean_solver

                            mod.show_viewport = show
                            mod.show_expanded = False
                            if bpy.app.version[:2] >= (2, 91):
                                mod.show_in_editmode = True
                            mod.object = new
                            mod.operation = 'DIFFERENCE'

                            if hasattr(wm, 'Hard_Ops_material_options'):
                                new.hops.status = 'BOOLSHAPE'

                            ignore_weight = preference.behavior.sort_bevel_ignore_weight
                            ignore_vgroup = preference.behavior.sort_bevel_ignore_vgroup
                            ignore_verts = preference.behavior.sort_bevel_ignore_only_verts
                            props = {'use_only_vertices': True} if bpy.app.version[:2] < (2, 90) else {'affect': 'VERTICES'}
                            bvls = bevels(obj, weight=ignore_weight, vertex_group=ignore_vgroup, props=props if ignore_verts else {})
                            sort(obj, option=preference.behavior, ignore=bvls, sort_depth=preference.behavior.sort_depth)

                        bc.inset = new

                        for mod in bc.inset.modifiers:
                            if mod.type == 'WEIGHTED_NORMAL':
                                bc.inset.modifiers.remove(mod)

                        original_active = bpy.context.active_object
                        bpy.context.view_layer.objects.active = new
                        bpy.ops.mesh.customdata_custom_splitnormals_clear()
                        bpy.context.view_layer.objects.active = original_active

                        if preference.behavior.inset_slice:
                            slice_inset = obj.copy()
                            slice_inset.data = obj.data.copy()

                            for mod in slice_inset.modifiers:
                                if mod.type == 'BOOLEAN':
                                    if mod.object is new:
                                        mod.operation = 'INTERSECT'

                                    elif mod.object == bc.shape:
                                        slice_inset.modifiers.remove(mod)

                            for col in obj.users_collection:
                                col.objects.link(slice_inset)

                            op.datablock['slices'].append(slice_inset)

                    if op.mode == 'INSET':
                        op.datablock['insets'].append(new)

                    else:
                        op.datablock['slices'].append(new)

        hops = getattr(wm, 'Hard_Ops_material_options', False)

        if not len(bpy.data.materials[:]):
            hops = False

        if hops and hops.active_material:
            active_material = bpy.data.materials[hops.active_material]

            bc.shape.data.materials.clear()

            if op.mode not in {'SLICE', 'INSET', 'KNIFE', 'EXTRACT'}:
                bc.shape.data.materials.append(active_material)

                if op.mode != 'MAKE':
                    for obj in op.datablock['targets']:
                        mats = [slot.material for slot in obj.material_slots if slot.material]

                        obj.data.materials.clear()

                        for index, mat in enumerate(mats):
                            if not index or (mat != active_material or mat in op.existing[obj]['materials']):
                                obj.data.materials.append(mat)

                        if active_material not in obj.data.materials[:]:
                            obj.data.materials.append(active_material)

            elif op.mode in {'SLICE', 'INSET'}:
                for obj in op.datablock['targets']:
                    mats = [slot.material for slot in obj.material_slots if slot.material]

                    obj.data.materials.clear()

                    for index, mat in enumerate(mats):
                        if not index or (mat != active_material or mat in op.existing[obj]['materials']):
                            obj.data.materials.append(mat)

                    if op.mode == 'INSET' and active_material not in obj.data.materials[:]:
                        obj.data.materials.append(active_material)

                for obj in op.datablock['slices']:
                    obj.data.materials.clear()
                    obj.data.materials.append(active_material)

                for obj in op.datablock['insets']:
                    obj.data.materials.append(active_material)
                    mats = [slot.material for slot in obj.material_slots]
                    index = mats.index(active_material)

                    for mod in obj.modifiers:
                        if mod.type == 'SOLIDIFY':
                            mod.material_offset = index

                            break

        # XXX: ensure edit mode state
        if op.datablock['slices'] and op.original_mode == 'EDIT_MESH':
            for obj in op.datablock['slices']:
                obj.select_set(True)

            bpy.ops.object.mode_set(mode='OBJECT')
            bpy.ops.object.mode_set(mode='EDIT')


class Node:

    def __init__(self, value, nextnode=None):
        # 初始化结点结构
        self.value = value
        self.next_node = nextnode

    def get_next(self):
        return self.next_node

    def set_next(self, nextnode):
        self.next_node = nextnode

    def get_data(self):
        return self.value

    def set_value(self, value):
        self.value = value

class LinkedList:
    def __init__(self, root=None):
        # 初始化链表数据结构
        self.root = root    # 默认是链表第一个结点
        self.size = 0

    def get_size(self):
        return self.size

    def add(self, node:Node):
        new_node = Node(node, self.root)
        self.root = new_node
        self.size += 1

    def remove(self, node:Node):
        this_node = self.root
        pre_node = None

        while this_node is not None:
            if this_node.get_data() == node:
                #r 如果不是第一个结点
                if pre_node is not None:
                    pre_node.set_next(this_node.get_next())
                else:
                    self.root = this_node.get_next()
                self.size -= 1
                return True
            else:
                pre_node = this_node
                this_node = this_node.get_next()
        return False

    def find(self, node:None):
        this_node = self.root
        while this_node is not None:
            if this_node.get_data() == node:
                return node
            elif this_node.get_next() == None:
                return False
            else:
                this_node = this_node.get_next()

if __name__ == '__main__':

    link = LinkedList()
    for i in range(5):
        link.add(i)
    print('size: ', link.size)
    print(link.remove(3))


import re
from datetime import datetime, timedelta

import cv2 as cv
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.initializers import Zeros
from tensorflow.keras.models import load_model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import MeanSquaredError
import numpy as np

from buttons import BUTTONS_COUNT, BUTTON_STATES_COUNT
from video import VIDEO_WIDTH, VIDEO_HEIGHT
from tensorflow_hub import KerasLayer

def open_video(path):
    return cv.VideoCapture(path)

def parse_video_creation_time(video_path):
    match = re.match(r'.*StreetFighterV (\d\d\d\d)-(\d\d)-(\d\d) (\d\d)-(\d\d)-(\d\d)-(\d\d\d)\.mp4', video_path)
    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        day = int(match.group(3))
        hour = int(match.group(4))
        minute = int(match.group(5))
        second = int(match.group(6))
        millisecond = int(match.group(7))
        time = datetime(year, month, day, hour, minute, second, millisecond * 1000)
        return time
    else:
        raise ValueError('Failed to retrieve creation time from video path.')

def read_data(video, video_creation_time, actions):
    data = []
    last_frame_time = None
    first_action_index = 0
    while True:
        frame_time = video_creation_time + timedelta(milliseconds=video.get(cv.CAP_PROP_POS_MSEC))
        return_value, frame = video.read()
        if not return_value:
            return data
        if actions[first_action_index][0] <= frame_time:
            frame = cv.resize(frame, (VIDEO_WIDTH, VIDEO_HEIGHT))
            frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
            frame = np.array(frame, dtype=np.float32)
            frame /= 255.0
            frame = np.pad(
                frame,
                (
                    (0, VIDEO_WIDTH - frame.shape[0]),
                    (0, VIDEO_WIDTH - frame.shape[1]),
                    (0, 0)
                ),
                'constant',
                constant_values=0
            )
            last_action_index = first_action_index
            while last_action_index < len(actions) - 1:
                action_index = last_action_index + 1
                action = actions[action_index]
                if (
                    action[0] <= frame_time and
                    (last_frame_time is None or action[0] > last_frame_time)
                ):
                    last_action_index = action_index
                else:
                    break
            frame_actions = actions[first_action_index:last_action_index+1]
            action = to_action(frame_actions)
            entry = (frame, action)
            data.append(entry)
            first_action_index = last_action_index + 1
            if first_action_index >= len(actions):
                return data
        last_frame_time = frame_time

def to_action(frame_actions):
    action = [0] * (BUTTONS_COUNT * 2)
    for frame_action in frame_actions:
        code = frame_action[1]
        state = frame_action[2]
        if code == 'ABS_HAT0Y' and state == 0:
            action[0] = 1
            action[4] = 1
        elif code == 'ABS_HAT0X' and state == 0:
            action[2] = 1
            action[6] = 1
        elif code in {'BTN_WEST', 'BTN_NORTH', 'BTN_TR', 'BTN_TL', 'BTN_SOUTH', 'BTN_EAST', 'ABS_RZ', 'ABS_Z'}:
            index = frame_action_to_action_index(frame_action)
            action[index + (0 if is_press(frame_action) else 1)] = 1
    return action

def frame_action_to_action_index(frame_action):
    code = frame_action[1]
    state = frame_action[2]
    if code in {'ABS_HAT0X', 'ABS_HAT0Y', 'ABS_RZ', 'ABS_Z'}:
        if code == 'ABS_HAT0X':
            if state == -1:
                action_index = 2
            elif state == 1:
                action_index = 6
            else:
                raise ValueError('Unexpected value for status: ' + str(state))
        elif code == 'ABS_HAT0Y':
            if state == -1:
                action_index = 0
            elif state == 1:
                action_index = 4
            else:
                raise ValueError('Unexpected value for state: ' + str(state))
        elif code == 'ABS_RZ':
            action_index = 20
        elif code == 'ABS_Z':
            action_index = 22
    else:
        mapping = {
            'BTN_WEST': 8,
            'BTN_NORTH': 10,
            'BTN_TR': 12,
            'BTN_TL': 14,
            'BTN_SOUTH': 16,
            'BTN_EAST': 18,
        }
        if code in mapping:
            action_index = mapping[code]
        else:
            raise ValueError('Unexpected value for code: ' + code)

    return action_index

def is_press(frame_action):
    code = frame_action[1]
    state = frame_action[2]
    if code in {'ABS_HAT0X', 'ABS_HAT0Y', 'ABS_RZ', 'ABS_Z'}:
        is_press = True if state != 0 else False
    else:
        is_press = True if state == 0 else False
    return is_press

def read_actions(file):
    actions = []
    line = file.readline()
    while line:
        action = parse_action_entry(line)
        actions.append(action)
        line = file.readline()
    return actions

def parse_action_entry(line):
    match = re.match(r'\((\d+\.\d+), \'(.+?)\', (-?\d+)\)', line)
    if match:
        timestamp = datetime.fromtimestamp(float(match.group(1)))
        code = match.group(2)
        state = int(match.group(3))
        action = (timestamp, code, state)
        return action
    else:
        raise ValueError('match failed')

actions_file = open('actions_3.txt')
actions = read_actions(actions_file)
actions_file.close()
video_path = 'D:\\StreetFighterV 2021-06-13 06-29-24-000.mp4'
video_creation_time = parse_video_creation_time(video_path)
video = open_video(video_path)
data = read_data(video, video_creation_time, actions)
video.release()

model = Sequential([
    KerasLayer(
        "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4",
        input_shape=(224, 224, 3),
        trainable=False
    ),
    Dense(1048, activation='relu'),
    Dense(BUTTONS_COUNT * BUTTON_STATES_COUNT, kernel_initializer=Zeros()),
])

model.compile(
    optimizer=Adam(learning_rate=0.001),
    loss=MeanSquaredError(),
)
# model = load_model('model')

x = np.array([entry[0] for entry in data])
y = np.array([entry[1] for entry in data])
model.fit(
    x=x,
    y=y,
    epochs=100,
    batch_size=32,
    validation_split=0.2,
    callbacks=[
        EarlyStopping(patience=1)
    ]
)

model.save(r'D:\model_5')


from django.db import models
try:
    from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
    from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

from model_utils.models import TimeStampedModel

from ..conf import settings

class SkipRating(TimeStampedModel):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE)
    object_id = models.IntegerField(db_index=True, null=True)
    content_type = models.ForeignKey(
        ContentType,
        null=True,
        related_name='skip_rating_objects',
        on_delete=models.CASCADE)
    content_object = GenericForeignKey()
    comment = models.TextField(
        blank=True,
        null=True)
    category = models.CharField(
        max_length=250,
        blank=True,
        choices=settings.RATINGS_CATEGORIES)
    context_object_id = models.IntegerField(
        db_index=True,
        null=True)
    context_content_type = models.ForeignKey(
        ContentType,
        related_name='skip_rating_contexts',
        null=True,
        on_delete=models.CASCADE)
    context_object = GenericForeignKey(
        'context_content_type',
        'context_object_id',
    )

    class Meta:
        unique_together = [
            ('object_id', 'content_type', 'user', 'category', 'context_content_type', 'context_object_id'),
        ]

    def __str__(self):
        return '{} - {}'.format(self.category, self.user)


from datetime import datetime
import os
from renamer import proper_name
import shutil
import sys

# Copies back metadata from backup

backup = sys.argv[1]
target = sys.argv[2]

for root, dirs, files in os.walk(backup):
    for file in files:
        (no_ext_name, ext) = os.path.splitext(file)
        new_name = no_ext_name + ".mp4"
        relative_dir = root[(len(backup) + 1):]
        full_new_name = os.path.join(target, os.path.join(relative_dir, new_name))
        if not os.path.exists(full_new_name):
            print("ERROR %s" % (full_new_name,))
            continue
        create_time = datetime.fromtimestamp(os.path.getmtime(os.path.join(root, file)))
        rename_to = proper_name(full_new_name, create_time)
        if rename_to != full_new_name:
            shutil.move(full_new_name, rename_to)
            print("%s => %s" % (full_new_name, rename_to))


def reverse(string : str) -> str:
    '''
    A funtion to reverse the characters in a string
    '''
    try:
        #Reversing the letters and storing it
        reversed_string : str = string[::-1]
        #Returning the stored string
        return reversed_string
    except Exception as err:
        print(f'{err}')

print(reverse('I am Federal'))


#!/usr/bin/python3

"""When character are consecutive in a string , it is possible to shorten the
character string by replacing the character with a certain rule. For example,
in the case of the character string YYYYY, if it is expressed as # 5 Y, it is compressed by one character.
Write a Python program to restore the original string by entering the compressed
string with this rule. However, the # character does not appear in the restored character string.
Input:
The restored character string for each character on one line.
Original text: XY#6Z1#4023
XYZZZZZZ1000023
Original text: #39+1=1#30
999+1=1000"""

def decompress(string):
    result = string
    for i in range(len(string)):
        if string[i] == "#":
            n = result.find("#")
            result = result[:n] + result[n+2] * int(result[n+1]) + result[n+3:]
    return result

if __name__ == "__main__":
    text = input("Original text: ")
    print(decompress(text))


import tkinter as tk
from tkf import App
from viewable import Viewable
from megawidget import Toast
from cyberpunk_theme import Cyberpunk
from cyberpunk_theme.widget.button import get_button_red_style, get_button_blue_style

class Hello(Viewable):
    """Graphical equivalent of a Hello World"""
    def __init__(self, app):
        super().__init__()
        self._app = app
        self._root = app.root
        self._btn_max = None

    def _build(self):
        """This method is part of the view lifecycle"""
        self._body = tk.Frame(self._root)
        self._root.geometry("500x300")
        # Label
        label = tk.Label(self._body, text="Hello Friend !")
        label.pack(expand=1, fill=tk.BOTH)
        # Footer
        footer = tk.Frame(self._body)
        footer.pack(side=tk.BOTTOM, fill=tk.X, padx=2, pady=2)
        # Button Maximize
        self._btn_max = tk.Button(footer, text="Maximize",
                                  command=self._on_click_btn_max)
        self._btn_max.pack(side=tk.RIGHT, padx=(2, 0))
        # Button Crash
        btn_crash = tk.Button(footer, text="Crash",
                              command=self._on_click_btn_crash)
        btn_crash.pack(side=tk.RIGHT)
        # Styling
        button_red_style = get_button_red_style()
        button_blue_style = get_button_blue_style()
        button_red_style.target(btn_crash)
        button_blue_style.target(self._btn_max)

    def _on_click_btn_max(self):
        self._app.maximize()
        self._btn_max.destroy()

    def _on_click_btn_crash(self):
        toast = Toast(self._body, message="This app is going to crash...")
        toast.wait_window()
        self._app.crash_resistant = False
        raise Exception("Deliberately raised exception !")

def main():
    # The App
    app = App()
    # Set the title
    app.title = "demo"
    # Resizable
    app.resizable = (True, True)
    # Set the theme
    app.theme = Cyberpunk()
    # Set the view
    app.view = Hello
    # Center the window on the screen
    app.center()
    # Lift off !
    app.start()

if __name__ == "__main__":
    main()


#coding:utf-8
from LogHandle import Logger
import urllib3
# 分析html用的库
from bs4 import BeautifulSoup

Logger.info(u'开始')

# 忽略警告：InsecureRequestWarning: UnverifiIOError: [Errno 0] Errored HTTPS request
# is being made.  Adding certificate verification is strongly advised.
# requests.packages.urllib3.disable_warnings()
# 一个PoolManager实例来生成请求, 由该实例对象处理与线程池的连接以及线程安全的所有细节
http = urllib3.PoolManager()
# 通过request()方法创建一个请求：
r = http.request('GET', 'https://itunes.apple.com/cn/genre/ios-%E5%9B%BE%E4%B9%A6/id6018?mt=8')
Logger.info(r.status)  # 200
# 获得html源码,utf-8解码
                     # print(r.data.decode('gbk', 'ignore').encode('utf-8'))

# 解析html
soup = BeautifulSoup(r.data,'lxml')
# Logger.info(bs.title)

# 解析App Store
index = 0
# 获取分类列表页面的链接
classify = {}
for link in soup.select('#genre-nav a'):
	Logger.info(link.text + link.attrs['href'])
	classify[index] = {'title':link.text ,'href':link.attrs['href']}
	index+=1

# 字母顺序链接
alphabeticalOrder = {}
for alphabetical in soup.select('#selectedgenre ul')[0].select('a'):
	Logger.info(alphabetical.text + alphabetical.attrs['href'])
	alphabeticalOrder[alphabetical.text] = {'title':alphabetical.text ,'href':alphabetical.attrs['href']}
	#index+=1

# 翻页链接

# app详情页面链接
for info in soup.select('#selectedcontent a'):
	Logger.info(info.text + info.attrs['href'])

index=0

## 使用urllib2.open()方法发送请求,并返回服务器响应的类文件对象
#request = urllib2.Request('http://www.baidu.com')
## 类文件对象支持文件对象操作方法,如read()方法读取返回文件对象的全部内容并将其转换成字符串格式并赋值给html变量
#response = urllib2.urlopen(request)

## 打印html变量,即可显示出整个页面
#html = response.read()
#Logger.info(html)
## print(html)
## 解析html
#bs=BeautifulSoup(html,'lxml')
#print bs.title
def getHtml(url):
	'''
	获取指定网址的html代码
	'''
	pass


from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(622, 540)
        self.textEdit = QtWidgets.QTextEdit(Dialog)
        self.textEdit.setGeometry(QtCore.QRect(10, 20, 591, 41))
        self.textEdit.setStyleSheet("background-color: rgb(170, 255, 127);")
        self.textEdit.setObjectName("textEdit")
        self.tableWidget = QtWidgets.QTableWidget(Dialog)
        self.tableWidget.setGeometry(QtCore.QRect(10, 60, 591, 471))
        self.tableWidget.setStyleSheet("gridline-color: rgb(170, 255, 127);\n"
"alternate-background-color: rgb(170, 255, 127);\n"
"border-bottom-color: rgb(170, 255, 127);")
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setRowCount(10)
        item = QtWidgets.QTableWidgetItem()
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(6, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(7, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(8, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(9, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setBold(True)
        font.setUnderline(True)
        font.setWeight(75)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\png-transparent-broccoli-vegetable-cauliflower-leaf-vegetable-food-grass.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon)
        self.tableWidget.setItem(0, 1, item)
        item = QtWidgets.QTableWidgetItem()
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\png-transparent-arrow-computer-icons-down-arrow-angle-2d-computer-graphics-green-thumbnail.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon1)
        self.tableWidget.setItem(0, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(1, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-filipino-cuisine-water-spinach-asian-cuisine-leaf-morning-glory-5afe72ab6d4e78.7025633915266249394477.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon2)
        self.tableWidget.setItem(1, 1, item)
        item = QtWidgets.QTableWidgetItem()
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-division-subtraction-sign-mathematics-obelus-negative-money-cliparts-5a762f03039129.3712697915176947230146.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon3)
        self.tableWidget.setItem(1, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(1, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(2, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\carrot-png-5a21c005b1b8f3.250363361512161285728.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon4)
        self.tableWidget.setItem(2, 1, item)
        item = QtWidgets.QTableWidgetItem()
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-arrow-icon-up-arrow-transparent-png-5a77bcb44b9aa6.5964438415177965323097.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon5)
        self.tableWidget.setItem(2, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(2, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(3, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\transparent-eggplant-vegetable-purple-food-plant-5d6849f5cd4a88.3257814415671157658409.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon6)
        self.tableWidget.setItem(3, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon3)
        self.tableWidget.setItem(3, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(3, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(4, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-juice-food-eating-health-apple-apple-fruit-transparent-png-5a748186173281.061706731517584774095.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon7)
        self.tableWidget.setItem(4, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon3)
        self.tableWidget.setItem(4, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(4, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(5, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon8 = QtGui.QIcon()
        icon8.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\419-4197493_gambar-kartun-pisang-pisang-clipart-hd-png-download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon8)
        self.tableWidget.setItem(5, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon3)
        self.tableWidget.setItem(5, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(5, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(6, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon9 = QtGui.QIcon()
        icon9.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\watermelon-png-image-picture-download-5a35d8c7309967.7675305415134783431991.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon9)
        self.tableWidget.setItem(6, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon1)
        self.tableWidget.setItem(6, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(6, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(7, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon10 = QtGui.QIcon()
        icon10.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\png-clipart-fried-chicken-tandoori-chicken-pakistani-cuisine-pakora-jerk-seasoning-food-recipe.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon10)
        self.tableWidget.setItem(7, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon1)
        self.tableWidget.setItem(7, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(7, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(8, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon11 = QtGui.QIcon()
        icon11.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-fish-spice-flat-fish-5aa43cb28b5bf8.2805629915207128825708.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon11)
        self.tableWidget.setItem(8, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon5)
        self.tableWidget.setItem(8, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(8, 3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(9, 0, item)
        item = QtWidgets.QTableWidgetItem()
        icon12 = QtGui.QIcon()
        icon12.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-caridea-shrimp-condiment-lee-kum-kee-food-personalized-shrimp-platter-5a9cd8ae9e96a8.0946965815202285266496.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        item.setIcon(icon12)
        self.tableWidget.setItem(9, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setIcon(icon3)
        self.tableWidget.setItem(9, 2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(9, 3, item)
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(115)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(60)
        self.tableWidget.verticalHeader().setDefaultSectionSize(40)
        self.tableWidget.verticalHeader().setMinimumSectionSize(30)
        self.textEdit_2 = QtWidgets.QTextEdit(Dialog)
        self.textEdit_2.setGeometry(QtCore.QRect(40, 490, 121, 31))
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(430, 490, 71, 31))
        icon13 = QtGui.QIcon()
        icon13.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-check-mark-computer-icons-clip-art-green-check-mark-2-icon-5ab1d1c01cb222.3320573215216030081176.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton.setIcon(icon13)
        self.pushButton.setIconSize(QtCore.QSize(24, 24))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Dialog)
        self.pushButton_2.setGeometry(QtCore.QRect(350, 490, 71, 31))
        icon14 = QtGui.QIcon()
        icon14.addPixmap(QtGui.QPixmap("D:\\SMT.1\\ALPRO G\\kisspng-x-mark-check-mark-clip-art-wrong-sign-5b12e9983fd272.4809619715279661042614.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_2.setIcon(icon14)
        self.pushButton_2.setIconSize(QtCore.QSize(24, 24))
        self.pushButton_2.setObjectName("pushButton_2")
        self.spinBox = QtWidgets.QSpinBox(Dialog)
        self.spinBox.setGeometry(QtCore.QRect(170, 490, 41, 31))
        self.spinBox.setObjectName("spinBox")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(Dialog)
        self.plainTextEdit.setGeometry(QtCore.QRect(510, 70, 81, 141))
        self.plainTextEdit.setObjectName("plainTextEdit")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.textEdit.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Form Pemesanan Fresh Box
"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("Dialog", "1."))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(_translate("Dialog", "2."))
        item = self.tableWidget.verticalHeaderItem(2)
        item.setText(_translate("Dialog", "3."))
        item = self.tableWidget.verticalHeaderItem(3)
        item.setText(_translate("Dialog", "4."))
        item = self.tableWidget.verticalHeaderItem(4)
        item.setText(_translate("Dialog", "5."))
        item = self.tableWidget.verticalHeaderItem(5)
        item.setText(_translate("Dialog", "6."))
        item = self.tableWidget.verticalHeaderItem(6)
        item.setText(_translate("Dialog", "7."))
        item = self.tableWidget.verticalHeaderItem(7)
        item.setText(_translate("Dialog", "8."))
        item = self.tableWidget.verticalHeaderItem(8)
        item.setText(_translate("Dialog", "9."))
        item = self.tableWidget.verticalHeaderItem(9)
        item.setText(_translate("Dialog", "10."))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Dialog", "Kode Produk"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("Dialog", "Nama Produk"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("Dialog", "Harga / Biji"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("Dialog", "Stok tersedia"))
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        item = self.tableWidget.item(0, 0)
        item.setText(_translate("Dialog", "SB"))
        item = self.tableWidget.item(0, 1)
        item.setText(_translate("Dialog", "Brokoli"))
        item = self.tableWidget.item(0, 2)
        item.setText(_translate("Dialog", "9.000"))
        item = self.tableWidget.item(0, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(1, 0)
        item.setText(_translate("Dialog", "KK"))
        item = self.tableWidget.item(1, 1)
        item.setText(_translate("Dialog", "Kangkung"))
        item = self.tableWidget.item(1, 2)
        item.setText(_translate("Dialog", "4.000"))
        item = self.tableWidget.item(1, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(2, 0)
        item.setText(_translate("Dialog", "WTL"))
        item = self.tableWidget.item(2, 1)
        item.setText(_translate("Dialog", "Wortel"))
        item = self.tableWidget.item(2, 2)
        item.setText(_translate("Dialog", "20.000"))
        item = self.tableWidget.item(2, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(3, 0)
        item.setText(_translate("Dialog", "TRG"))
        item = self.tableWidget.item(3, 1)
        item.setText(_translate("Dialog", "Terong"))
        item = self.tableWidget.item(3, 2)
        item.setText(_translate("Dialog", "7.000"))
        item = self.tableWidget.item(3, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(4, 0)
        item.setText(_translate("Dialog", "APL"))
        item = self.tableWidget.item(4, 1)
        item.setText(_translate("Dialog", "Apel"))
        item = self.tableWidget.item(4, 2)
        item.setText(_translate("Dialog", "23.000"))
        item = self.tableWidget.item(4, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(5, 0)
        item.setText(_translate("Dialog", "PSG"))
        item = self.tableWidget.item(5, 1)
        item.setText(_translate("Dialog", "Pisang"))
        item = self.tableWidget.item(5, 2)
        item.setText(_translate("Dialog", "12.000"))
        item = self.tableWidget.item(5, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(6, 0)
        item.setText(_translate("Dialog", "SMK"))
        item = self.tableWidget.item(6, 1)
        item.setText(_translate("Dialog", "Semangka"))
        item = self.tableWidget.item(6, 2)
        item.setText(_translate("Dialog", "25.000"))
        item = self.tableWidget.item(6, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(7, 0)
        item.setText(_translate("Dialog", "AB"))
        item = self.tableWidget.item(7, 1)
        item.setText(_translate("Dialog", "Ayam Bumbu"))
        item = self.tableWidget.item(7, 2)
        item.setText(_translate("Dialog", "34.000"))
        item = self.tableWidget.item(7, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(8, 0)
        item.setText(_translate("Dialog", "IB"))
        item = self.tableWidget.item(8, 1)
        item.setText(_translate("Dialog", "Ikan Bumbu"))
        item = self.tableWidget.item(8, 2)
        item.setText(_translate("Dialog", "32.000"))
        item = self.tableWidget.item(8, 3)
        item.setText(_translate("Dialog", "10"))
        item = self.tableWidget.item(9, 0)
        item.setText(_translate("Dialog", "UB"))
        item = self.tableWidget.item(9, 1)
        item.setText(_translate("Dialog", "Udang Bumbu"))
        item = self.tableWidget.item(9, 2)
        item.setText(_translate("Dialog", "48.000"))
        item = self.tableWidget.item(9, 3)
        item.setText(_translate("Dialog", "10"))
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.textEdit_2.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Masukkan kode menu
"))
        self.pushButton.setText(_translate("Dialog", "Pesan"))
        self.pushButton_2.setText(_translate("Dialog", "Hapus"))
        self.plainTextEdit.setPlainText(_translate("Dialog", "Keterangan :\n"
"↑ Harga pasar naik\n"
"\n"
"↓ Harga pasar turun\n"
"\n"
"- Harga Rata-rata"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())


from py4j.clientserver import ClientServer, JavaParameters, PythonParameters
from py4j.java_collections import ListConverter

class OperatorTest(object):

    def __init__(self):
        self.client_server = None

    def set_server(self, client_server):
        self.client_server = client_server

    def test(self, data):
        self.client_server.jvm.System.out.println("Python处理中。。")
        data.append(5)
        python_list = [i for i in data]
        # https://www.py4j.org/advanced_topics.html#converting-python-collections-to-java-collections
        python_list = ListConverter().convert(python_list, self.client_server._gateway_client)

        return python_list

    def add(self, a, b):
        # gateway.jvm.System.out.println("完成加法计算！")
        return a + b

    class Java:
        implements = ["com.example.py4jdemo.utils.operators.OperatorTest",
                      "com.example.py4jdemo.utils.operators.Addition"]

if __name__ == '__main__':
    op_test = OperatorTest()
    # gateway = JavaGateway(
    #     gateway_parameters=GatewayParameters(port=25333),
    #     callback_server_parameters=CallbackServerParameters(port=22536),
    #     python_server_entry_point=average)
    clientServer = ClientServer(
        java_parameters=JavaParameters(port=25333),
        python_parameters=PythonParameters(port=25336),
        python_server_entry_point=op_test)
    op_test.set_server(clientServer)
    print("server started")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May  9 22:34:44 2020

@author: sakib
"""
from nltk.tokenize import word_tokenize
import gensim
import os
import numpy as np

def create_word2vec(directory,texts,EMBEDDING_DIM = 100,window = 5,workers = 4, min_count = 4,sg=1):
    tokens = []
    for line in texts:
        words = word_tokenize(line)
        tokens.append(words)

    model = gensim.models.Word2Vec(sentences = tokens, size = EMBEDDING_DIM, window = 5, workers = 4, min_count = 4,sg=1)
    print('Saving word2vec model in the disk')

    filename = 'embeddings_w2v.txt'
    model.wv.save_word2vec_format(directory+'/'+filename, binary = False)

    return model

def load_word2vec(filename,tokenizer_word_index,EMBEDDING_DIM):

    embedding_index = {}

    f = open(os.path.join('',filename), encoding = "utf-8")

    for line in f:
        values = line.split()
        word = values[0]
        coefs = np.asarray(values[1:])
        embedding_index[word] = coefs

    f.close()

    num_words = len(tokenizer_word_index) + 1
    embedding_matrix = np.zeros((num_words,EMBEDDING_DIM))
    for word,i in tokenizer_word_index.items():
        if i> num_words:
            continue
        embedding_vector = embedding_index.get(word)
        if embedding_vector is not None:
            embedding_matrix[i] = embedding_vector

    return embedding_matrix