'''
This module provides general access to the official Telegram Bot API by
implementing useful functions.
'''

import json
import requests
from . import data

def check_with_exception(response):
  if not response.ok:
    response = response.json()
    raise Exception('{} ({})'.format(
      response['description'],
      response['error_code']))
  return response

class SupportedMethod:
  SEND_MSG = 'sendMessage'
  EDIT_MSG_TEXT = 'editMessageText'
  ANSWER_CALLBACK_QUERY = 'answerCallbackQuery'
  GET_WEBHOOK_INFO = 'getWebhookInfo'
  SET_WEBHOOK = 'setWebhook'
  DELETE_WEBHOOK = 'deleteWebhook'

class Webhook:

  def __init__(self, token, check_response=lambda x: x):
    self._token = token
    self._check_response = check_response

  @property
  def token(self):
    return self._token

  def url_for(self, method):
    '''
    Helper method to access the Telegram Bot API.
    '''
    return "https://api.telegram.org/bot{}/{}".format(
      self._token,
      method)

  @property
  def info(self):
    '''
    Returns the webhook info provided by Telegram Bot API in json
    format (as python dict).
    '''
    url = self.url_for(SupportedMethod.GET_WEBHOOK_INFO)
    return self._check_response(requests.get(url).json())

  @property
  def url(self):
    '''
    Returns the webhook url (string).
    '''
    return self.info['result']['url']

  def set_url_adding_token(self, base_url, certificate = None):
    '''
    Sets the webhook of this bot so incoming updates will be
    forwarded to it.
    Adds the bot's token after the given 'url'.
    '''
    api_url = self.url_for(SupportedMethod.SET_WEBHOOK)
    content = {'url': f'{base_url}/{self.token}'}
    if certificate is not None:
      content['certificate'] = certificate
    return self._check_response(requests.get(api_url, data=content))

  def delete(self):
    api_url = self.url_for(SupportedMethod.DELETE_WEBHOOK)
    return self._check_response(requests.get(api_url))

class Bot():

  def __init__(self, token, check_response=lambda x:x):
    self._webhook = Webhook(token, check_response=check_response)
    self._check_response = check_response

  @property
  def webhook(self):
    return self._webhook

  @property
  def token(self):
    return self.webhook._token

  def send_msg(self, msg, to, inline_keyboard=None):
    '''
    Sends the given message 'msg' to the user 'to', where 'to' is
    the user's chat_id (int) or the username (string) of the target
    channel (in the format @channelusername)
    '''
    url = self.webhook.url_for(SupportedMethod.SEND_MSG)
    content = {
      'chat_id': to,
      'text': msg
    }
    if inline_keyboard is not None:
      keyboard_data = []
      for row in inline_keyboard:
        new_row = []
        for button in row:
          if isinstance(button, data.InlineKey):
            new_row.append({
              'text': button.text,
              'callback_data': button.callback_data
            })
          else:
            new_row.append(button)
        keyboard_data.append(new_row)
      content['reply_markup'] = json.dumps({
        'inline_keyboard': keyboard_data
      })
    return self._check_response(requests.post(url=url, data=content))

  def answer_callback_query(
    self,
    callback_query_id,
    text=None,
    is_alert_not_notification=False
  ):
    url = self.webhook.url_for(SupportedMethod.ANSWER_CALLBACK_QUERY)
    content = {
      'callback_query_id': callback_query_id,
      'show_alert': is_alert_not_notification
    }
    if text is not None:
      content['text'] = text
    return self._check_response(requests.post(url=url, data=content))

  def edit_msg_text(self, chat_id, msg_id, new_text, inline_keyboard=None):
    url = self.webhook.url_for(SupportedMethod.EDIT_MSG_TEXT)
    content = {
      'chat_id': chat_id,
      'message_id': msg_id,
      'text': new_text
    }
    if inline_keyboard is not None:
      content['reply_markup'] = json.dumps({
        'inline_keyboard': inline_keyboard
      })
    return self._check_response(requests.post(url=url, data=content))


from html.parser import HTMLParser
import urllib.parse
import functions
from Crawler.PageUrl import PageUrl

class UrlFinder(HTMLParser):
    def __init__(self, page_url, tag, attr):
        self.page_url = page_url
        urlres = urllib.parse.urlparse(page_url)
        self.base_url = urlres.netloc
        self.scheme = urlres.scheme
        self.values = set()
        self.tag = tag
        self.attr = attr
        HTMLParser.__init__(self)

    def handle_starttag(self, tag, attrs):
        """
        This function called by HTMLParser internally. We modify it to make our work

        :rtype: object
        """
        if tag == self.tag:
            for (attr, value) in attrs:
                if attr == self.attr:
                    fullUrl = urllib.parse.urljoin(self.scheme + "://" + self.base_url, value)
                    self.values.add(fullUrl)
                else:
                    continue

    def get_values(self) -> object:
        """
        List of image link as set
        :return: object
        """
        return self.values

    def __setattr__(self, name, value):
        """
        page url must be a valid domain.
        :param name:
        :param value:
        :return:
        """
        if name == 'page_url':
            result = urllib.parse.urlparse(value);

            if len(result.scheme) > 0 and len(result.netloc) > 0:
                self.__dict__[name] = value
            else:
                raise Exception('Invalid url')

        else:
            self.__dict__[name] = value

    def error(self, message):
        pass

    def html_string(self) -> object:
        """
        Fetch html from url and return as Html String
        :param page_url:
        :rtype: object
        """
        html_string = ''
        try:
            request = urllib.request.Request(self.page_url, headers={
                "User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"})
            response = urllib.request.urlopen(request)
            if 'text/html' in response.getheader('Content-Type'):
                html_bytes = response.read()
                html_string = html_bytes.decode("utf-8")

        except Exception as e:
            return None
        return html_string


import argparse
import re
from pathlib import Path

node_pattern = re.compile(r"{(?P<SegmentIndex>\d+)_(?P<NodeIndex>\d+)} (?P<Distance>\d+\.\d+(?:E-?\d+)?)")

def main(arguments):
    max_diff = 0.0
    total_diff = 0.0
    compared_values = 0
    with arguments.a.open("r") as a, arguments.b.open("r") as b, arguments.out.open("w+") as out_file:
        for line_a in a:
            line_a = line_a.replace("\n", "")
            line_b = b.readline().replace("\n", "")

            if len(line_a) < 1 and len(line_b) < 1:
                continue
            elif len(line_a) < 1:
                print("missing line in a!")
                continue
            elif len(line_b) < 1:
                print("missing line in b!")
                continue

            match_a = node_pattern.fullmatch(line_a)

            if match_a is None:
                print(f"ill formatted line in a: {line_a}")
                continue

            match_b = node_pattern.fullmatch(line_b)

            if match_b is None:
                print(f"ill formatted line in b: {line_b}")
                continue

            segment_a = int(match_a.group("SegmentIndex"))
            node_a = int(match_a.group("NodeIndex"))
            distance_a = float(match_a.group("Distance"))

            segment_b = int(match_b.group("SegmentIndex"))
            node_b = int(match_b.group("NodeIndex"))
            distance_b = float(match_b.group("Distance"))

            if segment_a != segment_b or node_a != node_b:
                print(f"node mismatch! ({line_a} vs. {line_b})")
                continue

            diff = abs(distance_a - distance_b)
            total_diff += diff
            compared_values += 1
            if diff > max_diff:
                max_diff = diff
            print(diff, file=out_file)

    print(f"max_diff = {max_diff}")
    print(f"avg_diff = {total_diff / compared_values}")

if __name__ == "__main__":
    argument_parser = argparse.ArgumentParser()

    argument_parser.add_argument(
        "-a",
        type=Path,
        required=True
    )
    argument_parser.add_argument(
        "-b",
        type=Path,
        required=True
    )
    argument_parser.add_argument(
        "--out",
        type=Path,
        required=True
    )

    args = argument_parser.parse_args()
    main(args)


# -*- coding: utf-8 -*-
# @Author: JimZhang
# @Date:   2018-11-13 23:07:38
# @Last Modified by:   JimDreamHeart
# @Last Modified time: 2020-02-05 21:17:20

import wx;

from _Global import _GG;
from function.base import *;

class AboutIPDialogUI(wx.Dialog):
	"""docstring for AboutIPDialogUI"""
	def __init__(self, parent, id = -1, curPath = "", viewCtr = None, params = {}):
		self.initParams(params);
		super(AboutIPDialogUI, self).__init__(parent, id, title = self.__params["title"], pos = self.__params.get("pos", (0,0)), size = self.__params["size"], style = self.__params["style"]);
		self._className_ = AboutIPDialogUI.__name__;
		self._curPath = curPath;
		self.__viewCtr = viewCtr;
		self.Bind(wx.EVT_CLOSE, self.onClose); # 绑定关闭事件

	def onClose(self, event):
		self.EndModal(wx.ID_CANCEL);

	def initParams(self, params):
		# 初始化参数
		self.__params = {
			"title" : "关于平台",
			"size" : (-1,-1),
			"style" : wx.DEFAULT_DIALOG_STYLE,
			"blurUrlColor" : wx.Colour(60,60,240),
			"focusUrlColor" : wx.Colour(60,60,140),
		};
		for k,v in params.items():
			self.__params[k] = v;

	def getCtr(self):
		return self.__viewCtr;

	def initDialog(self):
		self.createControls(); # 创建控件
		self.initDialogLayout(); # 初始化布局
		self.updatePosition(); # 更新位置

	def createControls(self):
		# self.getCtr().createCtrByKey("key", self._curPath + "***Dialog"); # , parent = self, params = {}
		self.createContent();
		self.createAPPTitle();
		self.createCopyrightInfo();

	def initDialogLayout(self):
		box = wx.BoxSizer(wx.VERTICAL);
		box.Add(self.__appTitle, flag = wx.ALIGN_CENTER|wx.ALL, border = 20);
		box.Add(self.__content, flag = wx.ALIGN_CENTER|wx.ALL, border = 10);
		box.Add(self.__copyrightInfo, flag = wx.ALIGN_CENTER|wx.ALL, border = 10);
		self.SetSizerAndFit(box);

	def updatePosition(self):
		if "pos" not in self.__params:
			winCenterPoint = _GG("WindowObject").GetMainWindowCenterPoint();
			self.SetPosition(wx.Point(winCenterPoint.x - self.GetSize()[0]/2, winCenterPoint.y - self.GetSize()[1]/2));

	def updateDialog(self, data):
		pass;

	def createContent(self):
		self.__content = wx.Panel(self);
		self.createVersionView(self.__content);
		self.createWebsiteView(self.__content);
		box = wx.BoxSizer(wx.VERTICAL);
		box.Add(self.__version, flag = wx.TOP|wx.BOTTOM, border = 5);
		box.Add(self.__website, flag = wx.TOP|wx.BOTTOM, border = 5);
		self.__content.SetSizerAndFit(box);

	def createVersionView(self, parent):
		self.__version = wx.Panel(parent);
		title = wx.StaticText(self.__version, label = "版本号：");
		title.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD));
		val = wx.StaticText(self.__version, label = _GG("ClientConfig").UrlConfig().GetIPVersion());
		val.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD));
		val.SetForegroundColour(wx.Colour(0,100,0));
		box = wx.BoxSizer(wx.HORIZONTAL);
		box.Add(title, flag = wx.ALIGN_CENTER|wx.RIGHT, border = 5);
		box.Add(val, flag = wx.ALIGN_CENTER);
		self.__version.SetSizerAndFit(box);

	def createWebsiteView(self, parent):
		self.__website = wx.Panel(parent);
		title = wx.StaticText(self.__website, label = "官网：");
		title.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD));
		url = wx.StaticText(self.__website, label = _GG("AppConfig")["PyToolsIPUrl"]);
		url.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, underline = True));
		url.SetForegroundColour(self.__params["blurUrlColor"]);
		url.Bind(wx.EVT_ENTER_WINDOW, self.onEnterUrl);
		url.Bind(wx.EVT_LEAVE_WINDOW, self.onLeaveUrl);
		url.Bind(wx.EVT_LEFT_DOWN, self.onClickUrl);
		box = wx.BoxSizer(wx.HORIZONTAL);
		box.Add(title, flag = wx.ALIGN_CENTER|wx.RIGHT, border = 5);
		box.Add(url, flag = wx.ALIGN_CENTER);
		self.__website.SetSizerAndFit(box);

	def onEnterUrl(self, event):
		event.GetEventObject().SetForegroundColour(self.__params["focusUrlColor"]);
		event.GetEventObject().Refresh();

	def onLeaveUrl(self, event):
		event.GetEventObject().SetForegroundColour(self.__params["blurUrlColor"]);
		event.GetEventObject().Refresh();

	def onClickUrl(self, event):
		if wx.MessageDialog(self,"查看平台官网需要打开浏览器，是否确认打开？", "打开浏览器提示", style = wx.OK|wx.CANCEL|wx.ICON_QUESTION).ShowModal() == wx.ID_OK:
			self.getCtr().openUrl(event.GetEventObject().GetLabel());
		pass;

	def createAPPTitle(self):
		self.__appTitle = wx.StaticText(self, label = _GG("AppConfig")["AppTitle"], style = wx.ALIGN_CENTER);
		self.__appTitle.SetFont(wx.Font(16, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD));

	def createCopyrightInfo(self):
		self.__copyrightInfo = wx.StaticText(self, label = _GG("AppConfig")["CopyrightInfo"], style = wx.ALIGN_CENTER);
		self.__copyrightInfo.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL));


