from lxml import etree
import pika
import requests
from client.spider.base import Spider
import time
import threading
lock = threading.Lock()

class LieGoodsSpider(Spider):
    def __init__(self, cat_id,goods_id,goods_name, goods_sn,goods_desc, goods_thumb,site_url,
            ch, rk, is_first):
        Spider.__init__(self)

        self.cat_id = cat_id
        self.goods_id = goods_id
        self.goods_name = goods_name
        self.goods_sn = goods_sn
        self.goods_desc=goods_desc
        self.goods_thumb=goods_thumb
        self.url = site_url
        self.ch = ch
        self.rk = rk
        self.is_first = is_first
        self.headers = {"User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"}

    def goods(self, proxy_queue):
        global lock
        print('本地IP使用次数:', Spider.LOCAL_IP_USE_COUNT)
        print('代理IP使用次数:', Spider.PROXY_IP_USE_COUNT)
        if Spider.LOCAL_IP_USE_COUNT <= 5:
            with lock:
                Spider.LOCAL_IP_USE_COUNT += 1
            if Spider.LOCAL_IP_USE_COUNT >= 5:
                with lock:
                    Spider.PROXY_IP_USE_COUNT = 0
            return self.get_no_proxies(self.url, headers=self.headers, timeout=60)

        if Spider.PROXY_IP_USE_COUNT <= 5:
            with lock:
                Spider.PROXY_IP_USE_COUNT += 1
            if Spider.PROXY_IP_USE_COUNT >= 5:
                with lock:
                    Spider.LOCAL_IP_USE_COUNT = 0
            return self.get_use_proxies(self.url, self.headers, 60, self.ch, proxy_queue)

    def parse_goods(self,html):
        if html is None:
            return
        et = etree.HTML(html)
        # 供应商
        kc = 0
        stock = []
        manufacturer = str(et.xpath("//meta[@name='keywords']/@content")[0]).strip()
        try:
            kc = str(et.xpath("//span[@class='shipval']/text()")[0]).strip()
        except:
            kc = 0
        try:
            pdf_url = str(et.xpath("//a[@class='datasheet_align']/@href")[0]).strip()
        except:
            pdf_url = ""
        try:
            goods_img = str(et.xpath("//div[@id='outer-div1']/div/center/img/@src")[0]).strip()
        except:
            goods_img = ""
        tiered = []
        try:
            amount = str(et.xpath("//span[@class='usdpart1 usdpartHighlight']/span/text()")[0]).strip()
            price = str(et.xpath("//span[@class='usdpart1 usdpartHighlight']/p/text()")[0]).strip()
            tiered.append([int(amount), float(price[1:])])
        except:
            pass
        try:
            datas = et.xpath("//span[@class='usdpart1 ']")
            for data in datas:
                amount = str(data.xpath("./span/text()")[0]).strip()
                price = str(data.xpath("./p/text()")[0]).strip()
                tiered.append([int(amount), float(price[1:])])
        except:
            pass
        MOQ = str(et.xpath("//input[@id='quoteMin1']/@value")[0]).strip()
        stock.append(int(MOQ))
        stock.append(kc)
        multi = str(et.xpath("//input[@id='quoteMult1']/@value")[0]).strip()

        #　若是第一次更新
        if self.is_first:
            # ********************************************** brand
            lieBrand = {
                'brand_name': manufacturer,
                'site_url': '',
                'brand_logo': '',
                'brand_desc': '',
                'web_url': ''
            }
            body = str({"3": lieBrand})
            print('Sent 3. 更新lie_brand', body)
            self.ch.basic_publish(exchange='',
                    routing_key=self.rk,
                    properties=pika.BasicProperties(
                        delivery_mode=2),
                    body=body)
            body = ''

            # ********************************************** goods
            lg = {
                'goods_id': self.goods_id,
                'goods_sn': self.goods_sn,
                'provider_name': manufacturer,
                'goods_name': self.goods_name,
                'goods_desc': self.goods_desc,
                'site_url': self.url,
            }
            body = str({"1": lg})
            print('Sent 1. 更新mysql', body)
            self.ch.basic_publish(exchange='',
                    routing_key=self.rk,
                    properties=pika.BasicProperties(
                        delivery_mode = 2),
                    body=body)
            body = ''

            # ********************************************** price
            goods_price = []
            for ti in tiered:
                tmp = {'purchases': ti[0], 'price': ti[1]}
                goods_price.append(tmp)

            if goods_price != []:
                body = {'price': goods_price,
                        'goods_id': self.goods_id}
                body = str({"4": body})
                self.ch.basic_publish(exchange='',
                        routing_key=self.rk,
                        properties=pika.BasicProperties(
                            delivery_mode = 2),
                        body=body)
            body = ''

            # 更新mongo
            # ********************************************** avnet
            avnet = dict()
            avnet['goods_id'] = self.goods_id
            avnet['goods_name'] = self.goods_name
            avnet['goods_sn'] = self.goods_sn
            avnet['brand_name'] = manufacturer
            avnet['desc'] = self.goods_desc
            avnet['docurl'] = pdf_url
            avnet['pn'] = 'avnet'
            avnet['MOQ'] = MOQ
            avnet['pdf_url']=pdf_url
            avnet['goods_img']=goods_img
            avnet['stock'] = stock
            avnet['tiered'] = tiered
            avnet['increment'] = multi
            avnet['time'] = int(time.time())
            avnet['url'] = self.url
            body = str({"2": avnet})
            print('Sent 2. 更新mongo', body)
            self.ch.basic_publish(exchange='',
                    routing_key=self.rk,
                    properties=pika.BasicProperties(
                        delivery_mode = 2),
                    body=body)

        # 第二次更新
        else:

            # 更新mongo
            #TODO
            avnet = dict()
            avnet['goods_id'] = self.goods_id
            avnet['goods_name'] = self.goods_name
            avnet['goods_sn'] = self.goods_sn
            avnet['brand_name'] = manufacturer
            avnet['desc'] = self.goods_desc
            avnet['docurl'] = pdf_url
            avnet['pn'] = 'avnet'
            avnet['MOQ'] = MOQ
            avnet['pdf_url']=pdf_url
            avnet['goods_img']=goods_img
            avnet['stock'] = stock
            avnet['tiered'] = tiered
            avnet['increment'] = multi
            avnet['time'] = int(time.time())
            avnet['url'] = self.url
            body = str({"2": avnet})
            print('Sent 2. 更新mongo', body)
            self.ch.basic_publish(exchange='',
                    routing_key=self.rk,
                    properties=pika.BasicProperties(
                        delivery_mode = 2),
                    body=body)

if __name__ == '__main__':
    #信息格式如下
    params = {'cat_id': 1,
              'goods_id': 1,
              'goods_name': '',
              'goods_sn': '',
              'goods_desc': '',
              'goods_thumb':"",
              'site_url':""}
    from client.recv_cron.avnet import recv_goods
    conn = recv_goods.get_rb_conn()
    ch = conn.channel()
    rk = 'avnet_store_goods'
    ch.queue_declare(queue=rk)
    lgs = LieGoodsSpider(params['cat_id'],
            params['goods_id'],
            params['goods_name'],
            params['goods_sn'],
            params['goods_desc'],
            params['goods_thumb'],
            params['site_url'],
            ch, rk, is_first=False)
    html = lgs.goods()
    lgs.parse_goods(html)


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

import csv
# Leitura da tabela ACTION-GOTO
def leitutragoto():
    file = open('Sintatico\ACTION-GOTO.csv',encoding='utf-8')
    ACTIONGOTO = csv.reader(file,delimiter=';')

    header = {}
    n = 0
    for c in next(ACTIONGOTO):
      header.update({c:n})
      n+=1

    tabela = list(ACTIONGOTO)
    return tabela,header
# Regras gramaticais
def gramatica():
    gramatica = {
        1: "P'->P", 2: "P->inicio V A", 3: "V->varincio LV", 4: "LV->D LV", 5: "LV->varfim pt_v",
        6: "D->TIPO L pt_v", 7: "L->id", 8: "TIPO->inteiro", 9: "TIPO->real", 10: "TIPO->literal",
        11: "A->ES A", 12: "ES->leia id pt_v", 13: "ES->escreva ARG pt_v", 14: "ARG->lit", 15: "ARG->num",
        16: "ARG->id", 17: "A->CMD A", 18: "CMD->id rcb LD pt_v", 19: "LD->OPRD opm OPRD", 20: "LD->OPRD",
        21: "OPRD->id", 22: "OPRD->num", 23: "A->COND A", 24: "COND->CAB CP", 25: "CAB->se ab_p EXP_R fc_p então",
        26: "EXP_R->OPRD opr OPRD", 27: "CP->ES CP", 28: "CP->CMD CP", 29: "CP->COND CP", 30: "CP->fimse",
        31: "A->R A", 32: "R->CABR CPR", 33: "CABR->repita ab_p EXP_R fc_p", 34: "CPR->ES CPR", 35: "CPR->CMD CPR",
        36: "CPR->COND CPR", 37: "CPR->fimrepita", 38: "A->fim"
    }
    return gramatica
# Follow de não terminais
def follow():
    follow = {
        "P'": 'EOF',
        "P": 'EOF',
        "V": 'leia escreva ID se repita fim',
        "LV": 'leia escreva id se repita fim',
        "D": 'inteiro real literal varfim',
        "L": 'PT_V',
        "TIPO": 'ID',
        "A": 'EOF',
        "ES": 'leia escreva ID se repita fim fimse fimrepita',
        "ARG": 'PT_V',
        "CMD": 'leia escreva ID se repita fim fimse fimrepita',
        "LD": 'PT_V',
        "OPRD": 'OPM PT_V OP FC_P',
        "COND": 'leia escreva ID se repita fim fimse fimrepita',
        "CAB": 'leia escreva ID se fimse',
        "EXP_R": 'FC_P',
        "CP": 'leia escreva ID se repita fim fimse fimrepita',
        "R": 'leia escreva ID se repita fim',
        "CABR": 'leia escreva ID se fimrepita',
        "CPR": 'leia escreva ID se repita fim'
    }
    return follow


#!/usr/bin/env python3
import sys
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
from itertools import accumulate

sys.setrecursionlimit(10**6)
INF = 10**12
m = 10**9 + 7

def prime_factorize(N):
    prime_list = []
    while N % 2 == 0:
        prime_list.append(2)
        N //= 2
    f = 3
    while f**2 <= N:
        if N % f == 0:
            prime_list.append(f)
            N //= f
        else:
            f += 2
    if N != 1:
        prime_list.append(N)
    return prime_list

def main():
    N = int(input())
    if N == 1:
        print('BOWWOW')
        exit()
    N = N * (N + 1) // 2
    if len(prime_factorize(N)) == 1:
        print('WANWAN')
    else:
        print('BOWWOW')

if __name__ == "__main__":
    main()


#!/usr/bin/env python

# github.com/rubicks/trythis/python/kadane.py

import sys

def _kadane_idx(arr):
    ret = here = -sys.maxsize-1
    itmp = 0
    ibeg = 0
    iend = 0
    for i, e in enumerate(arr):
        here += e
        if here < e:
            here = e
            itmp = i
        if ret < here:
            ret = here
            ibeg = itmp
            iend = i + 1
    return ret, ibeg, iend

def _kadane(arr):
    return _kadane_idx(arr)[0]

def main():
    print(_kadane_idx(list(map(int, sys.argv[1:]))))
    return

if "__main__" == __name__:
    main()
    exit(0)


import torch
from torch.autograd import Function
from eaconv._ext import eaconv2d

def _conv_output_dim(inputDim, pad, filterDim, dilation, stride):
    tmp = 1 + (inputDim + 2 * pad - (((filterDim - 1) * dilation) + 1))
    if tmp % stride == 0\
            and pad >= 0\
            and stride >= 1\
            and dilation >= 1\
            and tmp > 0:
        return tmp // stride
    else:
        raise ValueError('Parameters of the kernel must be compatible '
                         'with the dimensions of the input')

class EAConv2dFunction(Function):

    def __init__(self, stride, padding, dilation, groups):
        super(EAConv2dFunction, self).__init__()
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.groups = groups

    def forward(self, *bias_inp_and_weight):
        num_inp = len(bias_inp_and_weight) // 2
        inp = bias_inp_and_weight[:num_inp]
        if len(bias_inp_and_weight) % 2 == 1:
            weight = bias_inp_and_weight[num_inp:-1]
            bias = bias_inp_and_weight[-1]
        else:
            weight = bias_inp_and_weight[num_inp:]
            bias = None

        self.saved_for_later = inp, weight, bias
        stride = self.stride
        padding = self.padding
        dilation = self.dilation
        groups = self.groups

        h = _conv_output_dim(inp[0].size(2), padding[0],
                             weight[0].size(2), dilation[0], stride[0])
        w = _conv_output_dim(inp[0].size(3), padding[1],
                             weight[0].size(3), dilation[1], stride[1])
        output = inp[0].new(inp[0].size(0), weight[0].size(0), h, w).zero_()
        if bias is not None:
            eaconv2d.EAConv2d_cuda_forward_bias(bias, output)
        for _inp, _weight in zip(inp, weight):
            if not isinstance(_inp, torch.cuda.FloatTensor):
                raise NotImplementedError
            eaconv2d.EAConv2d_cuda_forward(_inp, _weight, output,
                                           stride[0], stride[1],
                                           padding[0], padding[1],
                                           dilation[0], dilation[1],
                                           groups)
        return output

    def backward(self, gradOutput):
        gradOutput = gradOutput.contiguous()

        inp, weight, bias = self.saved_for_later

        stride = self.stride
        padding = self.padding
        dilation = self.dilation
        groups = self.groups

        if bias is not None:
            grad_bias = bias.new(*bias.size()).zero_()
        else:
            grad_bias = None

        grad_inp = []
        grad_weight = []
        for _inp in inp:
            grad_inp.append(_inp.new(*_inp.size()).zero_())
        for _weight in weight:
            grad_weight.append(_weight.new(*_weight.size()).zero_())

        if bias is not None:
            eaconv2d.EAConv2d_cuda_backward_bias(grad_bias, gradOutput)
        for _inp, _weight, _grad_inp, _grad_weight in zip(inp, weight,
                                                          grad_inp,
                                                          grad_weight):
            eaconv2d.EAConv2d_cuda_backward(_grad_inp, _grad_weight,
                                            gradOutput,
                                            _inp, _weight,
                                            stride[0], stride[1],
                                            padding[0], padding[1],
                                            dilation[0], dilation[1],
                                            groups)
        return_val = tuple(grad_inp) + tuple(grad_weight)
        if bias is not None:
            return_val = return_val + (grad_bias,)
        return return_val


import numpy as np
import torch
import torch.nn as nn
from .utils import register_model, get_model
from . import cos_norm_classifier

@register_model('MannNet')
class MannNet(nn.Module):

    """Defines a Dynamic Meta-Embedding Network."""

    def __init__(self, num_cls=10, model='LeNet', src_weights_init=None,
                 weights_init=None, use_domain_factor_selector=False, centroids_path=None, feat_dim=512):

        super(MannNet, self).__init__()

        self.name = 'MannNet'
        self.base_model = model
        self.num_cls = num_cls
        self.feat_dim = feat_dim
        self.use_domain_factor_selector = use_domain_factor_selector
        self.cls_criterion = nn.CrossEntropyLoss()
        self.gan_criterion = nn.CrossEntropyLoss()

        self.centroids = torch.from_numpy(np.load(centroids_path)).float().cuda()
        assert self.centroids is not None
        self.centroids.requires_grad = False

        self.setup_net()

        if weights_init is not None:
            self.load(weights_init)
        elif src_weights_init is not None:
            self.load_src_net(src_weights_init)
        else:
            raise Exception('MannNet must be initialized with weights.')

    def forward(self, x_s, x_t):

        """Pass source and target images through their respective networks."""

        score_s, x_s = self.src_net(x_s, with_ft=True)
        score_t, x_t = self.tgt_net(x_t, with_ft=True)

        if self.discrim_feat:
            d_s = self.discriminator(x_s.clone())
            d_t = self.discriminator(x_t.clone())
        else:
            d_s = self.discriminator(score_s.clone())
            d_t = self.discriminator(score_t.clone())

        return score_s, score_t, d_s, d_t

    def setup_net(self):

        """Setup source, target and discriminator networks."""
        self.src_net = get_model(self.base_model, num_cls=self.num_cls, feat_dim=self.feat_dim)
        self.tgt_net = get_model(self.base_model, num_cls=self.num_cls, feat_dim=self.feat_dim)

        input_dim = self.num_cls

        self.discriminator = nn.Sequential(
            nn.Linear(input_dim, 500),
            nn.ReLU(),
            nn.Linear(500, 500),
            nn.ReLU(),
            nn.Linear(500, 2),
            )

        self.fc_selector = nn.Linear(self.feat_dim, self.feat_dim)

        if self.use_domain_factor_selector:
            self.domain_factor_selector = nn.Linear(self.feat_dim, self.feat_dim)

        self.classifier = cos_norm_classifier.create_model(self.feat_dim, self.num_cls)

        self.image_size = self.src_net.image_size
        self.num_channels = self.src_net.num_channels

    def load(self, init_path):
        """Loads full src and tgt models."""
        net_init_dict = torch.load(init_path)
        self.load_state_dict(net_init_dict)

    def load_src_net(self, init_path):
        """Initialize source and target with source weights."""
        self.src_net.load(init_path)
        self.tgt_net.load(init_path)

        net_init_dict = torch.load(init_path)
        classifier_weights = net_init_dict['classifier.weight']

        self.classifier.weight.data = classifier_weights.data.clone()

    def save(self, out_path):
        torch.save(self.state_dict(), out_path)

    def save_tgt_net(self, out_path):
        torch.save(self.tgt_net.state_dict(), out_path)


def cards(deck, hand):
    every_card = []
    for card in range(1, deck+1):
        every_card += [[card-1, card]]
    found = True
    hand.sort()
    #print(every_card)
    while hand:
        if found == False:
            return False
        found = False
        check = hand[0]
        hand = hand[1:]
        for card in every_card:
            if check in card:
                every_card.remove(card)
                print(every_card)
                found = True
                break

    return True if found == True else False