import numpy as np

from keras.models import Sequential
from keras.layers import Dense,Activation
from keras import optimizers,losses
from keras.wrappers.scikit_learn import KerasClassifier
from keras.layers.advanced_activations import LeakyReLU,PReLU
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten
import keras

import cv2
import os

batch_size = 10
num_epochs = 5
num_datapoints = 5

input_base_directory = "../Datasets/Images/"

test_pos_directory = "../datasets/testset/Face/"
test_neg_directory = "../datasets/testset/Other/"
pos_test_filename_Format = test_pos_directory + "Face_frame_"
neg_test_filename_Format = test_neg_directory + "Other_frame_"

output_dim = 2

def str_to_img(s):
	img = list(map(lambda x: 1 if x=='1' else 0,s.split(",")))
	return img

def shape(line):
	return np.array(list(map(lambda x: int(x), line.split(",")))).reshape(-1,28)

def make_model():
	model = Sequential()
	model.add(Conv2D(32, kernel_size=(3, 3),
	                 activation='relu',
	                 input_shape=(150,90,1)))
	model.add(Conv2D(64, (3, 3), activation='relu'))
	# model.add(MaxPooling2D(pool_size=(2, 2)))
	# model.add(Dropout(0.25))
	model.add(Flatten())
	model.add(Dense(128, activation='relu'))
	# model.add(Dropout(0.5))
	model.add(Dense(output_dim, activation='softmax'))
	model.compile(loss=keras.losses.categorical_crossentropy,
	optimizer=keras.optimizers.Adadelta(),
	metrics=['accuracy'])

	return model

def get_file_data(filename_x,filename_y,one_hot_labels=True):
	with open(filename_x) as file_x,open(filename_y) as file_y:
		r_labels = []; r_data = [];
		for line in file_x:
			r_data.append(shape(line))
		if one_hot_labels:
			for line in file_y:
				r_labels.append(labels[int(line.strip())])
			r_labels=np.array(r_labels)
		else:
			for line in file_y:
				r_labels.append(int(line.strip()))
	r_data = np.array(r_data).reshape(len(r_data),28,28,1)

	return r_data,r_labels

def get_test_accuracy(test_data,test_labels,model):
	predicted_labels = model.predict(test_data)
	predicted_labels= list(map(lambda x: np.argmax(x),predicted_labels))
	num_right = 0
	for predicted,actual in zip(predicted_labels,test_labels):
		num_right += 1 if predicted == actual else 0
	return num_right/len(test_labels)

def get_images(num_datapoints,sub_dir):
	img_base_path = input_base_directory + sub_dir + "/"
	images = []
	for i in range(1,num_datapoints+1):
		img_path = img_base_path + sub_dir + "_frame_" + str(i).zfill(2) + ".png"
		img = cv2.imread(img_path,0) #0 for grayscale
		images.append(img)
	return images

def main():
	train_data = []
	train_labels = []

	train_data += get_images(num_datapoints,"Face")
	train_labels += ([1,0] for i in range(num_datapoints))

	train_data = np.array(train_data)
	train_labels = np.array(train_labels)

	train_data = train_data.reshape(len(train_data),150,90,1)

	model = make_model()
	model.fit(train_data,train_labels,epochs=1,batch_size=batch_size)

	# test_data.append(get_images(num_datapoints,"Other"))
	# test_labels.append([0,1] for i in range(num_datapoints))

if __name__ == '__main__':
	main()


#-*- coding: utf-8 -*-
"""
Koord is designed to be an indentation based language
so we implemented a basic indentation lexer for it.
We used python-lex-yacc (ply) for this.

.. module::indentlexer
   :synopsis: indentation based lexical analyzer.
.. moduleauthor:: Ritwika Ghosh <rghosh9@illinois.edu>

"""
from ply import *
from scanner import *

#macros
NO_INDENT = 0
MAY_INDENT = 1
MUST_INDENT = 2

#implementing a white space filter which makes sure to ignore white spaces
#which are not at the start of a line
def ws_filter(lexer, tokens):
    """
    implementing a white space filter which makes sure to ignore
    white spaces which are not at the start of a line

    Args:
        lexer (lexer) : the lexer object.
        tokens (tokens) : tokens of the lexer.
    Returns:
        (none) : yields the set of tokens without irrelevant spaces

    """
    lexer.line_start = line_start = True
    indent = NO_INDENT
    for token in tokens:
        token.line_start = line_start
        #if a colon is seen, the next line may be indented if a complex statement,
        #not indented if simple statement
        if token.type == 'COLON':
            line_start = False
            indent = MAY_INDENT
            token.must_indent = False
        #if a new line is seen, if it saw a colon before,
        #then it must indent . otherwise ignore.
        elif token.type == "NL":
            line_start = True
            if indent == MAY_INDENT:
                indent = MUST_INDENT
            token.must_indent = False
        #white spaces must be at the start of a line.
        elif token.type == 'WS':
            assert token.line_start
            line_start = True
            token.must_indent = False
        else:
            token.must_indent = (indent == MUST_INDENT)
            line_start = False
            indent = NO_INDENT
        yield token
        lexer.line_start = line_start

#see gardensnake.py in the ply distribution for documentation on this. copied almost line by line.

def indent_filter(tokens):
    """
    implementing an indentation filter which adds correct indents and dedents

    Args:
        tokens (tokens) : tokens of the lexer.
    Returns:
        (none) : yields proper indentation, or raises indentation errors.

    """
    levels = [0]
    token = None
    depth = 0
    prev_ws = False

    for token in tokens:
        if token.type == 'WS':
            assert depth == 0

            depth = len(token.value)
            prev_ws = True

            continue

        elif token.type == 'NL':
            depth = 0
            if prev_ws or token.line_start:
                continue
            yield token
            continue

        prev_ws = False
        if token.must_indent:
            if depth <= levels[-1]:
                raise IndentationError("expected an indented block at line %r" %(token.lineno))
            levels.append(depth)
            yield INDENT(token.lineno)

        elif token.line_start:
            if depth == levels[-1]:
                pass
            elif depth > levels[-1]:
                raise IndentationError("indentation increase but not in new block")
            else:
                try:
                    i = levels.index(depth)
                except ValueError:
                    raise IndentationError("inconsistent indentation")
                for _ in range(i+1, len(levels)):
                    yield DEDENT(token.lineno)
                    levels.pop()
        yield token

    if len(levels) > 1:
        assert token is not None
        for _ in range(1, len(levels)):
            yield DEDENT(token.lineno)

#final filter. may need an endmarker.

def filter(lexer):
    """
    implementing an lexer filter which iteratively applies the filters,
    and yields the filtered tokens.
    See gardensnake in ply documentation for more, this is almost a carbon copy.

    Args:
        tokens (tokens) : tokens of the lexer.
    Returns:
        (none) : yields correct tokens.

    """
    token = None
    tokens = iter(lexer.token, None)
    tokens = ws_filter(lexer, tokens)
    for token in indent_filter(tokens):
        yield token

class IndentLexer(object):
    """
    The indent lexer class, which can create a lexer
    and return indented code in terms of tokens.
    """
    def __init__(self):
        self.lexer = lex.lex()
        self.token_stream = None

    def input(self, code):
        """
        function to take in code, and apply the filters.
        """
        self.lexer.paren_count = 0
        self.lexer.input(code)
        self.token_stream = filter(self.lexer)

    def token(self):
        """
        function to yield the next token.
        """
        try:
            #print(self.lexer.paren_count)
            return self.token_stream.next()
        except StopIteration:
            return None

LEXER = IndentLexer()


#!/usr/bin/python

# Extracts data entities from an stp file and sorts them by number

f, f_keys = [], []

# Get all data entities
fn = "examples/test_sketch.stp"
with open(fn) as stp:
    for line in stp:
        # Reconnect broken lines
        while len(line) > 3 and line[-3] != ';':
            line = line[:-2]
            line += next(stp)

        # Save all data entities and their numbers
        if line[0] == '#' and '=' in line:
            stop = line.find('=')
            f.append(line)
            f_keys.append(int(line[1:stop]))

# Sort all data entities by their number
f = [x for _, x in sorted(zip(f_keys, f), key=lambda pair: pair[0])]

# Output result
with open("examples/test_sketch_out.txt", 'w') as out:
    prev = 0
    for line in f:
        out.write(line)


#!/usr/bin/env python

# Code on Github repository: https://github.com/jmssalas/Artificial-Vision-Exercises-2017

# Press 'Esc' key for exit
# Press 'Enter' key for make transformation
# Press 'd' key for calculate distance between points
# Press 'c' key for clear all points
# Use mouse for select points

# Execute: ./exercise11.py [-h] source reference
# where:
#   - source is the source image
#   - reference is the reference image
# Use -h option for help

##################################
## PROBLEM STATEMENT (IN SPANISH)
## -------------------------------
##
## Rectifica la imagen de un plano para medir distancias (tomando referencias manualmente)
##################################

import numpy            as np
import cv2              as cv
import argparse

from    os.path         import isfile

# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('source', help='Source image')
parser.add_argument('reference', help='Reference image')
args = parser.parse_args()

# Check if 'source' param is not a file. If it's not file, then exit
if not isfile(args.source):
    print('Error: {} is not a file'.format(args.source))
    exit(-2)

# Check if 'reference' param is not a file. If it's not file, then exit
if not isfile(args.reference):
    print('Error: {} is not a file'.format(args.reference))
    exit(-2)

programName = 'exercise11'          # Program name

srcWindow = programName + ' - source'           # Original image's window
refWindow = programName + ' - reference'        # Reference image's window
dstWindow = programName + ' - transformed'      # Transformed image's window

escKey = 27                         # Escape key code
enterKey = 10                       # Enter key code
distanceKey = ord('d')              # distance key code
clearKey = ord('c')                 # clear key code

srcPoints = list()                  # List of points selected in srcWindow
refPoints = list()                  # List of points selected in refWindow
dstPoints = list()                  # List of points selected in dstWindow

# Dictionary of lists of points
points = {srcWindow: srcPoints, refWindow: refPoints, dstWindow: dstPoints}

# P1-P2 points on reference Image
p1, p2 = None, None
# Real distance between P1-P2 on reference image
measurement = 0

# This variables are for modify the references points before make transformation
dx = 100    # displacement in X
dy = 500    # displacement in Y
sx = 0.5    # scale factor in X
sy = 0.5    # scale factor in Y