print(cards(25,[17,11,16,12,5,12,11]))
"""

"""


import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
onehot_encoder = OneHotEncoder(sparse=False)
from numpy import linalg as la

np.random.seed(42)

class MultiClassLogesticRegression:
    def __init__(self, lr=0.01, epochs=100):
        self.lr = lr
        self.epochs = epochs

    def of_grad(self, X, Y, W, nu):
        Z = -X @ W
        P = self.Softmax(Z, ax=1)
        N = X.shape[0]
        gd = (1 / N) * (X.T @ (Y - P)) + 2 * nu * W
        return gd

    def Softmax(self, x, ax=1):
        max = np.max(x, axis=ax, keepdims=True)  # returns max of each row and keeps same dims
        e_x = np.exp(x - max)  # subtracts each row with its max value
        sum = np.sum(e_x, axis=ax, keepdims=True)  # returns sum of each row and keeps same dims
        f_x = e_x / sum
        return f_x

    def sigmoid(self, z):
        return 1 / (1 + np.exp(-z))

    def gradient_descent(self, X, Y, max_itr=1000, alpha=0.1, nu=0):
        self.Y_onehot = onehot_encoder.fit_transform(Y.reshape(-1, 1))
        self.W = np.zeros((X.shape[1], self.Y_onehot.shape[1]))
        i = 0
        ilist = []
        losslist = []
        while i < max_itr:
            i = i + 1
            self.W -= alpha * self.of_grad(X, self.Y_onehot, self.W, nu)
            ilist.append(i)
            losslist.append(self.loss(X, self.Y_onehot, self.W, 0))
            # print(W)

            df = pd.DataFrame({'i': ilist, 'loss': losslist})

        return self.W, df

    def loss(self, X, Y, W, nu):
        Z = - X @ W
        N = X.shape[0]
        loss = 1 / N * (np.trace((X @ W) @ Y.T) + np.sum(np.log(np.sum(np.exp(Z), axis=1)))) + (nu * la.norm(W, 2))
        return loss

    def fit(self, X, Y):
        self.n_samples = X.shape[0]
        self.n_features = X.shape[1]
        self.W = np.random.randn(self.n_features)
        self.b = np.random.randn()
        self.W, self.lossplotinfo = self.gradient_descent(X, Y)

    def predict(self, A):
        Z = -A @ self.W
        P = self.Softmax(Z)
        return np.argmax(P, axis=1)

    def loss_v_i_plot(self):
        return self.lossplotinfo.plot(x='i',
                                      y='loss',
                                      xlabel='i',
                                      ylabel='loss')


"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""
def isPalindrome(left, right, array):
    if left+1 == right+1 and array[left] == array[right]:
        return True
    if left + 1 == right and array[left] == array[right]:
        return True
    if array[left] == array[right]:
        return isPalindrome(left+1, right-1, array)
    return False

if __name__ == '__main__':
    answer = 0
    for x in range(100, 999):
        for y in range(999, 100, -1):
            num = [int(z) for z in str(x*y)]
            if isPalindrome(0, len(num)-1, num):
                if x*y > answer:
                    answer = x*y
    print(answer)


import numpy
import math
from gnuradio import gr

class assign_freq_cf(gr.sync_block):
    """
    docstring for block assign_freq_cf
    """
    def __init__(self):
        gr.sync_block.__init__(self,
            name="assign_freq_cf",
            in_sig=[numpy.complex64],
            out_sig=[numpy.float32])

    def work(self, input_items, output_items):
    	#in0 = round(input_items[0], 4)
    	in0 = numpy.around(input_items[0].real,4)+(1j*numpy.around(input_items[0].imag,4))
    	#in0 = input_items[0]
    	out = output_items[0]
    	#print(in0[0])
    	#GR_M_SQRT2 = 1.41421356237309504880*math.sqrt(2)
    	GR_M_SQRT2 = round(math.sqrt(2)/2.0, 4)
    	#print(GR_M_SQRT2 + 1j*GR_M_SQRT2)
    	for i in range(len(in0)):
    		#print("Nuevo: ")
    		#print(round(in0[i].real,4)+(1j*round(in0[i].imag,4)))
    		#print(in0[i])
    		#print(complex(in0[i]) == complex((GR_M_SQRT2 + 1j*GR_M_SQRT2)))
    		if in0[i].real>=0.7 and in0[i].real<=0.75 and in0[i].imag>=0.7 and in0[i].imag<=0.75:
    			out[:] = 1
    		elif in0[i].real>=-0.75 and in0[i].real<=-0.7 and in0[i].imag>=0.7 and in0[i].imag<=0.75:
    			out[:] = 2
    		elif in0[i].real>=-0.75 and in0[i].real<=-0.7 and in0[i].imag>=-0.75 and in0[i].imag<=-0.7:
    			out[:] = 3
    		else:
    			out[:] = 4

    	return len(out)


import socket
import threading

PORT = 4720
IP = '192.168.1.61'

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((IP, PORT))

def receive():
   while True:
      try:
         message = client.recv(1024).decode('utf8')

         # if the messages from the server is NAME send the client's name
         if message == 'NAME':
            client.send(b'hello there')
         else:
            # insert messages to text box
            print(message)
      except:
         # an error will be printed on the command line or console if there's an error
         print("An error occured!")
         client.close()
         break

# function to send essages
def sendMessage():
   while True:
      message = input('nhap tin nhan: ')
      client.send(message.encode('utf8'))

recv_thread = threading.Thread(target=receive)
recv_thread.start()

send_thread = threading.Thread(target=sendMessage)
send_thread.start()


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

__author__ = 'T.ASAO <asao@sateraito.co.jp>'

import logging
import json
import datetime
import re
import sateraito_inc
import sateraito_func
from ucf.utils.ucfutil import *
from logiccommands.basecommand import *

#######################################
# PATTERN:正規表現コマンド
#  正規表現で文字列を抽出
#
#
# PATTERN	URL $pattern_result /content
# PATTERN	EMAIL $pattern_result /content
# PATTERN	'([^\s　。、]+)[\s　]*(?=様|さま|さん)' $pattern_result /content
#
#
#
#######################################
class PatternCommand(BaseCommand):
	def __init__(self, element_list, parent_command, script_row_num, params):
		super(PatternCommand, self).__init__(element_list, parent_command, script_row_num, params)

	# 解析
	def _analysis(self):

		if len(self.element_list) < 4:
			raise Exception(self.getMsg('CMDERR_NOEXIST_NEED_ELEMENTS'))

		# パターン
		pattern_element = self.getElementObj(1)

		# 結果をセットする変数
		target_element = self.getElementObj(2)
		if target_element.get('type') == 'literal':
			raise Exception(self.getMsg('CMDERR_INVALID_ELEMENT_KIND', (str(2), 'result', target_element.get('value'), self.getMsg('CONSTANT'), ','.join([self.getMsg('VARIABLE'), self.getMsg('JSONXPATH')]))))
		if not target_element.get('value').startswith('$') and not target_element.get('value').startswith('/'):
			raise Exception(self.getMsg('CMDERR_INVALID_ELEMENT_KIND2', (str(2), 'result', target_element.get('value'), ','.join([self.getMsg('VARIABLE'), self.getMsg('JSONXPATH')]))))

		# 検索する文字列
		value_element = self.getElementObj(3)
		# 定数でも変数でもJSONXPATHでもなければNG
		if not value_element.get('type') == 'literal' and not value_element.get('value').startswith('$') and not value_element.get('value').startswith('/'):
			raise Exception(self.getMsg('CMDERR_INVALID_ELEMENT_KIND2', (str(3), 'search_contents', value_element.get('value'), ','.join([self.getMsg('CONSTANT'), self.getMsg('VARIABLE'), self.getMsg('JSONXPATH')]))))

		# オプション：最大何個結果を取得するか（1以外の場合は、リストで返す. 未指定の場合もリスト）
		max_result_cnt_element = self.getElementObj(4)
		if max_result_cnt_element is not None:
			pass

	# コマンド実行
	def _execute(self):

		# パターン
		pattern_element = self.getElementObj(1)
		# 正規表現文字列
		pattern = ''
		# 定数の場合そのまま使用
		if pattern_element.get('type') == 'literal':
			pattern = pattern_element.get('value')

 		# 変数、JSONパスの場合
		elif pattern_element.get('value').startswith('$') or pattern_element.get('value').startswith('/'):
			pattern = self.getValue(pattern_element.get('value'))

 		# パターン指定子の場合、正規表現を作成
		# URLを抽出
		elif pattern_element.get('value') == 'URL':
			pattern = r"(https?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)"
		# EMAILパターン
		elif pattern_element.get('value') == 'EMAIL':
			pattern = r"([!-Z^-~]+@[!-Z^-~]+\.[!-Z^-~]+)"
		else:
			raise Exception(self.getMsg('CMDERR_INVALID_PATTERN', (str(1), 'pattern', pattern_element.get('value'), 'URL,EMAIL')))

		if pattern == '':
			raise Exception(self.getMsg('CMDERR_INVALID_PATTERN_FORMAT', (str(1), pattern)))

		logging.info('pattern=' + pattern)

		# 検索コンテンツ
		logging.info(self.getElementObj(3).get('value'))
		search_target = self.getValue(self.getElementObj(3))

		logging.info(search_target)

		# goku edit
		try:
			pattern_uni = pattern
			if not isinstance(pattern, unicode) and isinstance(pattern, basestring):
				pattern_uni = unicode(pattern, 'utf-8')
			search_target_uni = search_target
			if not isinstance(search_target, unicode) and isinstance(search_target, basestring):
				search_target_uni = unicode(search_target, 'utf-8')
			search_result = re.findall(pattern_uni, search_target_uni, re.UNICODE)
		except:
			# 検索
			search_result = re.findall(pattern, search_target)

		logging.info(search_result)

		# オプション最大何個結果を返すか（1の場合のみ配列ではなく文字列で返す）
		max_result_cnt = 0
		max_result_cnt_element = self.getElementObj(4)
		logging.info(max_result_cnt_element)
		if max_result_cnt_element is not None:
			max_result_cnt = self.getValue(max_result_cnt_element)
			if not isinstance(max_result_cnt, (int, long, float)):
				max_result_cnt = 0
			else:
				max_result_cnt = int(max_result_cnt)

		if max_result_cnt == 1:
			search_result = search_result[0] if len(search_result) >= 1 else ''
		elif max_result_cnt > 0:
			search_result = search_result[0:max_result_cnt]

		# 結果をセット
		target_element = self.getElementObj(2)
		self.setValue(target_element.get('value'), search_result)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path("<int:aluno_id>", views.aluno, name="aluno"),
    path('tempo/<int:id>', views.add_tempo, name='add_tempo'),
    path('busca/', views.busca, name='busca'),
    path('deletar/<int:id>', views.deletar, name='deletar'),
]


def get_places_num(dic):
    lis = []
    for k, v in dic.items():
        if v not in lis:
            lis.append(v)
    return len(lis)

def get_coefficient(name, place, places):
    if place >= 1:
        coefficient = round(100 - ((place - 1) * 100 / places))
    if place < 1:
        coefficient = round(100 * place)
    print(f'{name} with {place} place has {coefficient} coef')

def iterate(dic):
    for name, place in dic.items():
        get_coefficient(name, place, get_places_num(dic))
        print('places', get_places_num(dic))
    print()

situations = {'one player done 100%':
                  {'p1': 1},

              'one player done 60%':
                  {'p1': 0.6},

              'one player done 0%':
                  {'p1': 0},

              'one player done -50%':
                  {'p1': -0.5},

              'one player done -100%':
                  {'p1': -1},

              'all players have different places':
                  {'p1': 1,
                   'p2': 2,
                   'p3': 3,
                   'p4': 4,
                   'p5': 5},

              'some players have similar places':
                  {'p1': 1,
                   'p2': 2,
                   'p3': 2,
                   'p4': 3,
                   'p5': 4}}

for situation_name, players_and_places in situations.items():
    print(situation_name)
    for player_name, player_place in players_and_places.items():
        get_coefficient(player_name, player_place, get_places_num(players_and_places))
    print()


'''
python: Shopping Cart module

by Alexander Shinkov (@ashinkov)

TODO:
Carts should be created with an IngredientsStore instance.

from cart import Cart

shopping_cart = Cart(ingredient_store)
Ingredients can be added to a cart by name, with an optional quantity parameter.

shopping_cart.add('tomatoes')
shopping_cart.add('onions', 3)

The total for the cart can be calculated with get_total().
This method optionally takes a list of Discount objects that are applied
to items in the cart when calculating the total.

'''

from python_shopping.ingredients import IngredientsStore

class Cart:

    # Create dict cart_map: ingredient_name, number_of_items
    #
    cart_map = {}

    # getting ingredient dictionary from ingredients
    #
    def __init__(self, ingredient_store):
        self.ingredients_store = ingredient_store

    # 1st method - adding ingredient_name + number_of_items to cart (default number_of_items=1)
    #
    def add(self, ingredient_name, number_of_items=1):

        # checking/proceeding with positive number_of_items
        #
        if number_of_items > 0:

            # if ingredient_name exists in ingredients_store
            #
            if ingredient_name in self.ingredients_store.ingredients_map.keys():

                # if ingredient_name exists in our cart_map then +number_of_items
                # (+1 by default if no number_of_items mentioned)
                #
                if ingredient_name in self.cart_map.keys():
                    self.cart_map[ingredient_name] = self.cart_map.get(ingredient_name) + number_of_items

                # if ingredient_name does not exist in ingredients_store: +ingredient_name +number_of_items
                #
                else:
                    self.cart_map[ingredient_name] = number_of_items

    # on top:
    # if number_of_items is negative then subtracting if only the
    #
    def subtract(self, ingredient_name, number_of_items=1):

        if ingredient_name in self.cart_map.keys() and number_of_items > self.cart_map.get(ingredient_name):
            self.cart_map[ingredient_name] = self.cart_map.get(ingredient_name) - number_of_items

        if ingredient_name in self.cart_map.keys() and number_of_items == self.cart_map.get(ingredient_name):
            del self.cart_map[ingredient_name]

    # calculate total for the shopping cart
    #
    def get_total(self, discount_list=[]):   # discount_list empty by default

        # final total value (0 is default)
        #
        summary = 0

        # for each ingredient in cart:
        # if ingredient exists in discounts then adding to 'final total' the price with applied discount
        #
        for ingredient in self.cart_map:

            # for each discountList: f(x) = x.ingredient_name
            #
            if ingredient in list(map(lambda x: x.ingredient_name, discount_list)):

                # for each discountList: f(x) = x.ingredient_name and filter by ingredient_name
                # calculate_line_total for ingredient in cart_map with quantity
                # taking 1st element [0]
                #
                summary += list(filter(lambda x: x.ingredient_name == ingredient, discount_list))[0]\
                    .calculate_line_total(self.cart_map.get(ingredient), self.ingredients_store.get_ingredient_price(ingredient))

            # if no discounts available - then simply calculating price * quantity
            #
            else:
                summary += self.cart_map.get(ingredient) * self.ingredients_store.get_ingredient_price(ingredient)

        return summary


import torch
import torch.nn as nn
import torch.nn.functional as F
import math

def l2_norm(input, axis=1):
    norm = torch.norm(input, 2, axis, True)
    output = torch.div(input, norm)
    return output

class ArcFaceHead(nn.Module):
    def __init__(self, classnum, embedding_size=512, s=64.0, m=0.5):
        super(ArcFaceHead, self).__init__()
        self.weight = nn.Parameter(torch.FloatTensor(classnum, embedding_size))
        nn.init.xavier_uniform_(self.weight)

        self.m = m  # the margin value, default is 0.5
        self.s = s  # scalar value default is 64, see normface https://arxiv.org/abs/1704.06369
        self.eps = 1e-6

    def forward(self, embbedings, labels=None):
        emb_norm = l2_norm(embbedings)
        kernel_norm = l2_norm(self.weight)
        cosine = F.linear(emb_norm, kernel_norm)
        if labels is None:
            return cosine

        m_hot = torch.zeros(labels.size()[0], cosine.size()[1], device=cosine.device)
        m_hot.scatter_(1, labels.reshape(-1, 1), self.m)

        cosine = cosine.clamp(-1 + self.eps, 1 - self.eps)  # for stability
        theta = cosine.acos()
        theta_m = torch.clip(theta + m_hot, min=self.eps, max=math.pi - self.eps)
        cosine_m = theta_m.cos()
        scaled_cosine_m = cosine_m * self.s
        return scaled_cosine_m


"""
1. Clarification
2. Possible solutions
    - Cheating
    - Natural
3. Coding
4. Tests
"""

# # T=O(1), S=O(1)
# class Solution:
#     def divide(self, dividend: int, divisor: int) -> int:
#         x = int(dividend / divisor)
#         return x if -2**31 <= x <= 2**31 - 1 else 2**31-1

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        def div(a, b):
            if a < b: return 0
            count, tmp = 1, b
            while 2 * tmp <= a:
                count *= 2
                tmp *= 2
            return count + div(a - tmp, b)

        intMin, intMax = -2**31, 2**31-1
        if dividend == 0: return 0
        if divisor == 1: return dividend
        if divisor == -1:
            if dividend > intMin: return -dividend
            return intMax
        a, b, sign = dividend, divisor, 1
        if (a > 0 and b < 0) or (a < 0 and b > 0):
            sign = -1
        a, b = abs(a), abs(b)
        res = div(a, b)
        if sign > 0: return intMax if res > intMax else res
        return -res


"""
7의 개수
"""
def solution(array):
    answer = 0
    for i in array:
        while (i % 10) != 0:
            if (i % 10) == 7:
                answer += 1
            i = int(i / 10)
    return answer

print(solution([7, 77, 17]))

"""
잘라서 배열로 저장하기
"""
def solution(my_str, n):
    answer = []
    size = []
    my_str = list(my_str)
    i = len(my_str)
    while i > 0:
        if i >= n:
            size.append(n)
        else:
            size.append(i)
        i -= n

    for i in size:
        word = ''
        for j in range(size.pop(0)):
            word += my_str.pop(0)

    return answer