# Mouse event handler
def srcMouseEventHandler(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDOWN:
        srcPoints.append((x,y))
        putPoint(image=srcImage, point=(x,y), text='p'+str(len(srcPoints)))

# Mouse event handler
def dstMouseEventHandler(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDOWN:
        dstPoints.append((x, y))
        putPoint(image=dstImage, point=(x,y), text='p'+str(len(dstPoints)))

# Mouse event handler
def refMouseEventHandler(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDOWN:
        refPoints.append((x, y))
        putPoint(image=refImage, point=(x,y), text='p'+str(len(refPoints)))

# Set window's name
cv.namedWindow(srcWindow)
# Set mouseCallback to srcMouseEventHandler
cv.setMouseCallback(srcWindow, srcMouseEventHandler)

# Set window's name
cv.namedWindow(refWindow)
# Set mouseCallback to refMouseEventHandler
cv.setMouseCallback(refWindow, refMouseEventHandler)

# Read image in BGR
def readbgr(file):
    return cv.imread(file)

# Get input key
def getInputKey():
    return cv.waitKey(1) & 0xFF

# Put 'text' param above 'image' param in the 'origin' position
def putText(image, text, origin):
    cv.putText(img=image, text=text, org=origin, fontFace=cv.FONT_HERSHEY_PLAIN, fontScale=1, color=(0,255,0))  # Draw the text

# Draw circle above 'image' with center in 'point' point
def drawCircle(image, point):
    cv.circle(img=image, center=point, radius=1, color=(0, 255, 0))

# Put 'point' point above 'image' image with 'text' text
def putPoint(image, point, text):
    drawCircle(image=image, point=point)
    x,y = point
    putText(image=image, text=text, origin=(x+1,y+1))

# Draw line above 'image' with origin 'origin' and destination 'destination'
def drawLine(image, origin, destination) :
    cv.line(img=image, pt1=origin, pt2=destination, color=(0, 255, 0))

# Make a vector (array 1D)
def vec(*argn):
    return np.array(argn)

# Make H of displacement
def desp(d):
    dx,dy = d
    return np.array([
            [1,0,dx],
            [0,1,dy],
            [0,0,1]])

# Make H of scale
def scale(s):
    sx,sy = s
    return np.array([
            [sx,0,0],
            [0,sy,0],
            [0,0,1]])

# Convert a normal points to homogeneous points
def homog(x):
    ax = np.array(x)
    uc = np.ones(ax.shape[:-1]+(1,))
    return np.append(ax,uc,axis=-1)

# Convert a homogeneous points to normal points
def inhomog(x):
    ax = np.array(x)
    return ax[..., :-1] / ax[...,[-1]]

# Apply a homogeneous transformation 'h' to 'x' normal points
def htrans(h,x):
    return inhomog(homog(x) @ h.T)

# Convert list to array
def convertListToArray(list):
    return np.array(list).reshape(-1, 2)

# Function which make transformation of source image above reference image
def makeTransformation():
    global dstImage, dstOriginal

    # I do it here because if I do it when set the others windows
    # a black window will be showed and this does not have much sense
    # Set window's name
    cv.namedWindow(dstWindow)
    # Set mouseCallback to dstMouseEventHandler
    cv.setMouseCallback(dstWindow, dstMouseEventHandler)

    # Convert points lists to arrays
    view = convertListToArray(srcPoints)
    dst = convertListToArray(refPoints)

    # Modify a little the reference image
    dst = htrans(desp(vec(dx,dy)) @ scale(vec(sx, sy)), dst)

    # Find homography
    H, _ = cv.findHomography(view, dst)

    # Undo transformation
    dstOriginal = cv.warpPerspective(srcOriginal, H, (800,800))
    dstImage = np.copy(dstOriginal)

# Function which convert 'distance' in pixel to 'measurement' measurement
def convertDistance(distance, measurement):
    # Calculate distance between p1 and p2
    distP1P2 = np.sqrt(np.sum((vec(p2) - vec(p1)) ** 2))

    return distance*measurement/distP1P2

# Function which calculate distance between points of transformed image
def calculateDistances():
    print('The distance is:')

    distance = 0.0
    # For each couple of points
    for p1, p2 in [ (vec(x), vec(y)) for (x,y) in zip(dstPoints, dstPoints[1:]) ]:
        # Calculate distance
        dis = np.sqrt(np.sum((p2 - p1) ** 2))
        distance += dis

    realDistance = convertDistance(distance, measurement)

    # Put real distance above 'dstImage'
    putText(image=dstImage, text='The real distance is '+str(realDistance), origin=(20,20))
    # Print real distance for console
    print('The real distance is', realDistance)

# Clear points lists
def clearPointsLists():
    for list in points.values():
        list.clear()

# Restart images
def restartImages():
    global srcImage, refImage, dstOriginal, dstImage
    srcImage = np.copy(srcOriginal)
    refImage = np.copy(refOriginal)

    if dstOriginal is not None:
        dstImage = np.copy(dstOriginal)

# Check if reference points above 'transformed' image have been selected.
# It is for getting a reference distance for calculating real distance between two points.
def checkIfReferencePointsHaveBeenSelected() :
    global measurement, p1, p2

    if p1 is not None or p2 is not None:
        return True

    if len(dstPoints) != 2:
        print('ERROR: You must select only two points')
        exit(-3)

    # Ask the real distance between P1-P2 on reference image
    measurement = float(input('Introduce the real distance between P1-P2:'))
    # Get P1-P2 points of refPoints before clear point list
    p1 = dstPoints[0]; p2 = dstPoints[1]

    clearPointsLists(); restartImages()

    return False

srcOriginal = readbgr(args.source)
refOriginal = readbgr(args.reference)
dstOriginal = None

srcImage = None
refImage = None
dstImage = None

# Main function.
def play():
    restartImages()

    while (True):

        # Get input key
        key = getInputKey()

        if key == escKey: break

        if key == enterKey:
            srcLen = len(srcPoints)
            refLen = len(refPoints)

            # Only make transformation if the points have been selected
            if srcLen != 0 and refLen != 0:
                # Check if there are same points in source and reference images
                if srcLen != refLen :
                    print('ERROR: The points on source and reference windows must be equals')
                    exit(-1)

                # Make transformation
                makeTransformation()

                # Clear points and restart images for can select others points
                clearPointsLists()
                restartImages()

                print('First, select only two reference point above transformed window. After, press "d".')

        if key == distanceKey:
            # Check if the transformation has been make before calculatedistances
            if dstImage is None:
                print('ERROR: First, you must make transformation')
                exit(-3)

            if not checkIfReferencePointsHaveBeenSelected() :
                print('Now, select points for calculate distance and press "d" again.')

            # Only calculate distances when at least two points have been selected
            if len(dstPoints) > 1:
                calculateDistances()

        if key == clearKey:
            clearPointsLists()
            restartImages()

        # Show frames
        cv.imshow(srcWindow, srcImage)
        cv.imshow(refWindow, refImage)
        if dstImage is not None:
            cv.imshow(dstWindow, dstImage)

if __name__ == "__main__":
    play()


from skimage.io import imread

im = imread('tiles.png', as_gray=True)

h, w = im.shape
s = ''
for i in range(h):
    s += '"'
    for j in range(w):
        s += str(int(im[i,j]))
    s += '"'
    if i == h-1:
        s += ' '
    else:
        s += ','
    s += ' --' + str(i) + '\n'

file = open('rom.txt','w')
file.write(s)
file.close()


def countAfterFold(paper, folds, numFolds):
    for fold in folds[:numFolds]:
        if 'y' in fold[0]:
            top = int(fold[1]) - 1
            bottom = int(fold[1]) + 1
            while top >= 0 and bottom < len(paper):
                rowTop, rowBottom = paper[top], paper[bottom]
                top -= 1
                bottom += 1
                for i in range(0, len(rowBottom)):
                    if rowBottom[i] == '#':
                        rowTop[i] = '#'
            paper = paper[:int(fold[1])]

        elif 'x' in fold[0]:
            left = int(fold[1]) - 1
            right = int(fold[1]) + 1
            while left >= 0 and right < len(paper[0]):
                for row in paper:
                    if row[right] == '#':
                        row[left] = '#'
                left -= 1
                right += 1
            paper = [row[:int(fold[1])] for row in paper]

    return paper

def getInput():
    dots = []
    folds = []
    dotInput = True
    maxX = 0
    maxY = 0
    with open("./Day13_Input.txt") as inputFile:
        for line in inputFile:
            line = line.strip()
            if line == "":
                dotInput = False
                continue

            if dotInput:
                tokens = line.split(',')
                dots.append([int(tokens[0]), int(tokens[1])])
                maxX = max(maxX, int(tokens[0]))
                maxY = max(maxY, int(tokens[1]))
            else:
                tokens = line.split('=')
                folds.append([tokens[0], tokens[1]])
    return {"dots": dots, "folds": folds, "X-Limit": maxX, "Y-Limit": maxY}

input = getInput()
dots = input["dots"]
folds = input["folds"]
xLimit = input["X-Limit"]
yLimit = input["Y-Limit"]

paper = []
for r in range(0, yLimit + 1):
    paper.append(['.' for c in range(0, xLimit + 1)])

for dot in dots:
    paper[dot[1]][dot[0]] = '#'

# Part 1
paper = countAfterFold(paper, folds, 1)
numDots = 0
for row in paper:
    for data in row:
        if data == '#':
            numDots += 1
print("Number of Dots after 1st Fold: " + str(numDots))

# Part 2
paper = countAfterFold(paper, folds, len(folds))
print("After All Folds:")
for row in paper:
    for data in row:
        print(data, end="")
    print()


import xml.etree.ElementTree as ET
import sys
import numpy
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
numpy.set_printoptions(threshold=sys.maxsize)

"------------------------XML Parsing------------------------------"

#articles
tree = ET.parse("D:\\Files\\first1000.xml")
all_articles = tree.getroot()

#truths
oak_tree = ET.parse("D:\\Files\\truth1000.xml")
all_truth = oak_tree.getroot()

cachedStopWords = stopwords.words("english")

#here we are saving all those currently unused stuff like title,date,url
#and etc.
article_unused = []

#here we are saving all paragraphs ready for vectorizing
articles_ready_for_vectorizing = []

"-------------------------------------------------------------------"

"-------------------- Articles processing ------------------------- "

#going through every article in xml file
for article in all_articles:
    article_unused.append(article.attrib)
    article_text = ""
    for paragraph in article:
        if(paragraph.text != None):
            article_text = article_text+paragraph.text

    #removing stop words
    new_article_text = ' '.join([word for word in article_text.split() if word not in cachedStopWords])

    articles_ready_for_vectorizing.append(new_article_text)

#vector
vectorizer = CountVectorizer()

#matrix ready for ML models
matrix = vectorizer.fit_transform(articles_ready_for_vectorizing).todense()

with open('matrix.txt', 'w') as f:
    for vector in matrix:
        for item in vector:
            f.write("%s\n" % item)

#all vocabulary we have in articles
#print(vectorizer.vocabulary_)

"-----------------------------------------------------------------"

"-----------------------Truth processing--------------------------"

#final vector for ML testing
truth_vector = []

#going through every truth in xml file
for truth in all_truth:
    current_truth = truth.attrib
    hyperpartisan = current_truth['hyperpartisan']
    if(hyperpartisan == 'true'):
        truth_vector.append(1)
    else:
        truth_vector.append(0)

with open('truth.txt', 'w') as f:
    for item in truth_vector:
        f.write("%s\n" % item)

"------------------------------------------------------------------"


# -*- coding: utf-8 -*-
import os
import cgi
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from base import tarsusaRequestHandler

class AboutPage(tarsusaRequestHandler):
    def get(self):
        strdevVersion = os.environ['CURRENT_VERSION_ID']
        if self.chk_login():
            CurrentUser = self.get_user_db()
            template_values = {
                    'UserLoggedIn': 'Logged In',
                    'UserNickName': cgi.escape(CurrentUser.dispname),
                    'UserID': CurrentUser.key().id(),
                    'devVersion': strdevVersion,
            }
        else:
            template_values = {
                'UserNickName': "访客",
                'AnonymousVisitor': "Yes",
                'devVersion': strdevVersion,
            }
        path = os.path.join(os.path.dirname(__file__), '../pages/calit2/about.html')
        self.response.out.write(template.render(path, template_values))

class DocsPage(tarsusaRequestHandler):
    def get(self):

        if self.chk_login():
            CurrentUser = self.get_user_db()
            template_values = {
                    'PrefixCSSdir': "/",
                    'UserLoggedIn': 'Logged In',
                    'UserNickName': cgi.escape(CurrentUser.dispname),
                    'UserID': CurrentUser.key().id(),
            }

        else:
            template_values = {
                'PrefixCSSdir': "/",
                'UserNickName': "访客",
                'AnonymousVisitor': "Yes",
            }

        pageid = self.request.path[len('/docs/'):]
        if pageid == '':
            pageid = 'docs_index'
        path = os.path.join(os.path.dirname(__file__), '../pages/calit2/docs/' + pageid + '.html')

        self.response.out.write(template.render(path, template_values))

def main():
    application = webapp.WSGIApplication([('/about',AboutPage),
                                       ('/docs.+', DocsPage),
                                       ],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
      main()


import discord
from discord.ext import commands, tasks
import datetime
import character_sheet, json, asyncio
import random
import Googlify, RockPaperScissors, boons, DeityMessage, CanonList, OocMessage, hmk, valentine_generator, roll, RoleAssignment, TrickOrTreat, FishingGame
import re, time, os
import BotseriaServers
import aioscheduler

intents = discord.Intents.default()
intents.dm_reactions = True
intents.members = True

TOKEN = open('token.token').read()

bot = commands.Bot(command_prefix='>', case_insensitive=True, intents=intents, activity=discord.Game('with 0 pets today.'))
servers = BotseriaServers.PopulateServers()

bot.hmkGames = []
bot.rpsGames = []
bot.totGames = []
bot.factionMessages = BotseriaServers.PopulateFactionMessages(servers)
bot.canonMessages = {}
bot.oocMessages = {}
bot.hmkScoreMessages = {}
bot.roleMessages = {}
bot.petCounter = 0
bot.fishingGame = None
bot.monthCheck = False

def check_if_test_channel(ctx):
	#return ctx.channel.id == TESTCHANNEL
	if(str(ctx.guild.id) in servers):
		testchannels = [servers[guild]['testchannel'] for guild in servers]
		return ctx.channel.id in testchannels
	return False

def check_if_staff_or_test(ctx):
	#return ctx.guild.get_role(STAFFROLE) in ctx.author.roles or check_if_test_channel(ctx)
	if(str(ctx.guild.id) in servers):
		staffrole = servers[str(ctx.guild.id)]['staff']
		#print([servers[guild].keys() for guild in servers])
		#staffrole = [servers[guild]['staff'] for guild in servers if ctx.guild.get_role(int(servers[guild]['staff'])) != None][0]
		return ctx.guild.get_role(int(staffrole)) in ctx.author.roles or check_if_test_channel(ctx)
	return False

def check_if_december(ctx):
	return (time.localtime().tm_mon == 12) or (check_if_staff_or_test(ctx))

def check_if_february(ctx):
	return (time.localtime().tm_mon == 2) or (check_if_staff_or_test(ctx))

def check_if_october(ctx):
	return (time.localtime().tm_mon == 10) or (check_if_staff_or_test(ctx))

def check_if_bot_spam(ctx):
	if(str(ctx.guild.id) in servers):
		botchannel = int(servers[str(ctx.guild.id)]['botchannel'])
		return (ctx.channel.id == botchannel or check_if_staff_or_test(ctx))
	return False

@bot.event
async def on_ready():
	print('Logged in as')
	print(bot.user.name)
	print(bot.user.id)
	print('------')

@bot.command()
@commands.check(check_if_staff_or_test)
async def logout(ctx):
	await bot.logout()
	await bot.close()

@bot.command()
@commands.check(check_if_staff_or_test)
async def repopulate(ctx):
	'''***STAFF ONLY***'''
	await character_sheet.repopulate(ctx, servers)
	await ctx.send('Repopulated character list!')

@bot.command()
@commands.check(check_if_staff_or_test)
async def fetch(ctx):
	'''***STAFF ONLY***'''
	await character_sheet.Fetch(ctx.channel, ctx, servers)

@bot.command()
async def char(ctx, *, arg):
	name = arg.lower()
	if(str(ctx.guild.id) in servers):
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(name in data.keys()):
			characterInfo = data[name]
			output = character_sheet.MakeEmbed(name.title(), characterInfo, servers[str(ctx.guild.id)])
			await ctx.send(embed=output)
		else:
			output = 'Invalid character!\n```{}```'.format(name)
			await ctx.send(output)

@bot.command()
async def charlist(ctx, *, arg=''):
	if(len(arg) > 0):
		messageList = arg.split()
		if(messageList[-1].isdigit()):
			command = ' '.join(messageList[0:-1]).lower()
			number = int(messageList[-1])
		else:
			command = arg.lower()
			number = None
	else:
		command = ''
		number = None
	if(command == ''):
		# List all characters on Heavensfall
		if(number == None):
			bot.factionMessages['all'] = DeityMessage.DeityMessage('all', ctx.author, ctx, servers)
			await bot.factionMessages['all'].Send(ctx.channel)
			await bot.factionMessages['all'].ListNames()
		# Skip to a specific number of an existing message
		else:
			allMessage = bot.factionMessages['all']
			if(ctx.author == allMessage.user):
				if(number <= len(allMessage.characterList) and number >= 1):
					allMessage.index = number - 1
					await allMessage.Edit()
	# Deity character lists
	elif(command in bot.factionMessages):
		deity = command.lower()
		# List all characters of that deity
		if(number == None):
			bot.factionMessages[deity] = DeityMessage.DeityMessage(deity, ctx.author, ctx, servers)
			await bot.factionMessages[deity.lower()].Send(ctx.channel)
			await bot.factionMessages[deity].ListNames()
		# Skip to a specific number of an existing message
		else:
			factionMessage = bot.factionMessages[command]
			if(ctx.author == factionMessage.user):
				if(number <= len(factionMessage.characterList) and number >= 1):
					factionMessage.index = number-1
					await factionMessage.Edit()
	# Canon character lists
	elif(command in [canon[0] for canon in CanonList.CanonList(servers[str(ctx.guild.id)])]):
		canon = command
		# List all characters of that canon
		if(number == None):
			bot.canonMessages[canon] = CanonList.CanonMessage(canon, ctx.author, ctx, servers)
			await bot.canonMessages[canon].Send(ctx.channel)
			await bot.canonMessages[canon].ListNames()
		# Skip to a specific number of an existing message
		else:
			if(canon in bot.canonMessages):
				canonMessage = bot.canonMessages[canon]
				if(ctx.author == canonMessage.user):
					if(number <= len(canonMessage.characterList) and number >= 1):
						canonMessage.index = number - 1
						await canonMessage.Edit()
	# OOC character lists
	elif(command in OocMessage.OocList(ctx)):
		oocName = command
		# List all characters of that OOC
		if(number == None):
			bot.oocMessages[oocName] = OocMessage.OocMessage(ctx.author, oocName, ctx, servers)
			await bot.oocMessages[oocName].Send(ctx.channel)
			await bot.oocMessages[oocName].ListNames()
		# Skip to a specific number of an existing message
		else:
			oocMessage = bot.oocMessages[oocName]
			if(ctx.author == oocMessage.user):
				if(number <= len(oocMessage.characterList) and number >= 1):
					oocMessage.index = number - 1
					await oocMessage.Edit()

@bot.command()
async def canonlist(ctx):
	canonList = CanonList.CanonList(servers[str(ctx.guild.id)])
	index = 0
	sendString = 'Valid canons: ```'
	while(index < len(canonList)):
		while(len(sendString) < 1900):
			sendString += ('\n' + '{:<30}: {}'.format(canonList[index][0], canonList[index][1]))
			index += 1
			if(index >= len(canonList)):
				break
		sendString += '```'
		await ctx.send(sendString)
		sendString = '```'
	await ctx.send('>charlist [canon] to list characters for a canon')

@bot.command()
async def forward(ctx):
	await ctx.send('and back')
	await asyncio.sleep(2)
	await ctx.send('and then forward and back')
	await asyncio.sleep(2)
	await ctx.send('and then go forward and back')
	await asyncio.sleep(2)
	await ctx.send('and put one foot')
	await ctx.send('forward')

@bot.command()
@commands.check(check_if_staff_or_test)
async def rolemessage(ctx):
	#await ctx.send('Test',view=RoleAssignment.RoleAssignment())
	#embed = discord.Embed()
	#embed.description = "React to add role:\nðŸ‘© she/her\nðŸ‘¨ he/him\nðŸ‘¤ they/them"
	#bot.roleMessages[ctx.guild.id] = await ctx.send(embed=embed)
	#await bot.roleMessages[ctx.guild.id].add_reaction('ðŸ‘©')
	#await bot.roleMessages[ctx.guild.id].add_reaction('ðŸ‘¨')
	#await bot.roleMessages[ctx.guild.id].add_reaction('ðŸ‘¤')
	bot.roleMessages[ctx.guild.id] = RoleAssignment.RoleMessage(ctx)
	print(ctx.guild.id)
	await bot.roleMessages[ctx.guild.id].Send(ctx)

@bot.command()
#@commands.check(check_if_bot_spam)
async def fish(ctx):
	bot.fishingGame = FishingGame.FishingGame(ctx)
	await ctx.send("Reel in when a fish bites!", view=bot.fishingGame)
	await asyncio.sleep(5)
	await bot.fishingGame.ChangeStatus('Bite')
	if(bot.fishingGame.finished == False):
		await ctx.send("Oh! A bite!")
	await asyncio.sleep(5)
	await bot.fishingGame.ChangeStatus('Got Away')

@bot.command()
async def iam(ctx, *, arg=''):
	if(arg == ''):
		validRoles = servers[str(ctx.guild.id)]["roles"]
		#await ctx.send('I need to know what role you want, silly! Valid roles:\n```{}```'.format('\n'.join(list(ROLES.keys()))))
		await ctx.send('I need to know what role you want, silly! Valid roles:\n```{}```'.format('\n'.join(list(validRoles.keys()))))
	elif(arg.lower() == 'the bone of my sword'):
		# Kat is a weeb
		await ctx.send('Steel is my Body and Fire is my Blood.')
		await asyncio.sleep(2)
		await ctx.send('I have created over a Thousand Blades,')
		await asyncio.sleep(2)
		await ctx.send('Unknown to Death,')
		await asyncio.sleep(2)
		await ctx.send('Nor known to Life.')
		await asyncio.sleep(2)
		await ctx.send('Have withstood Pain to create many Weapons')
		await asyncio.sleep(2)
		await ctx.send('Yet those Hands will never hold Anything.')
		await asyncio.sleep(2)
		await ctx.send('So, as I Pray-')
		await asyncio.sleep(2)
		await ctx.send('**UNLIMITED BLADE WORKS**')
		await asyncio.sleep(1)
		await ctx.send(':crossed_swords:'*125)
	elif(arg.lower() == 'the night'):
		Googlify.Batmanify(Googlify.ImageFromURL(str(ctx.author.avatar))).save('tempBat.png')
		await ctx.send(file=discord.File('tempBat.png'))
	else:
		desiredRole = arg.lower()
		validRoles = servers[str(ctx.guild.id)]["roles"]
		#if(desiredRole in ROLES.keys()):
		if(desiredRole in validRoles.keys()):
			#if(ctx.guild.get_role(ROLES[desiredRole]) in ctx.author.roles):
			if(ctx.guild.get_role(validRoles[desiredRole]) in ctx.author.roles):
				await ctx.send('You already have role\n```{}```'.format(desiredRole))
			else:
				#await ctx.author.add_roles(ctx.guild.get_role(ROLES[desiredRole]))
				await ctx.author.add_roles(ctx.guild.get_role(validRoles[desiredRole]))
				await ctx.send('Role `{}` assigned!'.format(desiredRole))
		else:
			await ctx.send('Role `{}` not found.'.format(desiredRole))

@bot.command()
async def iamnot(ctx, *, arg=''):
	if(arg == ''):
		validRoles = servers[str(ctx.guild.id)]["roles"]
		#await ctx.send('I need to know what role you aren\'t, silly! Valid roles:\n```{}```'.format('\n'.join(list(ROLES.keys()))))
		await ctx.send('I need to know what role you aren\'t, silly! Valid roles:\n```{}```'.format('\n'.join(list(validRoles.keys()))))
	else:
		validRoles = servers[str(ctx.guild.id)]["roles"]
		desiredRole = arg.lower()
		if(desiredRole in validRoles.keys()):
			#if(ctx.guild.get_role(ROLES[desiredRole]) in ctx.author.roles):
			if(ctx.guild.get_role(validRoles[desiredRole]) in ctx.author.roles):
				#await ctx.author.remove_roles(ctx.guild.get_role(ROLES[desiredRole]))
				await ctx.author.remove_roles(ctx.guild.get_role(validRoles[desiredRole]))
				await ctx.send('Removed role\n```{}```'.format(desiredRole))
			else:
				await ctx.send('You do not have role\n```{}```'.format(desiredRole))
		else:
			await ctx.send('Role `{}` not found.'.format(desiredRole))

@bot.command()
async def sector(ctx):
	#faction = random.choice(FACTIONS)
	factions = servers[str(ctx.guild.id)]['factions']
	faction = random.choice(factions)
	text = ['Uplander! Uplander, make lookings! Swooshy spellycastings is sayings....um....is sayings {} is good choosymakes!'.format(faction),
			'According to the position of the stars, the placement of your bedroom, and the ripeness of this pickle - {} is the best sector for you!'.format(faction),
			'The fates have chosen, oh indecisive one - {} has found you worthy to fight in their name!'.format(faction)]
	await ctx.send(random.choice(text))

@bot.command()
async def hitme(ctx):
	with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
		data = json.load(json_data)
	character = random.choice(list(data.keys()))
	characterInfo = data[character]
	output = character_sheet.MakeEmbed(character.title(), characterInfo, servers[str(ctx.guild.id)])
	await ctx.send(embed=output)

@bot.command()
async def templates(ctx):
	await ctx.send('You can find Magician\'s templates here!\n{}'.format(servers[str(ctx.guild.id)]["templates"]))

@bot.command()
#@commands.check(check_if_bot_spam)
async def googlify(ctx, *, arg=''):
	#print(type(ctx.author.avatar))
	if(arg == ''):
		Googlify.Googlify(Googlify.ImageFromURL(str(ctx.author.avatar))).save('tempGoogly.png')
		await ctx.send(file=discord.File('tempGoogly.png'))
	elif(len(ctx.message.mentions) > 0):
		Googlify.Googlify(Googlify.ImageFromURL(str(ctx.message.mentions[0].avatar))).save('tempGoogly.png')
		await ctx.send(file=discord.File('tempGoogly.png'))
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(arg.lower() in data.keys()):
			Googlify.Googlify(Googlify.ImageFromURL(data[arg.lower()]['image'])).save('tempGoogly.png')
			await ctx.send(file=discord.File('tempGoogly.png'))
		else:
			await ctx.send('Character not found:```{}```'.format(arg.lower()))

@bot.command()
@commands.check(check_if_december)
async def santafy(ctx, *, arg=''):
	if(arg == ''):
		Googlify.Santafy(Googlify.ImageFromURL(str(ctx.author.avatar))).save('tempSanta.png')
		await ctx.send(file=discord.File('tempSanta.png'))
	elif(len(ctx.message.mentions) > 0):
		Googlify.Santafy(Googlify.ImageFromURL(str(ctx.message.mentions[0].avatar))).save('tempSanta.png')
		await ctx.send(file=discord.File('tempSanta.png'))
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(arg.lower() in data.keys()):
			Googlify.Santafy(Googlify.ImageFromURL(data[arg.lower()]['image'])).save('tempSanta.png')
			await ctx.send(file=discord.File('tempSanta.png'))
		else:
			await ctx.send('Character not found:```{}```'.format(arg.lower()))

@bot.command()
@commands.check(check_if_october)
async def spookify(ctx, *, arg=''):
	if(arg == ''):
		Googlify.Spookify(Googlify.ImageFromURL(str(ctx.author.avatar))).save('tempSpooky.png')
		await ctx.send(file=discord.File('tempSpooky.png'))
	elif(len(ctx.message.mentions) > 0):
		Googlify.Spookify(Googlify.ImageFromURL(str(ctx.message.mentions[0].avatar))).save('tempSpooky.png')
		await ctx.send(file=discord.File('tempSpooky.png'))
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(arg.lower() in data.keys()):
			Googlify.Spookify(Googlify.ImageFromURL(data[arg.lower()]['image'])).save('tempSpooky.png')
			await ctx.send(file=discord.File('tempSpooky.png'))
		else:
			await ctx.send('Character not found:```{}```'.format(arg.lower()))

@bot.command()
@commands.check(check_if_december)
async def santafly(ctx, *, arg=''):
	if(arg == ''):
		Googlify.Santafy(Googlify.ImageFromURL(str(ctx.author.avatar)), rand=True).save('tempSanta.png')
		await ctx.send(file=discord.File('tempSanta.png'))
	elif(len(ctx.message.mentions) > 0):
		Googlify.Santafy(Googlify.ImageFromURL(str(ctx.message.mentions[0].avatar)), rand=True).save('tempSanta.png')
		await ctx.send(file=discord.File('tempSanta.png'))
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(arg.lower() in data.keys()):
			Googlify.Santafy(Googlify.ImageFromURL(data[arg.lower()]['image']), rand=True).save('tempSanta.png')
			await ctx.send(file=discord.File('tempSanta.png'))
		else:
			await ctx.send('Character not found:```{}```'.format(arg.lower()))

@bot.command(name='2019ify')
@commands.check(check_if_december)
async def Happy2019(ctx, *, arg=''):
	if(arg == ''):
		Googlify.Happy2019(Googlify.ImageFromURL(str(ctx.author.avatar))).save('temp2019.png')
		await ctx.send(file=discord.File('temp2019.png'))
	elif(len(ctx.message.mentions) > 0):
		Googlify.Happy2019(Googlify.ImageFromURL(str(ctx.message.mentions[0].avatar))).save('temp2019.png')
		await ctx.send(file=discord.File('temp2019.png'))
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(arg.lower() in data.keys()):
			Googlify.Happy2019(Googlify.ImageFromURL(data[arg.lower()]['image'])).save('temp2019.png')
			await ctx.send(file=discord.File('temp2019.png'))
		else:
			await ctx.send('Character not found:```{}```'.format(arg.lower()))

@bot.command()
@commands.check(check_if_february)
async def valentines(ctx, fromChar='', toChar=''):
	""">valentines "character 1" "character 2" for a cheesy MS Paint Valentine's card.
	   Character names need to be enclosed in "quotation marks" """
	if(fromChar == '' or toChar == ''):
		ctx.send("I need to know who's sending a valentines to whom, silly!")
	else:
		with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
			data = json.load(json_data)
		if(fromChar.lower() not in data.keys()):
			await ctx.send('Character not found:```{}```'.format(fromChar.lower()))
		elif(toChar.lower() not in data.keys()):
			await ctx.send('Character not found:```{}```'.format(toChar.lower()))
		else:
			fromImage = Googlify.ImageFromURL(data[fromChar.lower()]['image'])
			toImage = Googlify.ImageFromURL(data[toChar.lower()]['image'])
			valentine_generator.MakeImage(fromImage, toImage).save('tempValentine.png')
			await ctx.send(file=discord.File('tempValentine.png'))

@bot.command()
#@commands.check(check_if_bot_spam)
async def rps(ctx):
	'''Mention someone with @<username> to challenge them to a rousing bout of rock-paper-scissors.
	   Check your DMs and respond with an emoji to play the game. The winner will be announced publicly.'''
	if(len(ctx.message.mentions) > 0):
		bot.rpsGames.sort(key=lambda x: x.valid, reverse=True)
		while(False in [game.valid for game in bot.rpsGames]):
			bot.rpsGames.pop()

		if(ctx.message.mentions[0].dm_channel == None):
			await ctx.message.mentions[0].create_dm()
		if(ctx.author.dm_channel == None):
			await ctx.author.create_dm()
		bot.rpsGames.append(RockPaperScissors.Game(ctx.message, ctx.author, ctx.message.mentions[0]))
		await bot.rpsGames[-1].Send()

@bot.command()
@commands.check(check_if_october)
async def tot(ctx):
	'''Mention someone with @<username> to challenge them to a rousing bout of trick or treat.
	   Check your DMs and respond with an emoji. The result will be announced publicly.'''
	if(len(ctx.message.mentions) > 0):
		bot.totGames.sort(key=lambda x: x.valid, reverse=True)
		while(False in [game.valid for game in bot.rpsGames]):
			bot.rpsGames.pop()
		if(ctx.message.mentions[0].dm_channel == None):
			await ctx.message.mentions[0].create_dm()
		if(ctx.author.dm_channel == None):
			await ctx.author.create_dm()
		bot.totGames.append(TrickOrTreat.Game(ctx.message, ctx.author, ctx.message.mentions[0]))
		await bot.totGames[-1].Send()

@bot.command(name='hmk')
#@commands.check(check_if_bot_spam)
async def hugmarrykill(ctx, *, arg=''):
	'''Mention someone with @<username> to begin a hug-marry-kill game.
	   Use >hmk with no arguments to show the scores for all characters.
	   Use >hmk <charname> to show the scores for a particular character.'''
	# Start a game if someone is mentioned
	if(len(ctx.message.mentions) > 0):
		# Sort games by validity, so invalid games are at the end of the list
		bot.hmkGames.sort(key = lambda x: x.valid, reverse=True)
		# Remove all invalid games. Games are invalid if they failed to start or ended.
		while(False in [game.valid for game in bot.hmkGames]):
			bot.hmkGames.pop()
		# Initialize a new game
		bot.hmkGames.append(hmk.Game(ctx.message, ctx.author, ctx.message.mentions[0], ctx.guild.id, servers[str(ctx.guild.id)]))
		await bot.hmkGames[-1].Send()
	# Search for the scores of a character
	elif(arg != ''):
		name = arg.lower()
		# Check if the server is valid
		if(str(ctx.guild.id) in servers):
			# Fetch character data
			with open('servers/{}/data.json'.format(ctx.guild.id)) as json_data:
				data = json.load(json_data)
			# Fetch hmk score data
			with open('servers/{}/hmk_scores.json'.format(ctx.guild.id)) as json_data:
				hmkdata = json.load(json_data)
			# Check if the character is valid
			if(name in data.keys()):
				characterInfo = data[name]
				# Check if the character has scores. If so, send their scores.
				if(name in hmkdata.keys()):
					output = hmk.HMKEmbed(name.title(), characterInfo, hmkdata[name], servers[str(ctx.guild.id)])
				# If the character has no hmk scores, give them 0 in each category.
				else:
					output = hmk.HMKEmbed(name.title(), characterInfo, {'hug': 0, 'marry': 0, 'kill': 0}, servers[str(ctx.guild.id)])
				await ctx.send(embed=output)
			else:
				output = 'Invalid character!\n```{}```'.format(name)
				await ctx.send(output)
	# Show all scores with an interactable embed.
	else:
		bot.hmkScoreMessages[ctx.author] = hmk.ScoreMessage(ctx.author, ctx, servers)
		await bot.hmkScoreMessages[ctx.author].Send(ctx.channel)
		await bot.hmkScoreMessages[ctx.author].ListNames()

@bot.command()
#@commands.check(check_if_bot_spam)
async def pet(ctx):
	'''Pet the bot. It is a good bot.
	Shoutouts to my friend Haruka for implementing this in a different bot, which I stole it from.'''
	responses = ['woof', 'bwoof', 'bark', 'bork', 'arf']
	bot.petCounter += 1
	await bot.change_presence(activity=discord.Game("with {} pets today.".format(bot.petCounter)))
	await ctx.send('{}'.format(random.choice(responses)))
@bot.command()
#@commands.check(check_if_bot_spam)
async def bulba(ctx):
	'''Show a v good bulba'''
	bulbaDirectory = './Bulbas/'
	bulbaFile = random.choice(os.listdir(bulbaDirectory))
	await ctx.send(file=discord.File(bulbaDirectory+bulbaFile))
#@bot.command(name='boons')
#@commands.check(check_if_staff_or_test)
#async def boonslist(ctx, number=10, minEX=1, minS=1):
#async def boonslist(ctx, *args):
#	if(len(args) > 0):
#		number= args[0]
#	minEX = 1
#	minS = 1
#	if(len(args) > 1):
#		names = args[1:]
#	batch = boons.BoonBatch(number, minEX, minS)
#	embeds = []
#	for boon in range(len(batch)):
#		if(boon < len(names)):
#			embeds.append(boons.BoonEmbed(batch[boon], names[boon]))
#		else:
#			embeds.append(boons.BoonEmbed(batch[boon]))
#	#embeds = [boons.BoonEmbed(batch[boon], names[boon]) for boon in range(len(batch))]
#	for embed in embeds:
#		await ctx.send(embed=embed)

@bot.command(name='boons')
async def boonslist(ctx, *, arg=''):
	args = arg.split('\n')
	if(len(args) > 0):
		number = len(args)
	else:
		number = 10
	minEX = 1
	minS = 1
	if(len(args) > 0):
		names = args
	else:
		names = []
	batch = boons.BoonBatch(number, minEX, minS)
	embeds = []
	for boon in range(len(batch)):
		if(boon < len(names)):
			embeds.append(boons.BoonEmbed(batch[boon], names[boon]))
		else:
			embeds.append(boons.BoonEmbed(batch[boon]))
	for embed in embeds:
		await ctx.send(embed=embed)

@bot.command(name='roll')
async def rolldie(ctx, *, arg=''):
	await ctx.send(roll.roll(arg))

@bot.command()
async def remind(ctx, *, arg=''):
	starting_time = datetime.datetime.utcnow()
	scheduler = aioscheduler.TimedScheduler()
	scheduler.start()
	scheduler.schedule(ctx.send('{}: {}'.format(ctx.author.mention, ctx.message.jump_url)), starting_time+datetime.timedelta(days=int(arg)))

@tasks.loop(hours=1)
async def RemindStartOfMonth():
	channel = bot.get_channel(880561729308868608)
	if(channel and datetime.datetime.now().day == 1 and not bot.monthCheck):
		await channel.send('{} do monthly stuff!'.format(bot.get_guild(880560673304768582).get_role(880560940905533460).mention))
		#await channel.send('do monthly stuff!')
		bot.monthCheck = True
	elif(datetime.datetime.now().day != 1):
		bot.monthCheck = False

@tasks.loop(hours=24)
async def ResetPetCounter():
	bot.petCounter = 0
	await bot.change_presence(activity=discord.Game("with {} pets today.".format(bot.petCounter)))

@ResetPetCounter.before_loop
async def before_ResetPetCounter():
	now = datetime.datetime.utcnow()
	later = now.replace(hour=4,minute=0,second=0)
	if(later < now):
		later += datetime.timedelta(days=1)
	#await asyncio.sleep_until(later)
	await discord.utils.sleep_until(later)

@bot.event
async def on_raw_reaction_add(payload):
	if(payload.member != bot.user):
		for roleMsg in bot.roleMessages:
			if(bot.roleMessages[roleMsg].message.id == payload.message_id):
				await bot.roleMessages[roleMsg].SetRole(str(payload.emoji), payload.member)
@bot.event
async def on_reaction_add(reaction, user):
	if(user != bot.user):
		for rpsGame in bot.rpsGames:
			if(rpsGame.valid):
				if(reaction.message.id == rpsGame.challengerMessage.id and user == rpsGame.challenger):
					await rpsGame.UpdateChallengerResponse(reaction)
				elif(reaction.message.id == rpsGame.targetMessage.id and user == rpsGame.target):
					await rpsGame.UpdateTargetResponse(reaction)
		for totGame in bot.totGames:
			if(totGame.valid):
				if(reaction.message.id == totGame.targetMessage.id and user == totGame.target):
					await totGame.UpdateTargetResponse(reaction)
		for hmkGame in bot.hmkGames:
			if(hmkGame.valid):
				if(reaction.message.id == hmkGame.targetMessage.id and user == hmkGame.target):
					if(str(reaction) == str(hmk.arrowLeft)):
						await hmkGame.Back()
					elif(str(reaction) == str(hmk.arrowRight)):
						await hmkGame.Advance()
					elif(str(reaction) == str(hmk.listEmoji)):
						await hmkGame.ListNames()
					else:
						await hmkGame.RegisterAnswer(reaction.emoji)
		for deity in bot.factionMessages:
			if(bot.factionMessages[deity] != None):
				if(bot.factionMessages[deity].message.id == reaction.message.id and bot.factionMessages[deity].user == user):
					if(str(reaction) == str(DeityMessage.arrowLeft)):
						await bot.factionMessages[deity].Back()
					elif(str(reaction) == str(DeityMessage.arrowRight)):
						await bot.factionMessages[deity].Advance()
					elif(str(reaction) == str(DeityMessage.listEmoji)):
						await bot.factionMessages[deity].ListNames()
		for canon in bot.canonMessages:
			if(bot.canonMessages[canon] != None):
				if(bot.canonMessages[canon].message.id == reaction.message.id and bot.canonMessages[canon].user == user):
					if(str(reaction) == str(CanonList.arrowLeft)):
						await bot.canonMessages[canon].Back()
					elif(str(reaction) == str(CanonList.arrowRight)):
						await bot.canonMessages[canon].Advance()
					elif(str(reaction) == str(CanonList.listEmoji)):
						await bot.canonMessages[canon].ListNames()
		for ooc in bot.oocMessages:
			if(bot.oocMessages[ooc] != None):
				if(bot.oocMessages[ooc].message.id == reaction.message.id and bot.oocMessages[ooc].user == user):
					if(str(reaction) == str(OocMessage.arrowLeft)):
						await bot.oocMessages[ooc].Back()
					elif(str(reaction) == str(OocMessage.arrowRight)):
						await bot.oocMessages[ooc].Advance()
					elif(str(reaction) == str(OocMessage.listEmoji)):
						await bot.oocMessages[ooc].ListNames()
		for hmkScore in bot.hmkScoreMessages:
			if(bot.hmkScoreMessages[hmkScore] != None):
				if(bot.hmkScoreMessages[hmkScore].message.id == reaction.message.id and bot.hmkScoreMessages[hmkScore].user == user):
					if(str(reaction) == str(hmk.arrowLeft)):
						await bot.hmkScoreMessages[hmkScore].Back()
					if(str(reaction) == str(hmk.arrowRight)):
						await bot.hmkScoreMessages[hmkScore].Advance()
					if(str(reaction) == str(hmk.listEmoji)):
						await bot.hmkScoreMessages[hmkScore].ListNames()
					if(str(reaction) == str(hmk.hEmoji)):
						await bot.hmkScoreMessages[hmkScore].Sort(str(reaction))
					if(str(reaction) == str(hmk.mEmoji)):
						await bot.hmkScoreMessages[hmkScore].Sort(str(reaction))
					if(str(reaction) == str(hmk.kEmoji)):
						await bot.hmkScoreMessages[hmkScore].Sort(str(reaction))
		#for roleMsg in bot.roleMessages:
		#	if(bot.roleMessages[roleMsg].message.id == reaction.message.id):
		#		await bot.roleMessages[roleMsg].SetRole(str(reaction), user)

if(__name__ == '__main__'):
	ResetPetCounter.start()
	RemindStartOfMonth.start()
	bot.run(TOKEN)


from EstruturasSimplificadas import *

def exerc2(nome_arq = 'in2.txt'):
   # Ler as primeiras 50 linhas de uma entrada e então escrevê-las na ordem
   # reversa. Ler as próximas 50 linhas e então escrevê-las em ordem reversa.
   # Fazer isso até que não existam mais linhas a serem lidas, neste ponto as
   # linhas restantes devem ser impressas em ordem reversa.
   # Em outras palavras, sua saída vai começar com a linha de número 50,
   # então a 49, 48 e assim por diante até a primeira linha. Isso será seguido
   # pela linha de número 100, seguida pela 99 98 até a linha 51, e assim por diante.
   # Seu código nunca deverá ter armazenado mais de 50 linhas.

    try:
        arq = open(nome_arq, "r" ,encoding="utf-8")
    except IOError:
        print("Erro ao abrir arquivo de entrada.")
        return

    sizeFile = len(arq.readlines())
    sizeAtual = sizeFile
    pilha = Pilha()

    arq.seek(0,0)
    for i in range(sizeFile):
        pilha.push(arq.readline())
        sizeAtual -= 1

        if(pilha.size() == 50 or sizeAtual == 0):
            for i in range(50):
                print(pilha.pop())

    arq.close()

if __name__ == "__main__":
    exerc2()


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

import threading
import pygame
import scipy as sc
import numpy

class BaseGUI(threading.Thread):
	#DEFAULT_FONT = "Noto Mono"

	def __init__(self, states, shutdown, fullscreen):
		super().__init__()
		size = (800, 480)

		self.states = states
		self.shutdown = shutdown
		self.fullscreen = fullscreen

		if fullscreen:
			self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
			self.set_mouse_visible(False)
		else:
			self.screen = pygame.display.set_mode(size)
			self.set_mouse_visible(True)

		# Set header (useful for testing, not so much for full screen mode!)
		pygame.display.set_caption("Curtis Controller Instrument Cluster")

		# Stop keys repeating (not so necessary for this script, but useful if you want to capture other key presses)
		pygame.key.set_repeat()

		pygame.init()
		pygame.mixer.quit()

	def toggle_mouse_visible(self):
		self.mouse_visible = not self.mouse_visible
		pygame.mouse.set_visible(self.mouse_visible)

	def set_mouse_visible(self, visible):
		self.mouse_visible = visible
		pygame.mouse.set_visible(self.mouse_visible)

	@staticmethod
	def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True):
		"""fill a surface with a gradient pattern
		Parameters:
		color -> starting color
		gradient -> final color
		rect -> area to fill; default is surface's rect
		vertical -> True=vertical; False=horizontal
		forward -> True=forward; False=reverse

		Pygame recipe: http://www.pygame.org/wiki/GradientCode
		"""
		if rect is None:
			rect = surface.get_rect()

		x1, x2 = rect.left, rect.right
		y1, y2 = rect.top, rect.bottom

		if vertical:
			h = y2 - y1
		else:
			h = x2 - x1
		if forward:
			a, b = color, gradient
		else:
			b, a = color, gradient

		rate = (
			float(b[0] - a[0]) / h,
			float(b[1] - a[1]) / h,
			float(b[2] - a[2]) / h
		)

		fn_line = pygame.draw.line

		if vertical:
			for line in range(y1, y2):
				color = (
					min(max(a[0] + (rate[0] * (line - y1)), 0), 255),
					min(max(a[1] + (rate[1] * (line - y1)), 0), 255),
					min(max(a[2] + (rate[2] * (line - y1)), 0), 255)
				)
				fn_line(surface, color, (x1, line), (x2, line))
		else:
			for col in range(x1, x2):
				color = (
					min(max(a[0] + (rate[0] * (col - x1)), 0), 255),
					min(max(a[1] + (rate[1] * (col - x1)), 0), 255),
					min(max(a[2] + (rate[2] * (col - x1)), 0), 255)
				)
				fn_line(surface, color, (col, y1), (col, y2))

	@staticmethod
	def draw_text(scr, text, size, pos, font, color=(255, 255, 255), topright=False):

		tfont = pygame.font.SysFont(font, size)
		#tfont = pygame.freetype.Font(font, size)
		#tfont.kerning = True
		text_bitmap = tfont.render(text, 1, color)
		if topright:
			rect = text_bitmap.get_rect()
			rect.topright = pos
			pos = rect

		scr.blit(text_bitmap, pos)

	@staticmethod
	def draw_shadow_text(scr, text, size, pos, font, color=(255, 255, 255), topright=False):
		tfont = pygame.font.SysFont(font, size)

		drop_color = (70, 70, 70)
		dropshadow_offset = size // 20

		text_bitmap = tfont.render(text, True, drop_color)
		if topright:
			rect = text_bitmap.get_rect()
			rect.topright = pos
			pos = rect

		scr.blit(text_bitmap, (pos[0] + dropshadow_offset, pos[1] + dropshadow_offset))

		text_bitmap = tfont.render(text, 1, color)
		scr.blit(text_bitmap, pos)

	@staticmethod
	def rotate(points: numpy.core.multiarray, center: numpy.core.multiarray, radians: float) -> numpy.core.multiarray:
		return sc.dot(points - center, sc.array([[sc.cos(radians), sc.sin(radians)], [-sc.sin(radians), sc.cos(radians)]])) + center


import csv

titulo = input("Digite um nome de filme: ").strip().upper()

with open("nomes.csv", "r") as arquivo:
    leitor = csv.DictReader(arquivo)

    contador = 0

    for row in leitor:
        if row["Nomes"].strip().upper() == titulo:
            contador += 1

print(contador)


from qgis.PyQt.QtCore import pyqtSignal, Qt
from qgis.PyQt.QtGui import QCursor, QPixmap
from qgis.core import Qgis, QgsGeometry, QgsWkbTypes
from qgis.gui import QgsMapTool, QgsRubberBand, QgsVertexMarker

class LineTool(QgsMapTool):
    """
    A basic point tool that can be connected to actions in order to handle
    point based actions.
    """

    geometryComplete = pyqtSignal(object)
    locationChanged = pyqtSignal(object)

    def __init__(self, canvas):
        super(LineTool, self).__init__(canvas)
        self.m1 = None
        self.m2 = None
        self.p1 = None
        self.p2 = None

        self.band = QgsRubberBand(canvas, QgsWkbTypes.LineGeometry)
        self.band.setWidth(3)
        self.band.setColor(Qt.red)
        self.cursor = QCursor(
            QPixmap(
                [
                    "16 16 3 1",
                    "      c None",
                    ".     c #FF0000",
                    "+     c #FFFFFF",
                    "                ",
                    "       +.+      ",
                    "      ++.++     ",
                    "     +.....+    ",
                    "    +.     .+   ",
                    "   +.   .   .+  ",
                    "  +.    .    .+ ",
                    " ++.    .    .++",
                    " ... ...+... ...",
                    " ++.    .    .++",
                    "  +.    .    .+ ",
                    "   +.   .   .+  ",
                    "   ++.     .+   ",
                    "    ++.....+    ",
                    "      ++.++     ",
                    "       +.+      ",
                ]
            )
        )

    def canvasReleaseEvent(self, event):
        if self.m2 and self.m1:
            self.reset()

        point = self.snappoint(event.pos())

        if not self.m1:
            self.m1 = QgsVertexMarker(self.canvas())
            self.m1.setIconType(1)
            self.m1.setColor(Qt.blue)
            self.m1.setIconSize(6)
            self.m1.setPenWidth(3)
            self.m1.setCenter(point)
            self.p1 = point
            return

        if not self.m2:
            self.m2 = QgsVertexMarker(self.canvas())
            self.m2.setIconType(1)
            self.m2.setColor(Qt.red)
            self.m2.setIconSize(6)
            self.m2.setPenWidth(3)
            self.m2.setCenter(point)
            self.p2 = point

        if self.m2 and self.m1:
            geom = QgsGeometry.fromPolylineXY([self.p1, self.p2])
            self.band.setToGeometry(geom, None)
            self.geometryComplete.emit(geom)

    def canvasMoveEvent(self, event):
        point = self.snappoint(event.pos())
        self.locationChanged.emit(point)

    def snappoint(self, point):
        utils = self.canvas().snappingUtils()
        match = utils.snapToMap(point)
        if match.isValid():
            return match.point()
        else:
            return self.canvas().getCoordinateTransform().toMapCoordinates(point)

    def activate(self):
        self.canvas().setCursor(self.cursor)
        self.reset()

    def deactivate(self):
        """
        Deactivate the tool.
        """
        pass

    def reset(self):
        self.band.reset()
        self.canvas().scene().removeItem(self.m1)
        self.canvas().scene().removeItem(self.m2)
        self.m1 = None
        self.m2 = None
        self.p1 = None
        self.p2 = None


#!/usr/bin/env python
# 第 0006 题：你有一个目录，放了你一个月的日记，都是 txt，
# 为了避免分词的问题，假设内容都是英文，请统计出你认为每篇日记最重要的词。
# coding:utf-8
import re
import glob
from collections import Counter

def get_word_num(txt_path):
    path = '%s/*.txt' % txt_path
    # 忽视的词的标准不好判断
    stop_word = (['the', 'in', 'of', 'and', 'to', 'has', 'that', 'this', 's',
                 'is', 'are', 'a', 'with', 'as', 'an', 'i', 'his', 'it', 'he',
                  'she', 'you', 'for', 'was', 'have', 'from', 'had', 'my',
                  'at', 'upon', 'but', 'which', 'not', 'be', 'by', 'their',
                  'him', 'sir', 'there', 'who', 'they', 'said', 'on',
                  'so', 'them', 'all', 'we', 'were'])
    for files in glob.glob(path):
        f = open(files, 'r')
        content = f.read().lower()
        pattern = '[a-z0-9\']+'
        words = re.findall(pattern, content)
        wordList = Counter(words)
        for i in stop_word:
            if i in wordList:
                wordList[i] = 0
        f.close()
        # print(wordList.most_common())
        return wordList.most_common()[0]

if __name__ == '__main__':
    txt_path = 'G:\code\python\dailyCode\\0006'
    result = get_word_num(txt_path)
    print(result)


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

'''
融合方式： 加权平均
权值计算：按照各个品牌的线下误差，作误差倒数的归一化加权
        其中yuna_predict的brand5数据不沿用，yuna_predict的brand8数据权重人为减小
后期处理：对节假日预测偏低的数据人为改动
结果： B榜（37048）

'''

import pandas as pd
from pandas import Series, DataFrame
import numpy as np
from scipy.stats import mode
import csv
import matplotlib.dates
import matplotlib.pyplot as plt
from datetime import *
import urllib, urllib.parse, urllib.request
import json

from sklearn.preprocessing import *
from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib

# 导入数据
def importDf(url, sep='\t', header='infer', index_col=None):
    df = pd.read_csv(url, sep=sep, header=header, index_col=index_col)
    return df

# 标记周数
def tickWeek(df, start):
    preVal = df[:-1]['day_of_week'].values
    preVal = np.insert(preVal, 0, preVal[0]-1)
    df['new_week'] = (preVal >= df.day_of_week)
    weekList = list()
    week = start
    for item in df['new_week']:
        week += (1 if item else 0)
        weekList.append(week)
    df['week'] = weekList
    return df

# 给数据添加日期字段
def addGuessDate(df, startDate):
    if isinstance(startDate, str):
        startDate = datetime.strptime(startDate, '%Y-%m-%d')
    df['guess_date'] = df['week']*7 + df['day_of_week']
    df['guess_date'] = df['guess_date'].map(lambda x: startDate + timedelta(days=x))
    df['year'] = df['guess_date'].map(lambda x: x.year)
    df['month'] = df['guess_date'].map(lambda x: x.month)
    df['day'] = df['guess_date'].map(lambda x: x.day)
    df['day_of_year'] = df['guess_date'].map(lambda x: (x.date() - date(x.year,1,1)).days)
    df['month_day'] = df['guess_date'].map(lambda x: x.month*100+x.day)
    df['guess_date'] = pd.to_datetime(df['guess_date'])
    return df

# 请求第三方接口获取日期休假情况(date字符串格式为YYYYMMDD)
# @param dateList: 日期格式为字符串YYYYMMDD
# @return: 返回结果：0：工作日，1：休息日，2：节假日
def checkHoliday(dateList):
    if not isinstance(dateList[0], str):
        dateList = [dt.strftime('%Y%m%d') for dt in dateList]
    url = "http://tool.bitefu.net/jiari/"
    data = urllib.parse.urlencode({'d':','.join(dateList)})
    res = urllib.request.urlopen(url, data.encode()).read()
    res = json.loads(res.decode('utf-8'))
    # 订正第三方接口返回值数值型与字符串型不统一的bug
    for k,v in res.items():
        res[k] = int(v)
    return res

# 添加节假日标记字段
def addHoliday(df):
    dateList = pd.to_datetime(df.guess_date)
    dateList = [dt.strftime('%Y%m%d') for dt in dateList]
    res = checkHoliday(dateList)
    df['holiday'] = list(map(lambda x: res[x], dateList))
    return df

# 特征方法汇总
def feaFactory(df, startWeek=0):
    df = tickWeek(df, startWeek)
    df = addGuessDate(df,'2012-12-30')
    df = addHoliday(df)
    return df

# 划分训练集和测试集
def trainTestSplit(df, splitN, trainLabel):
    trainX = df[:splitN][trainLabel]
    trainY = df[:splitN]['cnt']
    testX = df[splitN:][trainLabel]
    testY = df[splitN:]['cnt']
    return (trainX, trainY, testX, testY)

# 导出预测结果
def exportResult(df, fileName, header=False, index=False, sep='\t'):
    df.to_csv('./%s' % fileName, sep=sep, header=header, index=index)

# 统计预测误差
def countDeltaY(predictSeries, labelSeries, show=True, title='', subplot=None):
    deltaSeries = predictSeries - labelSeries
    if subplot!=None:
        plt.subplot(subplot[0], subplot[1], subplot[2])
    deltaSeries.plot(style='b-')
    plt.title(title)
    if show:
        plt.show()
    return deltaSeries

if __name__ == '__main__':
    # 导入数据
    dfs = []
    dfs.append(importDf('../lake/resultB3_lake_aveHoliday2_dropData.txt', header=None, index_col=[0,1]))
    dfs.append(importDf('../keng/prophet_dateProperty_B_fusai_3_7.txt', header=None, index_col=[0,1]))
    dfs.append(importDf('../xgboost1/xgboost2B.txt', header=None, index_col=[0,1]))
    for df in dfs:
        df.columns = ['predict']
        df.index.names = ['date','brand']
    df = pd.concat(dfs, axis=1, keys=['lake', 'keng', 'yuna'])
    df.columns = [x[0]+'_'+x[1] for x in df.columns]
    df.reset_index(inplace=True)
    otherDf = importDf('../linear1/linear2B_predict.csv', sep=',')
    df = pd.merge(df, otherDf[['date','brand','guess_date','day_of_week','holiday']], how='left', on=['date','brand'])
    # 按排名加权平均
    rankList = {
        1:[0.24,0.35,0.41],
        2:[0.28,0.30,0.42],
        3:[0.40,0.26,0.34],
        4:[0.28,0.36,0.36],
        5:[0.50,0.50,0.00],
        6:[0.34,0.32,0.34],
        7:[0.36,0.36,0.28],
        8:[0.35,0.42,0.23],
        9:[0.35,0.37,0.28],
        10:[0.30,0.40,0.30]
    }
    for b in range(1,11):
        df.loc[df.brand==b,'predict'] = df.loc[df.brand==b,'lake_predict']*rankList[b][0] + df.loc[df.brand==b,'keng_predict']*rankList[b][1] + df.loc[df.brand==b,'yuna_predict']*rankList[b][2]
    exit()

    modelName = 'average2B_brand'
    exportResult(df, "%s_predict.csv" % modelName, header=True, sep=',')
    exportResult(df[['date','brand','predict']], "%s_0308.txt" % modelName)


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if len(s)==1:
            return 1
        start = 0
        longest = 1
        while start+longest+1<len(s):
            pos = self.findOcurance(s[start:start+longest])
            if pos == -1:
                longest += 1
            else:
                start = start+pos+1
        return longest

    def findOcurance(self, s: str) -> int:
        for x in range(1,len(s)):
            if s.find(s[x])!=x:
                return s.find(s[x])
        return -1

print(Solution().lengthOfLongestSubstring("abcb"))


import pickle
import time
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from alexnet import AlexNet

# TODO: Load traffic signs data.
sign_data_file = './train.p'
with open(sign_data_file, mode='rb') as f:
    sign_data = pickle.load(f)

# TODO: Split data into training and validation sets.
X_train, X_valid, y_train, y_valid = train_test_split(sign_data['features'], sign_data['labels'], test_size=0.33, random_state=36)
print("Shapes of X_train, X_valid, y_train, y_valid", X_train.shape, X_valid.shape, y_train.shape, y_valid.shape)

# TODO: Define placeholders and resize operation.
#sign_names = pd.read_csv('signnames.csv')
nb_classes = 43
EPOCHS = 10
BATCH_SIZE = 128
rate = 0.001

x = tf.placeholder(tf.float32, (None, 32, 32, 3))
resized = tf.image.resize_images(x, (227, 227))
y = tf.placeholder(tf.int64, None)

# TODO: pass placeholder as first argument to `AlexNet`.
fc7 = AlexNet(resized, feature_extract=True)
# NOTE: `tf.stop_gradient` prevents the gradient from flowing backwards
# past this point, keeping the weights before and up to `fc7` frozen.
# This also makes training faster, less work to do!
fc7 = tf.stop_gradient(fc7)

# TODO: Add the final layer for traffic sign classification.
shape = (fc7.get_shape().as_list()[-1], nb_classes)  # use this shape for the weight matrix

#fc8 Fully Connected layer added by Sundar. 11/15/17
#fc(43, relu=false, name='fc8')
fc8W = tf.Variable(tf.truncated_normal(shape, stddev=1e-2))
fc8b = tf.Variable(tf.zeros(nb_classes))
logits = tf.nn.xw_plus_b(fc7, fc8W, fc8b)

#prob
#softmax(name='probs')
#probs = tf.nn.softmax(logits)

sess = tf.Session()

# TODO: Define loss, training, accuracy operations.
# HINT: Look back at your traffic signs project solution, you may
# be able to reuse some the code.
#cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation, var_list=[fc8W, fc8b])
init = tf.global_variables_initializer()

correct_prediction = tf.argmax(logits, 1)
accuracy_operation = tf.reduce_mean(tf.cast(tf.equal(correct_prediction, y), tf.float32))
#saver = tf.train.Saver()

# This function evaulates the acuuracy of Network model.

def evaluate(X_data, y_data, sess):
    num_examples = len(X_data)
    total_accuracy = 0
    total_loss = 0
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        loss, accuracy = sess.run([loss_operation, accuracy_operation], feed_dict={x: batch_x, y: batch_y})
        total_loss += (loss * len(batch_x))
        total_accuracy += (accuracy * len(batch_x))
        return total_loss/num_examples, total_accuracy / num_examples

# TODO: Train and evaluate the feature extraction model.
with tf.Session() as sess:
    sess.run(init)
    num_examples = len(X_train)

    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        t0 = time.time()
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})

        #training_accuracy = evaluate(X_train, y_train)
        validation_loss, validation_accuracy = evaluate(X_valid, y_valid, sess)
        print("EPOCH {} ...".format(i+1))
        #print("Training Accuracy = {:.3f}".format(training_accuracy))
        print("Time: %.3f seconds" % (time.time() - t0))
        print("Validation Loss = {:.3f}".format(validation_loss))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()

    #saver.save(sess, './my-model-graph')
    #print("Model saved")


import numpy as np
#import tensorflow as tf
from add_variable_scope import add_variable_scope
import unittest

NA_int32 = -(1 << 31)
# We can modify post_NA_int32 to allow for categories to include an extra NaN
# category. Just make it 0
post_NA_int32 = NA_int32

class tf:
    float32 = None

def _embedding_initializer(n_cats, n_dims, tf_float):
    "Makes embedding for a variable. Doesn't take into account missing values."
    assert n_cats > 1
    fmt_str = "{{:0{:d}b}}".format(n_dims)
    if n_dims > 1:
        initial_embeddings = np.zeros([n_cats, n_dims], dtype=tf_float.name)
        for i in range(n_cats):
            for j, c in enumerate(fmt_str.format(i)):
                if c == '1':
                    initial_embeddings[i, j] = 1.
                else:
                    initial_embeddings[i, j] = -1.
        ie = initial_embeddings
        initial_embeddings = ((ie - ie[1:].mean(axis=0, keepdims=True)) /
                              ie[1:].var(axis=0, keepdims=True))
    else:
        ie = np.arange(-(n_cats-1)/2, n_cats/2, 1.) / n_cats + 0.1
        ie = ie.astype(tf_float.name)
        initial_embeddings = ie[:, np.newaxis]
    del ie

    assert initial_embeddings.shape[0] == n_cats
    assert initial_embeddings.shape[1] == n_dims
    return initial_embeddings

def compress_categories(possible_cats):
    """Makes a possibly sparse array of categories, with all integers >1, of
    length `n`; into a dictionary that maps the first `n` natural numbers to
    these categories."""
    possible_cats.sort()
    rearrange_cats = [None]*len(possible_cats)
    i = 0
    j = 0
    while i < len(possible_cats):
        c = possible_cats[i]
        while j+1 < c and i < len(possible_cats):
            rearrange_cats[j] = possible_cats[-1]
            possible_cats = possible_cats[:-1]
            j += 1
        if i < len(possible_cats):
            rearrange_cats[j] = c
        j += 1
        i += 1
    return rearrange_cats

def dataset_dimensions_info(dataset):
    df, orig_cat_idx = dataset
    num_idx = list(filter(lambda k: df[k].dtype == np.float64, df.keys()))
    cat_idx = list(filter(lambda k: df[k].dtype == np.int32, df.keys()))
    n_dims_l = []
    n_cats_l = []
    add_columns_after = {}
    all_cat_maps = {}

    for i, k in enumerate(cat_idx.copy()):
        possible_cats = list(df[k].unique())
        if NA_int32 in possible_cats:
            possible_cats.remove(NA_int32)

        n_cats = len(possible_cats)
        if n_cats == 1:
            add_columns_after[k] = possible_cats[0]
            cat_idx.remove(k)
            continue

        cat_map = compress_categories(possible_cats)
        if k in orig_cat_idx:
            n_dims = int(np.ceil(np.log2(n_cats)))
        else:
            n_dims = 1
        all_cat_maps[k] = cat_map

        n_dims_l.append(n_dims)
        n_cats_l.append(n_cats)
    return {"num_idx": num_idx,
            "cat_idx": cat_idx,
            "n_dims_l": n_dims_l,
            "n_cats_l": n_cats_l,
            "_cat_maps": all_cat_maps,
            "_add_columns_after": add_columns_after,
            "_one_hot_cumsum": np.cumsum([0] + n_cats_l[:-1])}

@add_variable_scope(name='inputs')
def make_input_layer(dataset, weights_initializer=None,
                     embeddings_kind="many_little", cat_inputs_kind="sparse",
                     tf_float=tf.float32):
    "make categorical inputs and concatenate them with numerical inputs"
    assert embeddings_kind in ["many_little", "one_big"], """the embeddings are
        either one big summed embedding or several little embeddings
        concatenated"""
    assert cat_inputs_kind in ["sparse", "dense"]
    if embeddings_kind == "one_big":
        assert cat_inputs_kind == "dense", """one_big and sparse are
        incompatible"""
        assert weights_initializer is not None

    ret = dataset_dimensions_info(dataset)
    num_idx = ret["num_idx"]
    cat_idx = ret["cat_idx"]
    n_dims_l = ret["n_dims_l"]
    n_cats_l = ret["n_cats_l"]

    inputs_l = []
    mask_inputs_l = []

    if len(num_idx) > 0:
        ret["num_inputs"] = tf.placeholder(
            tf_float, shape=[None, len(num_idx)], name="num_ph")
        ret["num_mask_inputs"] = tf.placeholder(
            tf.bool, shape=[None, len(num_idx)], name="num_mask_ph")
        inputs_l.append(ret["num_inputs"])
        mask_inputs_l.append(ret["num_mask_inputs"])

    assert len(cat_idx) == len(n_dims_l) and len(n_dims_l) == len(n_cats_l)
    if len(cat_idx) > 0:
        if cat_inputs_kind == "sparse":
            ret["cat_inputs"] = tf.placeholder(
                tf.int32, shape=[None, len(cat_idx)], name="cat_ph")
        elif cat_inputs_kind == "dense":
            ret["cat_inputs"] = tf.placeholder(
                tf_float, shape=[None, sum(n_cats_l)], name="cat_ph")

        ret["cat_mask_inputs"] = tf.placeholder(
            tf.bool, shape=[None, len(cat_idx)], name="cat_mask_ph")

        if embeddings_kind == "one_big":
            embeddings = tf.get_variable("embeddings", dtype=tf_float,
                                         shape=[sum(n_cats_l), sum(n_dims_l)],
                                         initializer=weights_initializer(),
                                         trainable=True)
            inputs_l.append(tf.matmul(ret["cat_inputs"], embeddings,
                                      name="embed_index"))

        for i, (k, n_dims, n_cats) in enumerate(zip(cat_idx, n_dims_l, n_cats_l)):
            if embeddings_kind == "many_little":
                initial_embedding = _embedding_initializer(n_cats, n_dims,
                                                           tf_float)
                embedding = tf.get_variable(
                    k,
                    dtype=tf_float,
                    initializer=initial_embedding,
                    trainable=True)
                if cat_inputs_kind == "sparse":
                    input_slice = ret["cat_inputs"][:, i]
                    looked_up = tf.nn.embedding_lookup(embedding, input_slice)
                elif cat_inputs_kind == "dense":
                    start = ret["_one_hot_cumsum"][i]
                    end = start + n_cats
                    input_slice = ret["cat_inputs"][:, start:end]
                    looked_up = tf.matmul(input_slice, embedding, name="looked_up")
                inputs_l.append(looked_up)

            mask = tf.stack([ret["cat_mask_inputs"][:, i]] * n_dims, axis=1)
            mask_inputs_l.append(mask)

    assert len(inputs_l) > 0, "The dataframe to get inputs from is empty!"
    ret["inputs"] = tf.concat(inputs_l, axis=1)
    ret["mask_inputs"] = tf.concat(mask_inputs_l, axis=1)
    assert ret["inputs"].get_shape()[1] == ret["mask_inputs"].get_shape()[1]
    return ret

def make_one_hot(array, indices, input_layer):
    """Converts a list of category indices into a one-hot array suitable for
    inputting"""
    assert indices.shape[-1] == len(input_layer["n_dims_l"])
    array[:] = 0
    array[input_layer["_one_hot_cumsum"] + indices] = 1
    return array

def preprocess_dataframe(dataframe, input_layer):
    """Makes categories zero-based and contiguous. Removes categories with one
    value."""
    for c, m in input_layer["_cat_maps"].items():
        inv_m = dict(zip(m, range(len(m))))
        inv_m[NA_int32] = post_NA_int32
        dataframe[c] = dataframe[c].map(inv_m).astype(np.int32)

        target_list = sorted(list(range(0, len(m))))
        if post_NA_int32 in dataframe[c].unique():
            target_list.append(post_NA_int32)
            target_list.sort()
        assert sorted(dataframe[c].unique()) == target_list
    return dataframe

def postprocess_dataframe(dataframe, input_layer):
    """Restores sparse 1-based categories. Re-adds categories with one
    value."""
    for c, m in input_layer["_cat_maps"].items():
        dataframe.loc[:, c] = dataframe[c].map(m.__getitem__).astype(np.int32)
    for c, v in input_layer["_add_columns_after"].items():
        dataframe.loc[:, c] = np.int32(v)
    return dataframe

class TestCompressCategories(unittest.TestCase):
    def test_compress(self):
        possible_cats = list(range(1, 6))
        self.assertEqual(compress_categories(possible_cats),
                         list(range(1, len(possible_cats)+1)))
        possible_cats[2] = 7
        self.assertEqual(compress_categories(possible_cats), [1, 2, 7, 4, 5])
        self.assertEqual(compress_categories([2, 5, 8]), [8, 2, 5])
        self.assertEqual(compress_categories([2, 10, 11]), [11, 2, 10])

    def test_random_compress(self):
        for _ in range(100):
            n = np.random.randint(1, 31)
            cats = np.random.choice(n * 4, size=n, replace=False)
            cats += 1  # ensure they start at 1
            l = compress_categories(cats)
            self.assertEqual(set(l), set(cats))


from collections import Counter, defaultdict
import heapq
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq_cnt = Counter(nums)
        d = defaultdict(list)
        for key,val in freq_cnt.items():
            d[val].append(key)
        freq = [-i for i in list(d.keys())]
        heapq.heapify(freq)
        remain_element = k
        res = []
        while remain_element>0:
            tmp = d[-heapq.heappop(freq)]
            tmpL = len(tmp)
            if tmpL>=remain_element:
                res.extend(tmp[:remain_element])
                break
            else:
                res.extend(tmp)
                remain_element-=tmpL
        return res


# -*- coding: utf-8 -*-
"""\
This is a python package that builds Word2Vec modules from either
a set of topics or a text or PDF file
It incorporates python-goose and news-corpus-builder
ported to Python 3.x

Leidos licenses this file
to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
from setuptools import setup, find_packages

requires = [
    'pyramid',
    'pyramid_chameleon',
    'pyramid_debugtoolbar',
    'waitress',
    ]
tests_require = [
    'WebTest >= 1.3.1',  # py3 compat
    'pytest',  # includes virtualenv
    'pytest-cov',
    ]

setup(
    name='modelerserver',
    version='0.1.5',
    packages=find_packages(),
    py_modules = ['domainmodeler', 'knowledgemodeler', 'mongoaccessor'],
    include_package_data=True,
    author='dana moore',
    author_email='dana.e.moore _at_ leidos.com',
    description='Domain and Knowledge builder functions',
    url='None',
    download_url='None',
    zip_safe=False,
    keywords='corpus, nlp news,extractor,web scrapping, natural language processing'.split(','),
    license='MIT License',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        "Programming Language :: Python",
        "Framework :: Pyramid",
        'Topic :: Text Processing',
	],
    entry_points="""\
      [paste.app_factory]
      main = modelerserver:main
      """,
)


import stripe
from django.conf import settings

stripe.api_key = settings.STRIPE_SECRET_KEY

import json
from .models import *

def cookieCart(request):
    try:
        cart = json.loads(request.COOKIES['cart'])
    except:
        cart = {}

    items = []
    order = {'get_cart_items': 0, 'get_cart_total': 0, 'shipping': False}
    cartItems = order['get_cart_items']

    for i in cart:
        try:
            cartItems += cart[i]['quantity']

            product = Product.objects.get(id=i)
            total = (product.price * cart[i]['quantity'])

            order['get_cart_total'] += total
            order['get_cart_items'] += cart[i]['quantity']

            item = {
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'price': product.price,
                    'imageURL': product.imageURL,
                },
                'quantity': cart[i]['quantity'],
                'get_total': total
            }

            items.append(item)
        except:
            pass

    return {'cartItems': cartItems, 'order': order, 'items': items}

def product_sales_pipeline(product_name, product_price):
    stripe_product_obj = stripe.Product.create(name=product_name) #create product in stripe
    stripe_product_id = stripe_product_obj.id #id of stripe product created
    stripe_price_obj = stripe.Price.create(
        product = stripe_product_id,
        unit_amount = product_price,
        currency = 'inr'
    )
    base_endpoint = 'https://micro-ecom-web.onrender.com'
    success_url = f"{base_endpoint}/"
    cancel_url = f"{base_endpoint}/payments/cancelled/"

    checkout_session = stripe.checkout.Session.create(
        line_items = [
            {
                'price': stripe_price_obj.id,
                'quantity': 1,
            }
        ],
        mode = 'payment',
        success_url = success_url,
        cancel_url = cancel_url
    )
    return checkout_session.url