"""
중복된 숫자 개수
"""
def solution(array, n):
    return array.count(n)

"""
머쓱이보다 키 큰 사람
"""
def solution(array, height):
    idx = len(array)
    array.sort()
    for i in range(len(array)):
        if array[i] > height:
            idx = i
            break;
    return len(array) - idx


'''Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios.
Guarde esses resultados em um dicionário. No final coloque em ordem sabendo que o vencedor tirou o maior número no dado'''

from random import randint
from time import sleep
from operator import itemgetter

jogadores = dict()
ranking = list()
rank = dict()

print("Valores sorteados: ")
sleep(1)
for i in range(1,5):
    dado = randint(1, 6)
    jogadores['Jogador'] = i
    jogadores['Dado'] = dado
    ranking.append(jogadores.copy())
    sleep(1)
    print(f"O jogador {jogadores['Jogador']} tirou {jogadores['Dado']}.")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 30 21:33:52 2019

@author: dobvinci
"""

import gpxpy
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

sns.set()
gpx_file = open('route_cost.gpx', 'r')
gpx = gpxpy.parse(gpx_file)
print("Tracks {}".format(len(gpx.tracks)))
print("Segments {}".format(len(gpx.tracks[0].segments)))
print("Points {}".format(len(gpx.tracks[0].segments[0].points)))
data = gpx.tracks[0].segments[0].points
## Start Position
start = data[0]
print("Starting Point {}".format(start))
## End Position
finish = data[-1]

print("End Point {}".format(finish))
print("Duration {}".format(gpx.get_duration()))

distance=gpx.length_2d()/1000
print("2D Distance {} KM".format(distance))
df = pd.DataFrame(columns=['lon', 'lat'])
#print("3D Distance {} KM".format(gpx.length_3d()/1000))
df = pd.DataFrame(columns=['lon', 'lat'])
for point in data:
    df = df.append({'lon': point.longitude, 'lat' : point.latitude}, ignore_index=True)

data_path = 'lpq'
fig = plt.figure(facecolor = '0.05')
ax = plt.Axes(fig, [0., 0., 1., 1.], )
ax.set_aspect('equal')
ax.set_axis_off()
fig.add_axes(ax)
#fig.add_axes(ax)
sns.set_style("dark")
sns.despine(left=True,right=True)
x=[36.786102,39.63615315,40.04830556,41.85686111]
y=[-1.259201,-0.45880086,1.751611111,3.932805556]

plt.scatter(x,y, s = 100)
#plt.plot(df['lon'],df['lat'], color = 'deepskyblue', lw = 0.2, alpha = 0.8)
plt.plot(df['lon'],df['lat'], color = 'deepskyblue')
plt.ylabel("longitude")
plt.xlabel("Latitude")

plt.title("Route plan from Safaricom HQ Distance {} KM".format(distance))

filename = data_path + '.png'
plt.savefig(filename, facecolor = fig.get_facecolor(), bbox_inches='tight', pad_inches=0, dpi=300)


# A complete working Python program to demonstrate all
# Queue operations using doubly linked list

# Node class
class Node:

    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
        self.prev = None  # Initialize prev as null

# Queue class contains a Node object
class Queue:

    # Function to initialize head
    def __init__(self):
        self.head = None
        self.last = None

    # Function to add an element data in the Queue
    def enqueue(self, data):
        if self.last is None:
            self.head = Node(data)
            self.last = self.head
        else:
            self.last.next = Node(data)
            self.last.next.prev = self.last
            self.last = self.last.next

    # Function to remove first element and return the element from the queue
    def dequeue(self):

        if self.head is None:
            return None
        else:
            temp = self.head.data
            self.head = self.head.next
            #self.head.next = None
            return temp

        # Function to return top element in the queue

    def first(self):

        return self.head.data

    # Function to return the size of the queue
    def size(self):

        temp = self.head
        count = 0
        while temp is not None:
            count = count + 1
            temp = temp.next
        return count

    # Function to check if the queue is empty or not
    def isEmpty(self):
        if self.head is None:
            print(" head is none")
            return True
        else:
            #print("head is not none")
            return False

    # Function to print the stack
    def printqueue(self):

        print("queue elements are:")
        temp = self.head
        if temp is None:
            print("Queue is empty")
            return None
        else:
            while temp is not None:
                print(temp.data, end="->")
                temp = temp.next

# Code execution starts here
if __name__ == '__main__':

    # Start with the empty queue
    queue = Queue()
    queue.enqueue(6)
    queue.enqueue(12)
    queue.printqueue()
    print("\n The first element is : ", queue.first())
    print("The size of the queue is : ", queue.size())
    queue.enqueue(18)
    queue.enqueue(24)
    queue.printqueue()
    queue.dequeue()
    print("Queue follows First in First out policy")
    queue.printqueue()
    queue.dequeue()
    queue.dequeue()
    print("\n Only one element is left in the queue")
    queue.printqueue()
    #queue.dequeue()

    queue.printqueue()

    #Check if Queue is empty
    #True: if queue is empty
    #False: if queue is not empty
    print("\n Check if queue is empty: ", queue.isEmpty())
    queue.dequeue()
    print("\n Check if queue is empty: ", queue.isEmpty())


import cv2 as cv
import sys

filename=sys.argv[1] # we pass filename as command-line-argument here i.e. python3 car.py vehicle.jpg
car_cascade = cv.CascadeClassifier('cars.xml')
img=cv.imread(filename)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # convert image to gray scale
cars = car_cascade.detectMultiScale(gray, 1.1, 1) # apply haar-cascade
for (x,y,w,h) in cars:                            ## for each car found in the image
  cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)  ## draw a rectangle (in RED COLOR of WIDTH 2) around the car
cv.imwrite("detected_car.jpg",img)


from string import Template
from pathlib import Path
from typing import Tuple
import logging
import pendulum as pdl
from pendulum.exceptions import ParserError
from freebilly.repository.AbstractWorkLogUnitOfWork import AbstractWorkLogUnitOfWork
from freebilly.repository.AbstractBillUnitOfWork import AbstractBillUnitOfWork
from freebilly.repository.CsvWorkLogRepository import (
    CsvWorkLogRepository,
)  # TODO coupling
from freebilly.services.AbstractServiceLayer import AbstractServiceLayer
from freebilly.domain.AbstractWorkLog import AbstractWorkLog
from freebilly.domain.AbstractWorkSession import AbstractWorkSession
from freebilly.domain.OrderedSetWorkLog import OrderedSetWorkLog  # TODO coupling
from freebilly.domain.PendulumWorkSession import PendulumWorkSession  # TODO coupling

logger = logging.getLogger(__name__)

class ConcreteServiceLayer(AbstractServiceLayer):
    @staticmethod
    def start_session(
        uow: AbstractWorkLogUnitOfWork, client: str, project: str
    ) -> Tuple[
        AbstractWorkLog, AbstractWorkSession
    ]:  # TODO I am saying that but... implementation uses concrete classes...

        logger.info(f"starting session for client {client} and project {project}...")

        work_session = PendulumWorkSession()
        with uow:
            if uow.work_logs.exists(client, project):
                work_log = uow.work_logs.get(client, project)
            else:
                work_log = OrderedSetWorkLog(client, project)

        logger.info(f"session started")

        return work_log, work_session

    @staticmethod
    def end_session(
        uow: AbstractWorkLogUnitOfWork,
        work_log: AbstractWorkLog,
        work_session: AbstractWorkSession,
    ):

        logger.info(f"ending and committing session...")

        with uow:
            work_session.end_session()
            work_log.add_session(work_session)
            uow.commit(work_log)

        logger.info(f"session ended and committed")

    @staticmethod
    def add_session(
        uow: AbstractWorkLogUnitOfWork,
        client: str,
        project: str,
        start_time: str,
        end_time: str,
    ):  # TODO I am saying that but... implementation uses concrete classes...

        logger.info(
            f"pushing supplied session for client {client} and project {project}..."
        )

        try:
            start_time, end_time = pdl.parse(start_time), pdl.parse(end_time)
        except ParserError:
            logger.error(
                "could not parse the start or end time. Is it a valid ISO 8601 format?"
            )
            raise

        work_session = PendulumWorkSession(start_time=start_time, end_time=end_time)

        with uow:
            if uow.work_logs.exists(client, project):
                work_log = uow.work_logs.get(client, project)
            else:
                work_log = OrderedSetWorkLog(client, project)
            work_log.add_session(work_session)
            uow.commit(work_log)

        logger.info(f"session committed")

    @staticmethod
    def produce_bill(
        uow: AbstractBillUnitOfWork,
        template_path: Path,
        work_log_path: Path,
        extra_info: dict,
        client: str,
        project: str,
        start_time: pdl.DateTime,
        end_time: pdl.DateTime,
        hourly_rate: float,
    ) -> None:

        logging.info(
            f"starting bill production for client {client} and project {project}"
        )

        repo = CsvWorkLogRepository(path=work_log_path)
        if not repo.exists(client, project):
            raise ValueError(
                f"could not find any work log data for client {client} and project {project}..."
            )
        work_log = repo.get(client, project)
        quantity = work_log.total_time(start_time, end_time)
        total = round(
            quantity * hourly_rate, 2
        )  # TODO this is business logic leaking into services. This might mean you actually need a Bill domain object, that's a work log and a rate.
        known_keywords = {
            "hourly_rate": hourly_rate,
            "quantity": quantity,
            "total": total,
        }
        if not all(
            [x not in extra_info.keys() for x in ["hourly_rate", "quantity", "total"]]
        ):
            raise ValueError(
                "'hourly_rate', 'quantity', 'total' are special keywords for which data is to be inferred by the program. They "
                "should not appear as keys in the bill info dictionary."
            )
        all_info = extra_info | known_keywords
        with open(str(template_path)) as template_file:
            template_bill = Template(template_file.read())
            filled_bill = template_bill.substitute(all_info)
        # finally, commit to the data.
        with uow:
            uow.commit(filled_bill)

        logging.info("bill produced")


from django.shortcuts import render, HttpResponse, redirect, get_object_or_404
from django.contrib.auth.models import User, Group
from django.contrib import messages
from .tokens import account_activation_token
from .models import Profile
from django.http import JsonResponse, HttpResponseForbidden
from workshop.models import Workshop, Contributor
from django.views.decorators.csrf import csrf_protect
from django.views.generic.detail import DetailView
from django.views.generic import View
from django.template.loader import get_template

class Detail(DetailView):
    model = Profile
    template_name = 'learner/profile.html'

    def get_user_object(self):
        try:
            return self.user_obj
        except:
            self.user_obj = get_object_or_404(User, username=self.kwargs.get('username'))
            return self.user_obj

    def get_contributor_object(self):
        try:
            return self.contributor_obj
        except:
            try:
                self.contributor_obj = Contributor.objects.get(profile=self.get_user_object().profile)
                return self.contributor_obj
            except:
                return None

    def get_object(self):
        user_obj = self.get_user_object()
        return user_obj.profile

    def is_me(self):
        user_obj = self.get_user_object()
        return user_obj == self.request.user

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['is_me'] = self.is_me()
        if context['is_me']:
            context['user'] = self.request.user
        else:
            context['user'] = self.get_user_object()

        context['contributor'] = self.get_contributor_object()
        context['is_instructor'] = Group.objects.get(name='Instructor') in self.request.user.groups.all()

        return context

from .forms import LearnerRegisterForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_encode
from django.core.mail import EmailMultiAlternatives
from django.utils.encoding import force_bytes

class Register(View):

    form = LearnerRegisterForm()

    def get(self, request):
        if request.user.is_authenticated:
            return redirect('website:index')
        return render(request, 'learner/register.html', {'form': self.form})

    def post(self, request):
        self.form = LearnerRegisterForm(request.POST)

        if self.form.is_valid():
            user = self.form.save(commit=False)
            user.is_active = False
            user.save()
            username = self.form.cleaned_data.get('username')
            messages.info(request, f'Account created for {username}. You have to click the confirmation link in the email in order to activate your account.')

            context = {
                'user': user,
                'domain': get_current_site(request).domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            }
            text_message = get_template('learner/fragments/email/new_acc_email.txt').render(context)
            html_message = get_template('learner/fragments/email/new_acc_email.html').render(context)
            to_email = self.form.cleaned_data.get('email')
            email = EmailMultiAlternatives('Activate your account', text_message, 'Digital Humanities Research Institute <info@dhinstitutes.org>', [to_email])
            email.attach_alternative(html_message, "text/html")
            email.send()

            return redirect('login')
        else:
            return self.get(request=request)

def activate(request, uidb64='', token=''):
    from django.utils.http import urlsafe_base64_decode
    from django.contrib.auth import login
    from django.utils.encoding import force_text

    uid = force_text(urlsafe_base64_decode(uidb64))
    try:
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        messages.success(request, f'Thank you for your email confirmation, {user.username}. You have been logged in automatically.')
        return redirect('website:index')
    else:
        return HttpResponse('Activation link is invalid!')

@csrf_protect
def favorite(request):
    if not request.user.is_authenticated:
        return JsonResponse({'error': 'user is not authenticated'})

    workshop = request.headers.get('workshop')
    obj = get_object_or_404(Workshop, slug=workshop)

    removed, added = False, False
    if obj in request.user.profile.favorites.all():
        request.user.profile.favorites.remove(obj)
        #print(obj, "removed as favorite")
        removed = True
    else:
        request.user.profile.favorites.add(obj)
        #print(obj, "added as favorite")
        added = True

    output_data = {'workshop': obj.name, 'success': True, 'added': added, 'removed': removed}

    return JsonResponse(output_data)

@csrf_protect
def instructor_request(request):
    if not request.user.is_authenticated:
        return HttpResponseForbidden('You do not have access to this page. If you think you should have access to it, please contact the site administrator.')

    request.user.profile.instructor_requested = True
    request.user.profile.save()

    output_data = {'success': True}

    return JsonResponse(output_data)

def get_pending_requests():
    instructor = Group.objects.get(name='Instructor')
    pending_requests = list()
    all_pending_requests = Profile.objects.filter(instructor_requested=True)
    for profile in all_pending_requests:
        if not instructor in profile.user.groups.all():
            pending_requests.append(profile)
        else:
            profile.instructor_requested = False
            profile.save()
    return pending_requests

from django.views.generic import View

class InstructorRequests(View):

    def post(self, request, *args, **kwargs):
        instructor = Group.objects.get(name='Instructor')
        user = get_object_or_404(User, username=request.user.username)

        user.groups.add(instructor)
        user.profile.instructor_requested = False
        user.profile.save()

        output_data = {'success': True}
        return JsonResponse(output_data)

    def get(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            return HttpResponseForbidden()

        pending_requests = get_pending_requests()

        return render(request, 'learner/requests.html', {'pending_requests': pending_requests})


import config as con
import time
import pandas
from selenium import webdriver
from bs4 import BeautifulSoup

def gymDataColl():
    # selenium gets html code
    elem = driver.find_element_by_xpath("//*")
    source_code = elem.get_attribute('innerHTML')

    # bs4 gets the html data for processing
    soup = BeautifulSoup(source_code, "html.parser")

    # create list for gyms
    onlyDivs = soup.find_all('div','lead mb-3')

    # create list for occupants
    onlyOccupancy = soup.find_all('span', 'occupancy')

    # create list for queue
    onlyQueue = soup.find_all('span', 'queue_length')

    finalList = []
    timeStr = time.ctime()

    df = pandas.DataFrame(data={"Gym": [i.string for i in onlyDivs], "Occupancy": [i.string for i in onlyOccupancy], "Queue Length": [i.string for i in onlyQueue], "Time": [timeStr for _ in range(len(onlyDivs))]})
    # filename = getFileName()
    df.to_csv("./gymdata.csv", mode = 'a', header = False)
    return

url = 'https://smartentry.org/status/gymmboxx'

driver = webdriver.Chrome(con.directory)

driver.get(url)
# delay so dynamic elements can load
time.sleep(5)

# test collection of data
df = pandas.DataFrame(data={"Gym":[], "Occupancy":[], "Queue Length":[], "Time":[]})
df.to_csv("./gymdata.csv", mode = 'w', header = True)

i = 1;
while(i<=20):
    print('script running')
    gymDataColl()
    print( str(i) + "pulling again")
    i += 1
    time.sleep(600)

# with open('gymdata.csv','a') as f:
#     df.to_csv(f, header = False)


import time
import Story
import Enemy

class Game:
	def __init__(self): # things that happen when you're starting the game
		self.game_name = "Teymur\'s Blessing"
		print(Story.INTRO)
		# testing encounterEnemy

	def losegame(self, Timur): # losing the game
		print("You lost the game")
		print("You lost the game at: " + Timur.level)
		print("Your final stats:")
		for key, value in Timur.stats.items(): # get me everything inside Timur's stats
			print("{}: {}".format(key, value)) # [Strength] = its value (10 or whatever)

	def encounterEnemy(self, level, health, name):
		print("You have encountered a {}!".format(name))
		print("Level: {}\nHealth: {}\n".format(level,health))
		return Enemy.Enemy(level, health, name)
		# create a new Enemy with given level, health and name. Returns it to set to a variable

	def listenForAttack(Timur, target): # target must be passed as obj
		while target.status != "Dead":
			while True: # this lets us keep asking for an attack until we get a valid input
				# print out every move that Timur has
				attack_map = {}

				for move, value in Timur.moves.items():
					#  attack_map[i] = move
					# enumerate allows us to assign numbers to moves
					# this lets us just type the number of the attack without
					# having to type out the whole name every time
					print("{}\nDamage: {}\n".format(move.title(), value['Damage']))
					# i (Autism)
					# Damage: i['Damage'] (10)
				selection = input("Select an attack:\n")
				if selection not in Timur.moves:
					print("That's not a valid move.")
					continue # go back to the beginning of the loop

				Timur.executeAttack(Timur.moves[selection.lower()], target)
				# attacks are stored in lowercase to in case someone enters
				# 'aUtiSm' we still want it to work
				break # break out of the loop

	def playersTurn(self):
		pass


from rest_framework import views, response, status, viewsets
from .serializers import CustomerSerializer
from .models import Customer

class CustomerListCreateAPIView(views.APIView):
    serializer_class = CustomerSerializer

    def get(self, request):
        queryset = Customer.objects.all()
        serializer = self.serializer_class(queryset, many=True)
        return response.Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return response.Response(serializer.data, status=status.HTTP_201_CREATED)

class CustomerDetailView(views.APIView):
    serializer_class = CustomerSerializer

    def get(self, request, pk):
        instance = Customer.objects.get(pk=pk)
        serializer = self.serializer_class(instance=instance)
        return response.Response(serializer.data)

    def patch(self, request, pk):
        instance = Customer.objects.get(pk=pk)
        serializer = self.serializer_class(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return response.Response(serializer.data)

    def delete(self, request, pk):
        try:
            instance = Customer.objects.get(pk=pk)
            instance.delete()
            return response.Response(status=status.HTTP_204_NO_CONTENT)
        except Customer.DoesNotExist:
            return response.Response({'message': 'customer not found'})


import base64
import json
import re
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes, parser_classes, action
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token
from event.models import DragEvent, City, Bookmark
from user.models import FollowManager, User,DragProfile
from event.api.serializers import CreateDragEventSerializer, SerializeAllEvents, EventHostSerializer, CitySerializer
from random import choice
from string import ascii_letters
import itertools
from django.conf import settings
from rest_framework import viewsets
from django.utils.translation import gettext_lazy as _
from rest_framework import parsers
from .pagination import CustomPagination, ProfilePagination
from datetime import datetime
from rest_framework.authtoken.models import Token

class DragEventViewSet(viewsets.ModelViewSet):
    queryset = DragEvent.objects.all()
    pagination_class = ProfilePagination
    serializer_class = CreateDragEventSerializer
    parser_classes = (parsers.MultiPartParser, parsers.FormParser,parsers.JSONParser)
    # permission_classes = [
    #     permissions.IsAuthenticatedOrReadOnly]

    @action(detail=False,  methods=["POST"], permission_classes=[IsAuthenticated])
    def handle_events(self, serializer):
        if self.request.method == "POST":
            info = json.loads(self.request.data.get('data'))
            ser = CreateDragEventSerializer(data=self.request.data)
            if ser.is_valid():
                profile = ser.save(self.request.user, info)
                return Response({'status':'success'})

    @action(detail=False,  methods=["GET"])
    def all_cities(self, pk=None):
        cities = City.objects.all()
        serialized_cities = CitySerializer(cities, many =True, context={'request': self.request})

        result = json.loads(json.dumps(serialized_cities.data))
        data = dict(
            result = self.paginate_queryset(result),
            status = True,
        )

        return Response(data)

    @action(detail=False,  methods=["GET"], permission_classes=[IsAuthenticated])
    def all_event_host(self, pk=None):
        performers = DragProfile.objects.filter(approved = True).values_list('owner', flat=True)
        performers = User.objects.filter(pk__in  = performers).exclude(pk = self.request.user.pk )

        d_serializer = EventHostSerializer(performers, many=True)
        general_hosts= json.loads(json.dumps(d_serializer.data))

        # general = ,

        data = dict(
            result = self.paginate_queryset(general_hosts),
            status = "success",
        )
        print("HOSTS : ",general_hosts)
        return Response(data)

    @action(detail=False,  methods=["GET", "PUT"], permission_classes=[IsAuthenticated])
    def edit_event(self, pk=None):
        if self.request.method == "GET":
            event_pk = self.request.GET.get('q', None)
            all_cities = City.objects.all()
            city_serializer = CitySerializer(all_cities, many=True, context={'request': self.request})
            cities = json.loads(json.dumps(city_serializer.data))
            if int(event_pk) > 0:
                event= DragEvent.objects.get(pk = event_pk)
                event_hosts_pk = json.loads(event.hosts)
                event_hosts = User.objects.filter(pk__in = event_hosts_pk).exclude(pk = self.request.user.pk )
                d_serializer = EventHostSerializer(event_hosts, many=True)
                result= json.loads(json.dumps(d_serializer.data))
                event_serializer = SerializeAllEvents(event)
                event_obj = json.loads(json.dumps(event_serializer.data))

                data = dict(
                    hosts = result,
                    status = "success",
                    cities = cities,
                    event = event_obj
                )
                return Response(data)

            else:

                data = dict(
                    hosts = [],
                    status = "success",
                    cities = cities,
                )

                return Response(data)
        else:
            event_pk = self.request.data.get('id')
            print("EV : ", event_pk)
            info = json.loads(self.request.data.get('data'))
            ser = CreateDragEventSerializer(data=self.request.data)
            if ser.is_valid():
                profile = ser.update(event_pk, info)
                return Response({'status':'success'})

    @action(detail=False,  methods=["DELETE"],permission_classes=[IsAuthenticated])
    def event_delete(self, serializer):
        event_id = self.request.GET.get('q', None)
        # event_id = None
        if event_id:
            event = DragEvent.objects.get(pk=event_id)
            if event.performer.pk == self.request.user.pk:
                event.delete()

                data= dict(
                    status=True,
                )

                return Response(data)

        data= dict(status=False)

        return Response(data)

    @action(detail=False,  methods=["GET"])
    def event_detail(self, serializer):
        pk =  self.request.GET.get('q', None)
        token = self.request.GET.get('t', None)
        if pk:
            try:
                event = DragEvent.objects.get(pk=pk)
                event_hosts = json.loads(event.hosts)
                host_users = User.objects.filter(id__in = event_hosts)

                creator = event.performer

                event_serialized = SerializeAllEvents(event)
                host_serializer = EventHostSerializer(host_users, many=True)
                creator_serializer = EventHostSerializer(creator)

                hosts = json.loads(json.dumps(host_serializer.data))
                performer = json.loads(json.dumps(creator_serializer.data))
                event_detail = json.loads(json.dumps(event_serialized.data))

                print("TOKEN : ", token)
                if token != 'null':
                    online = True
                else:
                    online = False
                if Token.objects.filter(user=creator).exists():
                    print("T")
                    if Token.objects.get(user=creator).key == token:
                        owner = True

                    else:
                        owner = False
                else:
                    owner = False

                print(online)

                data = dict(
                    status = True,
                    creator_info=performer,
                    hosts_list = hosts,
                    owner = owner,
                    size = len(hosts),
                    event = event_detail,
                    online = online
                )
                print("DaTA : ", data)
                return Response(data)
            except Exception as e :
                print(e)
        data =dict(
            status = False
        )
        print("DaTA : ", data)
        return Response(data)

class ListEventViewSet(viewsets.ModelViewSet):
    pagination_class = CustomPagination
    serializer_class = SerializeAllEvents
    parser_classes = (parsers.MultiPartParser, parsers.FormParser,parsers.JSONParser)
    # permission_classes = [
    #     permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        return DragEvent.objects.all().order_by('-date_uploaded')
        # return event_query

    @action(detail=False,  methods=["GET"], permission_classes=[IsAuthenticated])
    def bookmark_status(self, serializer):
        event_id = self.request.GET.get('g', None)
        book_list_events = list(Bookmark.objects.filter(owner= self.request.user).values_list('bookmarked_events', flat=True))
        print(book_list_events, event_id)
        if event_id:
            if int(event_id) in book_list_events:
                marked = True
            else:
                marked = False

            data = {
                "status" : True,
                "marked" : marked
            }

            return Response(data)

        else:
            # return all events in bookmark list
            bookmarked_events = DragEvent.objects.filter(pk__in = book_list_events)
            event_serializer = SerializeAllEvents(bookmarked_events, many=True)
            event_result = json.loads(json.dumps(event_serializer.data))

            data= {
                "status" : True,
                "result" : self.paginate_queryset(event_result),
            }

            return Response(data)

    @action(detail=False,  methods=["POST"], permission_classes=[IsAuthenticated])
    def handle_bookmark(self, serializer):
        body = self.request.data
        event_id = body['id']
        user = self.request.user
        value = body['val']
        user_bookmark = Bookmark.objects.get(owner = user)
        event = DragEvent.objects.get(pk = event_id)
        if value:
            user_bookmark.bookmarked_events.add(event)
            data = {
                "status" : True,
                "marked" : True
            }
        else:
            user_bookmark.bookmarked_events.remove(event)
            data = {
                "status" : True,
                "marked" : False,
            }
        user_bookmark.save()

        return Response(data)

    @action(detail=False,  methods=["GET"])
    def every_event(self, serializer):
        query= self.get_queryset()
        curr = self.request.GET.get('g', None)
        upcoming_query = query.filter(raw_date__gte=curr)
        upcoming_serializer = self.serializer_class(upcoming_query,many=True)
        upcoming_result= json.loads(json.dumps(upcoming_serializer.data))

        data= {
                "status" : True,
                "result" : self.paginate_queryset(upcoming_result),
            }

        return Response(data)

    def filter_follow_events(self, request_user_pk, filterer):

        request_user = User.objects.get(id = request_user_pk)

        request_user_followed = FollowManager.objects.get(owner=request_user).following.all()
        drag_events = DragEvent.objects.filter(performer__in = request_user_followed)

        return drag_events

    @action(detail=False,  methods=["GET"])
    def history_profile(self, serializer):
        query = self.get_queryset().order_by('raw_date')
        owner = self.request.GET.get('q', None)
        curr = self.request.GET.get('g', None)
        filterer = self.request.GET.get('f', None)
        if owner:
            try:
                user = User.objects.get(email=owner)
                if filterer=='followed_events':
                    query = self.filter_follow_events(user.pk, filterer)
                elif filterer == 'bookmark':
                    query = self.filter_bookmark(user, filterer)
                elif 'city' in filterer.split('-'):
                    query = self.filter_by_city(filterer.split('-')[-1])
                else:
                    query = query.filter(performer=user)
                if DragProfile.objects.filter(owner=user).exists() and DragProfile.objects.get(owner=user).approved:
                    history_query = query.filter(raw_date__lt=curr)
                    history_serializer = self.serializer_class(history_query,many=True)
                    history_result= json.loads(json.dumps(history_serializer.data))
                    data= {
                        "status" : True,
                        "result" : self.paginate_queryset(history_result),

                    }
                else:
                    if filterer and 'city' in filterer.split('-'):
                        query = self.filter_by_city(filterer.split('-')[-1])
                    history_query = query.filter(raw_date__lt=curr).order_by('-raw_date')
                    history_serializer = self.serializer_class(history_query,many=True)
                    history_result= json.loads(json.dumps(history_serializer.data))
                    data= {
                        "status" : True,
                        "result" : self.paginate_queryset(history_result)
                    }

            except Exception as e:
                print(e)

                data = dict(
                    status = False,
                )
            return Response(data)

        else:
            if filterer and 'city' in filterer.split('-'):
                query = self.filter_by_city(filterer.split('-')[-1])
            history_query = query.filter(raw_date__lt=curr).order_by('-raw_date')
            history_serializer = self.serializer_class(history_query,many=True)
            history_result= json.loads(json.dumps(history_serializer.data))
            data= {
                "status" : True,
                "result" : self.paginate_queryset(history_result)
            }

            return Response(data)

    def filter_bookmark(self,d_user, filterer):
        user_bookmark = Bookmark.objects.get(owner=d_user)
        drag_events = user_bookmark.bookmarked_events.all()

        return drag_events

    def filter_by_city(self, city_name):
        drag_events = DragEvent.objects.filter(city = city_name)

        return drag_events

    @action(detail=False,  methods=["GET"])
    def profile_event(self, serializer):
        query = self.get_queryset()
        owner = self.request.GET.get('q', None)
        curr = self.request.GET.get('g', None)
        filterer = self.request.GET.get('f', None)

        if owner:
            try:
                user = User.objects.get(email=owner)
                if filterer=='followed_events':
                    query = self.filter_follow_events(user.pk, filterer)
                elif filterer == 'bookmark':
                    query = self.filter_bookmark(user, filterer)
                elif filterer and 'city' in filterer.split('-'):
                    query = self.filter_by_city(filterer.split('-')[-1])
                else:
                    query = query.filter(performer=user)
                if DragProfile.objects.filter(owner=user).exists() and DragProfile.objects.get(owner=user).approved:
                    upcoming_query = query.filter(raw_date__gte=curr).order_by('raw_date')
                    upcoming_serializer = self.serializer_class(upcoming_query,many=True)
                    upcoming_result= json.loads(json.dumps(upcoming_serializer.data))
                    data= {
                        "status" : True,
                        "result" : self.paginate_queryset(upcoming_result),

                    }
                else:
                    if filterer and 'city' in filterer.split('-'):
                        query = self.filter_by_city(filterer.split('-')[-1])
                    upcoming_query = query.filter(raw_date__gte=curr).order_by('raw_date')
                    upcoming_serializer = self.serializer_class(upcoming_query,many=True)
                    upcoming_result= json.loads(json.dumps(upcoming_serializer.data))
                    data= {
                        "status" : True,
                        "result" : self.paginate_queryset(upcoming_result)
                    }

                print(data)

            except Exception as e:
                print(e)

                data = dict(
                    status = False,
                )
            return Response(data)

        else:
            if filterer and 'city' in filterer.split('-'):
                query = self.filter_by_city(filterer.split('-')[-1])
            upcoming_query = query.filter(raw_date__gte=curr)
            upcoming_serializer = self.serializer_class(upcoming_query,many=True)
            upcoming_result= json.loads(json.dumps(upcoming_serializer.data))
            data= {
                "status" : True,
                "result" : self.paginate_queryset(upcoming_result)
            }

            return Response(data)


# Build a star pyramid tower

def tower_builder(n_floors):
    tower = []
    stars = []
    count = 1
    while n_floors > 0:
        stars.append('*' * count)
        count += 2
        n_floors -= 1
    for i in stars:
        tower.append(i.center(len(stars[-1])))
    return tower

test1 = print(tower_builder(5))


from threading import Thread
import base64
import flask
import redis
import uuid
import time
import json
import sys
import io
import algorithm
import numpy

IMAGE_QUEUE  = "image_queue"
BATCH_SIZE   = 32
DTYPE        = numpy.float32
SERVER_SLEEP = 0.25
CLIENT_SLEEP = 0.25

# initialize our Flask application, Redis server, and Keras model
app = flask.Flask(__name__)
db = redis.StrictRedis(host="localhost", port=6379, db=0)

def base64_encode_image(a):
  # base64 encode the input NumPy array
  return base64.b64encode(a).decode("utf-8")

def base64_decode_image(a, dtype, shape):
  # if this is Python 3, we need the extra step of encoding the
  # serialized NumPy string as a byte object
  if sys.version_info.major == 3:
    a = bytes(a, encoding="utf-8")

  # convert the string to a NumPy array using the supplied data
  # type and target shape
  a = np.frombuffer(base64.decodestring(a), dtype=dtype)
  a = a.reshape(shape)

  # return the decoded image
  return a

def pre_process_file(I):
  # if sys.version_info.major == 3:
  #   I = bytes(I, encoding="utf-8")
  # I = base64.decodestring(I)
  I = io.BytesIO(base64.b64decode(I))
  # print(type(I))
  # print(I[:10])
  return I

def classify_process():
  while True:
    # get BATCH_SIZE no of requests
    queue = db.lrange(IMAGE_QUEUE, 0, BATCH_SIZE - 1)
    n = 0
    for q in queue:
      q = json.loads(q.decode("utf-8"))
      q['input_file'] = pre_process_file(q['input_file'])
      item_id = q["id"]

      # compute result for one request
      result = algorithm.compute(q)
      # put result in queue
      db.set(item_id,json.dumps(result))
      n = n+1
    # delete the processed requests
    db.ltrim(IMAGE_QUEUE, n,-1)
    # sleep for some time before polling again
    time.sleep(SERVER_SLEEP)

@app.route("/predict", methods=["POST"])
def predict():
  # initialize the data dictionary that will be returned from the  view
  data = {"success": False}

  # ensure an image was properly uploaded to our endpoint
  if flask.request.method == "POST":
    if flask.request.files.get("input_file"):
      # print(flask.request.files["input_file"])
      input_file = flask.request.files["input_file"].read()

      #image = numpy.frombuffer(io.BytesIO(image).getbuffer())
      #image = numpy.zeros((3,3))
      #image = prepare_image(image, (IMAGE_WIDTH, IMAGE_HEIGHT))

      # ensure our NumPy array is C-contiguous as well,
      # otherwise we won't be able to serialize it
      #image = image.copy(order="C")

      # generate an ID for the classification then add the
      # classification ID + image to the queue

      # input_file = io.BytesIO(input_file)

      #input_file = numpy.frombuffer(input_file.getbuffer(),dtype="u8")
      #print(input_file.shape)
      input_file = base64.b64encode(input_file).decode("utf-8")

      k = str(uuid.uuid4())
      #d = {"id": k, "input_file": base64_encode_image(input_file)}
      d = {"id": k, "input_file": input_file}

      db.rpush(IMAGE_QUEUE, json.dumps(d))
      # keep looping until our model server returns the output
      # predictions
      while True:
        # attempt to grab the output predictions
        output = db.get(k)

        # check to see if our model has classified the input
        # image
        if output is not None:
          # add the output predictions to our data
          # dictionary so we can return it to the client
          output = output.decode("utf-8")
          data["output"] = json.loads(output)

          # delete the result from the database and break
          # from the polling loop
          db.delete(k)
          break

        # sleep for a small amount to give the model a chance
        # to classify the input image
        time.sleep(CLIENT_SLEEP)

      # indicate that the request was a success
      data["success"] = True

  # return the data dictionary as a JSON response
  return flask.jsonify(data)

# if this is the main thread of execution first load the model and
# then start the server
if __name__ == "__main__":
  # load the function used to classify input images in a *separate*
  # thread than the one used for main classification
  print("* Starting model service...")
  t = Thread(target=classify_process, args=())
  t.daemon = True
  t.start()

  # start the web server
  print("* Starting web service...")
  app.run()