from config import Config
from sqlalchemy import (Column, Integer, String, Boolean, BigInteger, DECIMAL,
                        Float, Date, DateTime, ForeignKey, create_engine)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func
from flask_login import UserMixin

Base = declarative_base()

class User(Base, UserMixin):
    """Model for user accounts."""

    # Defined User Level Ranges

    CONST_LEVEL1 = 5.0
    CONST_LEVEL2 = 10.0
    CONST_LEVEL3 = 15.0
    CONST_LEVEL4 = 20.0

    # Table name
    __tablename__ = 'USER'
    # Table Columns
    userID = Column(Integer, primary_key=True)
    firstname = Column(String(255), nullable=False, unique=False)
    lastname = Column(String(255), nullable=False, unique=False)
    email = Column(String(40), unique=True, nullable=False)
    dob = Column(Date, unique=False, nullable=False)
    gender = Column(String(20), unique=False, nullable=False)
    username = Column(String(64), index=True, unique=True)
    userpass = Column(String(200), unique=False, nullable=False)
    verified = Column(Boolean, unique=False, nullable=False)
    banned = Column(Boolean, unique=False, nullable=False)
    balance = Column(DECIMAL(20, 2, asdecimal=False), unique=False,
                     nullable=False)
    overallPerc = Column(Float, unique=False, nullable=False)
    totalNumSales = Column(Integer, unique=False, nullable=False)

    def getRating(self):

        """
        Returns overall rating between 1-5 based on Users overall proft/loss
        percentage.

        Args: None

        Returns:
            A Star rating between 1-5 for the user currently
        """

        numStars = 0
        # The overall percent of a user into a defined set of ratings 1-5

        if ((self.overallPerc > 0)and(self.overallPerc <= self.CONST_LEVEL1)):
            numStars = 1
        if ((self.overallPerc > self.CONST_LEVEL1) and
                (self.overallPerc <= self.CONST_LEVEL2)):
            numStars = 2
        if ((self.overallPerc > self.CONST_LEVEL2) and
                (self.overallPerc <= self.CONST_LEVEL3)):
            numStars = 3
        if ((self.overallPerc > self.CONST_LEVEL3) and
                (self.overallPerc <= self.CONST_LEVEL4)):
            numStars = 4
        if (self.overallPerc > self.CONST_LEVEL4):
            numStars = 5
        return (numStars)

    def getStarRating(self):
        """
        Returns the name of the png file to display the correct star rating img

        Args: None

        Returns:
            Returns a png link address
        """
        returnval = ""
        numStars = self.getRating()

        if (numStars > 0):
            returnval = 'images/awards' + str(numStars)+'.png'
        return (returnval)

    def get_id(self):
        return self.userID

class Usershare(Base):
    """ Model for Usershares """
    # TODO: Consider removing this table or adding more useful info
    # Table name
    __tablename__ = "USERSHARE"
    # Table Columns
    userID = Column(Integer, ForeignKey('USER.userID'),
                    primary_key=True)
    issuerID = Column(String(3), ForeignKey('SHARE.issuerID'),
                      primary_key=True)
    profit = Column(DECIMAL(20, 2, asdecimal=False), nullable=False,
                    unique=False)
    loss = Column(DECIMAL(20, 2, asdecimal=False), nullable=False,
                  unique=False)
    quantity = Column(BigInteger, nullable=False, unique=False)

class Transaction(Base):
    """Model for Transaction"""
    # Table name
    __tablename__ = "TRANSACTION"
    # Table Columns
    transID = Column(Integer, primary_key=True)
    issuerID = Column(String(45), ForeignKey('SHARE.issuerID'),
                      primary_key=False)
    userID = Column(Integer, ForeignKey('USER.userID'), primary_key=False)
    datetime = Column(DateTime, nullable=False, unique=False)
    transtype = Column(String(1), nullable=False, unique=False)
    feeval = Column(DECIMAL(20, 2, asdecimal=False), nullable=False,
                    unique=False)
    stocktransval = Column(DECIMAL(20, 2, asdecimal=False), nullable=False,
                           unique=False)
    totaltransval = Column(DECIMAL(20, 2, asdecimal=False), nullable=False,
                           unique=False)
    quantity = Column(BigInteger, nullable=False, unique=False)
    status = Column(String(20), nullable=False)

class Share(Base):
    """Model for shares."""
    # Table name
    __tablename__ = 'SHARE'
    # Table Columns
    issuerID = Column(String(3), primary_key=True)
    fullname = Column(String(80), nullable=False, unique=False)
    shortname = Column(String(50), nullable=False, unique=True)
    abbrevname = Column(String(50), nullable=False, unique=True)
    description = Column(String(500), nullable=False, unique=False)
    industrysector = Column(String(50), nullable=True, unique=False)
    currentprice = Column(Float, nullable=False, unique=False)
    marketcapitalisation = Column(BigInteger, nullable=False, unique=False)
    sharecount = Column(BigInteger, nullable=False, unique=False)
    daychangepercent = Column(Float, nullable=False, unique=False)
    daychangeprice = Column(Float, nullable=False, unique=False)
    daypricehigh = Column(Float, nullable=False, unique=False)
    daypricelow = Column(Float, nullable=False, unique=False)
    dayvolume = Column(BigInteger, nullable=False, unique=False)

class Tips(Base):
    """Model to access database tips."""
    # Table name
    __tablename__ = 'TIPS'
    # Table Columns
    tipID = Column(Integer, primary_key=True)
    data = Column(String(100), nullable=False, unique=False)

class SharePrice(Base):
    """Model for share price record."""
    # Table name
    __tablename__ = 'SHAREPRICE'
    # Table Columns
    issuerID = Column(String(3), ForeignKey('SHARE.issuerID'),
                      primary_key=True)
    time = Column(DateTime, primary_key=True)
    price = Column(Float, nullable=False, unique=False)

class Admin(Base, UserMixin):
    """ Model for admin user """
    # Table name
    __tablename__ = 'ADMIN'
    # Table Columns
    adminID = Column(Integer, primary_key=True)
    username = Column(String(64), index=True, unique=True)
    passhash = Column(String(200), unique=False, nullable=False)

class Leaderboard(Base):
    """Model for historical user ranking and value"""
    # Table name
    __tablename__ = 'LEADERBOARD'
    # Table Columns
    userID = Column(Integer, ForeignKey('USER.userID'),
                    primary_key=True)
    recordtime = Column(DateTime, primary_key=True)
    ranking = Column(Integer, nullable=False, unique=False)
    totalvalue = Column(DECIMAL(20, 2), unique=False, nullable=False)

# Allow creation of tables by running API directly
if __name__ == "__main__":
    # Define database API
    gdb = DatabaseAPI(Config)
    # Create tables
    Base.metadata.create_all(gdb.engine)


numbers = [1, 2, 3, 4, 5]

def pow(n):
    return lambda x : x**n

numberToIndex2 = pow(2)
numberToIndex3 = pow(3)
numberToIndex4 = pow(4)

print(numberToIndex2(2))
print(numberToIndex3(2))
print(numberToIndex4(2))

# Use lambda functions when an anonymous function is required for a short period of time.
raiseToTwo = pow(2)
x = lambda v : [raiseToTwo(x) for x in v]

print(x([1, 2, 3, 4]))


import sqlite3
import shutil

from PyQt5.QtWidgets import QMainWindow
from designers.admin_add_dog_window_designer import Ui_AdminAddDogWindow
from PyQt5.QtWidgets import QFileDialog
from functions.convert_to_png import *

class AddDogWidget(QMainWindow, Ui_AdminAddDogWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("add")
        self.btn_add.clicked.connect(self.add)
        self.btn_file.clicked.connect(self.file)

    def add(self):
        try:
            con = sqlite3.connect("dog_shelter_db")
            cur = con.cursor()
            breed = self.breed_edit.text()
            gender = self.gender_edit.text()
            filename = self.filename_edit.text()

            breed_id = cur.execute("""SELECT id FROM breeds
                WHERE breed == :breed""", {'breed': breed}).fetchone()[0]

            cur.execute("""INSERT INTO
                dogs(dog_image_file_name, breed_id, gender, is_taken)
                VALUES(:filename, :breed_id, :gender, "no")
                """, {'filename': filename, 'gender': gender, 'breed_id': breed_id})

            con.commit()
            con.close()
            self.hide()
        except TypeError:
            self.lbl_error.setText("Введите породу и пол собаки")
        except sqlite3.IntegrityError:
            self.lbl_error.setText("Файл с таким именем уже существует. Возможно, "
                                   "Вы не выбрали файл с картинкой")

    def file(self):
        filename = self.filename_edit.text()
        open(f"images\{filename}.png", "x")  # создание нового файла в images
        inp_file_name = QFileDialog.getOpenFileName(self, 'Выбрать картинку', '')[0]
        shutil.copy(inp_file_name, f"images\{filename}.png")  # перенос файла в images
        convert_to_png(filename)  # конвертирование файла с картинкой в png


"""Protocol for chat server - Computação Distribuida Assignment 1."""
import json
from datetime import datetime
from socket import socket

class Message:
    """Message Type."""

    def __init__(self,command):
        self.command = command

class JoinMessage(Message):
    """Message to join a chat channel."""
    def __init__(self,channel):
        super().__init__("join")
        self.channel = channel
        self.data = {"command": "join", "channel": self.channel}

    def __dict__(self):
        return self.data

    def __str__(self):
        return json.dumps(self.data)

class RegisterMessage(Message):
    """Message to register username in the server."""
    def __init__(self,username):
        super().__init__("register")
        self.username = username
        self.data = {"command": "register", "user": self.username}

    def __dict__(self):
        return self.data

    def __str__(self):
        return json.dumps(self.data)

class TextMessage(Message):
    """Message to chat with other clients."""
    def __init__(self, message, channel, timestamp):
        super().__init__("message")
        self.message = message
        self.timestamp = timestamp
        if channel != None:
            self.channel = channel
            self.data = {"command": "message","message": self.message,"channel": self.channel, "ts": self.timestamp}
        else:
            self.data = {"command": "message","message": self.message, "ts": self.timestamp}

    def __dict__(self):
        return self.data

    def __str__(self):
        return json.dumps(self.data)

class CDProto:
    """Computação Distribuida Protocol."""

    @classmethod
    def register(cls, username: str) -> RegisterMessage:
        """Creates a RegisterMessage object."""
        msg = RegisterMessage(username)
        return msg.__str__()

    @classmethod
    def join(cls, channel: str) -> JoinMessage:
        """Creates a JoinMessage object."""
        msg = JoinMessage(channel)
        return msg.__str__()

    @classmethod
    def message(cls, message: str, channel: str = None) -> TextMessage:
        """Creates a TextMessage object."""
        now = datetime.now()
        epoch = datetime.utcfromtimestamp(0)
        seconds_since_epoch = (now - epoch).total_seconds()
        unix_timestamp = int(seconds_since_epoch)
        msg = TextMessage(message, channel, unix_timestamp)
        return msg.__str__()

    @classmethod
    def send_msg(cls, connection: socket, msg: Message):
        """Sends through a connection a Message object."""
        msg_size = len(str(msg).encode())
        msg_size = msg_size.to_bytes(length = 2,byteorder = "big")
        connection.send(msg_size)
        connection.send(str(msg).encode())

    @classmethod
    def recv_msg(cls, connection: socket) -> Message:
        """Receives through a connection a Message object."""
        try :
            msg_size = int.from_bytes(connection.recv(2), "big")
            raw_msg = connection.recv(msg_size)
            if raw_msg != b'':
                decoded_msg = raw_msg.decode()
                json_msg = json.loads(decoded_msg)
                command = json_msg.get("command")
                if command == "register":
                    return RegisterMessage(json_msg["user"])
                elif command == "join":
                    return JoinMessage(json_msg["channel"])
                elif command == "message":
                    if json_msg.get("channel") == None:
                        return TextMessage(json_msg["message"], None, json_msg["ts"])
                    else:
                        return TextMessage(json_msg["message"], json_msg["channel"], json_msg["ts"])
        except json.decoder.JSONDecodeError:
            raise CDProtoBadFormat(raw_msg)

class CDProtoBadFormat(Exception):
    """Exception when source message is not CDProto."""

    def __init__(self, original_msg: bytes=None) :
        """Store original message that triggered exception."""
        self._original = original_msg

    @property
    def original_msg(self) -> str:
        """Retrieve original message as a string."""
        return self.original_msg.decode()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 10:38:30 2019

@author: charitha
"""

def convert_source(x, result_file_type):
    if result_file_type == 'old':
        x = x.replace('new_segments', 'New Segments')
        x = x.replace('remarketing', 'Remarketing')

    if result_file_type == 'new':
        x = x.replace( 'New Segments','new_segments')
        x = x.replace('Remarketing','remarketing')

    return x

def convert_metric(x, result_file_type):
    if result_file_type == 'old':
        x = x.replace('transactions', 'Transactions')
        x = x.replace('users', 'Users')
        x = x.replace('conversion_rate', 'Conversion Rate')
        x = x.replace('bounce_rate', 'Bounce Rate')
        x = x.replace('average_order_value', 'Avg. Order Value')

    if result_file_type == 'new':
        x = x.replace('Transactions', 'transactions',)
        x = x.replace('Users', 'users')
        x = x.replace('Conversion Rate','conversion_rate')
        x = x.replace('Bounce Rate', 'bounce_rate')
        x = x.replace('Avg. Order Value', 'average_order_value')

    return x

def old_to_new(data_frame):
    data_frame = data_frame.rename(columns = {'customerName':'client_id',
                                              'metric':'metric',
                                              'type':'type',
                                              'source':'source',
                                              'siteAudienceSize':'site_audience_size',
                                              'avgMetric':'avg_metric',
                                              'propertyTitle':'property_title',
                                              'transactionType':'transaction_type',
                                              'backendName':'backend_name',
                                              'interfaceName':'interface_name',
                                              'properties.0':'properties',
                                              'segmentAudienceSize':'segment_audience_size',
                                              'transaction':'transaction',
                                              'audienceMetric':'audience_metric'})
    result_file_type = 'new'
    data_frame[['source']] = data_frame[['source']].apply(lambda x: convert_source(x, result_file_type))
    data_frame[['metric']] = data_frame[['metric']].apply(lambda x: convert_metric(x, result_file_type))

    return data_frame

def new_to_old(data_frame):

    data_frame = data_frame.rename(columns = {'client_id':'customerName',
                                              'metric':'metric',
                                              'type':'type',
                                              'source':'source',
                                              'site_audience_size':'siteAudienceSize',
                                              'avg_metric':'avgMetric',
                                              'property_title':'propertyTitle',
                                              'transaction_type':'transactionType',
                                              'backend_name':'backendName',
                                              'interface_name':'interfaceName',
                                              'properties':'properties.0',
                                              'segment_audience_size':'segmentAudienceSize',
                                              'transaction':'transaction',
                                              'audience_metric':'audienceMetric'})
    result_file_type = 'old'
    data_frame[['source']] = data_frame[['source']].apply(lambda x: convert_source(x, result_file_type))
    data_frame[['metric']] = data_frame[['metric']].apply(lambda x: convert_metric(x, result_file_type))

    return data_frame


class Car:
    def __init__(self,color,mileage):
        self.color = color
        self.mileage = mileage

car_1 = Car(color= "Red", mileage = 34)
car_2 = Car(color= "Blue", mileage = 23)

for Car in (car_1,car_2):
    print(f"The car is {Car.color} and the mileage is {Car.mileage}")

toyota = car_1.color
print(toyota)

Suzuki = car_2.mileage
print(Suzuki)
print(car_2.color)
print(car_1.mileage)

class bike:
    def __init__(self,model,mileage,price):
        self.model = model
        self.mileage = mileage
        self.price = price
bike_1 = bike(model='AZ342DC', mileage=23, price=13000)
bike_2 = bike(model='DC548FE', mileage=21, price=15433)

for bike in (bike_1,bike_2):
    print(f"The number is {bike.model} and the mileage is {bike.mileage}")

if (bike.mileage >= 18):
    print('bike has good mileage')
else:
    print('no good')

print(bike_1.model)
print(bike_2.mileage)

mason = {"name": "Atharva",
        "Assignment": [34,41,33],
        "Test": [15,11,12],
        "lab": [34,41]}

print(mason['name'])
if (mason['name'] == 'Atharva'):
    print("Authorized, access granted")
else:
    print('No access, give correct ccredentials')

class Dog:
    attr1 = "mammal"
    attr2 = "dog"

    def fun(self):
        print('I am a', self.attr1)
        print('I am a', self.attr2)

Rodger = Dog()

print(Rodger.attr1)
Rodger.fun()


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def rightSideView(self, root: TreeNode) -> list[int]:
        if not root:
            return []
        queue = [root]
        ans = []
        while queue:
            q = queue
            queue = []
            ans.append(q[-1].val)
            for i in q:
                if i.left:
                    queue.append(i.left)
                if i.right:
                    queue.append(i.right)
        return ans


#!/usr/bin/python3
import requests
import json
import sys
import os
import config as cfg
from datetime import datetime, time
import calendar
import re

class RestClient:

    def __init__(self, url, API_KEY):
        self.url = url
        self.key = API_KEY

    def make_restclient(url, API_KEY):
        client = RestClient(url, API_KEY)
        client.url = url
        client.key = API_KEY
        return client

    def get_code(self):

        endpoint = "https://app.hubspot.com/oauth/authorize"
        data = {'scope': 'contacts', 'client_id': '{}'.format(
            cfg.appconfig['client_id']), 'redirect_uri': '{}'.format(cfg.appconfig['redirect_uri'])}
        headers = {}
        r = requests.get(url=endpoint, data=data, headers=headers)
        print('Response Get Code .....{}'.format(r.text))
        print(r.text)
        return r

    def refresh_token(self):
        print('Refresh Token ...')

        endpoint = "{}token".format(cfg.appconfig['api_oauth_url'])
        data = {'grant_type': 'refresh_token', 'client_id': '{}'.format(cfg.appconfig['client_id']), 'client_secret': '{}'.format(
            cfg.appconfig['client_secret']), 'refresh_token': '{}'.format(cfg.appconfig['refresh_token'])}
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'utf-8'}
        #print('Endpoint  refresh token ..... : {}'.format(endpoint))
        r = requests.post(url=endpoint, data=data, headers=headers)
        #print('Response fresh token.....{}'.format(r.text))
        resp_dict = json.loads(r.text)
    #    print('ACCESS token.....{}'.format(resp_dict['access_token']))
        return resp_dict['access_token']

    def get_token(self):
        print('Get Token ...')

        endpoint = "{}token".format(cfg.appconfig['api_oauth_url'])
        data = {'grant_type': 'authorization_code', 'client_id': '{}'.format(cfg.appconfig['client_id']), 'client_secret': '{}'.format(
            cfg.appconfig['client_secret']), 'redirect_uri': '{}'.format(cfg.appconfig['redirect_uri']), 'code': '{}'.format(cfg.appconfig['app_auth_code'])}
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'utf-8'}
        print('Endpoint  ..... : {}'.format(endpoint))
        r = requests.post(url=endpoint, data=data, headers=headers)
        print('Response .....{}'.format(r.text))
        print(r.text)
        return r

    def create_contact(self, row, access_token):
        try:
            if not row[7]:
                raise Exception(
                    "Email is empty, not able to persist in Hubspot")

            print("try to persist contact in hubspot : %s" % row[7])
            endpoint = "{}contact/createOrUpdate/email/{}".format(
                cfg.appconfig['api_url'], row[7].strip())
            #print("Endpoint : {}".format(endpoint))
            headers = {}
            headers["Content-Type"] = "application/json"
            headers["Authorization"] = "Bearer {}".format(access_token)
            dateofbirth = self.convertToTimestamp(row[12], "%d.%m.%Y")
            dateNextBooking = self.convertToTimestamp(row[24], "%d.%m.%Y")
            sepaMandatFrom = self.convertToTimestamp(row[20], "%d.%m.%Y")
            dateOfLastBooking = self.convertToTimestamp(row[22], "%d-%m-%Y")
            valueLastBooking = str(row[23])
            #print("dateNextBooking :{}" .format(dateNextBooking))
            #print("Kontaktkategorie :{}" .format(row[24]))
            #if valueLastBooking:
            #    valueLastBooking = re.findall('\d+', str(row[23]))[0]
            #print("VALUE %s" %  valueLastBooking)
            data = json.dumps({
                "properties": [
                    {
                        "property": "email",
                        "value": "%s" % row[7].strip()
                    },
                    # {
                    #  "property": "Login",
                    #  "value": "%s" % row[0]
                    # },
                    # {
                    #  "property": "Mitglied-Status",
                    #  "value": " %s " % row[1]
                    # },
                    {
                        "property": "firstname",
                        "value": "%s" % row[2]
                    },
                    {
                        "property": "lastname",
                        "value": "%s" % row[3]
                    },
                    #{
                    #    "property": "website",
                    #    "value": "http://hubspot.com"
                    #},
                    #{
                    #    "property": "company",
                    #    "value": "HubSpot"
                    #},
                    {
                        "property": "phone",
                        "value": "%s" % row[4]
                    },
                    {
                        "property": "mobilephone",
                        "value": "%s" % row[5]
                    },
                    # {
                    #  "property": "mg_nr",
                    #  "value": "%s" % row[8]
                    # },
                    {
                        "property": "address",
                        "value": "%s" % row[11]
                    },
                    {
                        "property": "date_of_birth",
                        "value": "%s" % dateofbirth
                    },
                    # {
                    #  "property": "Mehrwertsteuer",
                    #  "value": "%s" % row[13]
                    # },
                    # {
                    #  "property": "Kontoinhaber",
                    #  "value": "%s" % row[14]
                    # },
                    # {
                    #  "property": "Kontonummer",
                    #  "value": "%s" % row[15]
                    # },
                    # {
                    #  "property": "Bankleitzahl",
                    #  "value": "%s" % row[16]
                    # },
                    # {
                    #  "property": "name_der_bank",
                    #  "value": "%s" % row[17]
                    # },
                    # {
                    #  "property": "IBAN",
                    #  "value": "%s" % row[18]
                    # },
                    # {
                    #  "property": "BIC",
                    #  "value": "%s" % row[19]
                    # },
                    # {
                    #  "property": "sepa_mandat_vom",
                    #  "value": "%s" % sepaMandatFrom
                    # },
                    # {
                    #  "property": "sepa_referenz",
                    #  "value": "%s" % row[21]
                    # },
                    {
                        "property": "city",
                        "value": "%s" % row[10]
                    },
                    {
                        "property": "fax",
                        "value": "%s" % row[6]
                    },
                    #{
                    #    "property": "state",
                    #    "value": "MA"
                    #},
                    {
                        "property": "datum_der_letzten_Buchung",
                        "value": "%s" % dateOfLastBooking
                    },
                    {
                        "property": "wert_der_letzten_Buchung",
                        "value": "%s" % valueLastBooking
                    },
                    {
                        "property": "zip",
                        "value": "%s" % row[9]
                    },
                    {
                        "property": "datum_der_n_chsten_buchung",
                        "value": "%s" % dateNextBooking
                    },
                    {
                        "property": "kontaktkategorie",
                        "value": "%s" % row[25]
                    }
                ]
            })
            #print("Setting Call...")
            r = requests.post(url=endpoint, data=data, headers=headers)
            # print(r.text)
            # print(r.status_code)
            if r.status_code == 404:
                raise Exception("Api URL not available : " . endpoint)
            if r.status_code != 200:
                raise Exception(r.text)
            return row[7]
        except Exception as e:
            raise e

    def findCSV(self):
        file_names = []
        csvdir = cfg.appconfig['csvdirectory']
        for file in os.listdir(csvdir):
            if file.endswith(".csv"):
                file_names.append(os.path.join(csvdir, file))
                print(os.path.join(csvdir, file))
        return file_names

    def sendMailCorrect(self, csvfile, data):
        sendmail_location = "/usr/sbin/sendmail"  # sendmail location
        p = os.popen("%s -t" % sendmail_location, "w")
        #p.write("From: %s\n" % cfg.appconfig['email_from'])
        p.write("To: %s\n" % cfg.appconfig['email_to'])
        p.write("CC: %s\n" % ",".join(cfg.appconfig['email_cc']))
        p.write("Subject: Result of Hubspot Import CSV imported correctly {}!\n".format(csvfile))
        p.write("\n")  # blank line separating headers from body
        p.write("Processed:")
        p.write("\n")  # blank line separating headers from body
        for st in data:
            p.write(st)
            p.write("\n")  # blank line separating headers from body
        p.write("\n")  # blank line separating headers from body
        p.write(
            "File imported correctly to Hubspot and moved to processed: {} ".format(csvfile))
        status = p.close()
        if status != 0:
            print("Sendmail exit status", status)

    def sendMailError(self, csvfile, etext, data):
        sendmail_location = "/usr/sbin/sendmail"  # sendmail location
        p = os.popen("%s -t" % sendmail_location, "w")
        #p.write("From: %s\n" % cfg.appconfig['email_from'])
        p.write("To: %s\n" % cfg.appconfig['email_to'])
        p.write("CC: %s\n" % ",".join(cfg.appconfig['email_cc']))
        p.write("Subject: Result of Hubspot Import ERROR importing CSV {}!\n".format(csvfile))
        p.write("\n")  # blank line separating headers from body
        p.write("Processed:")
        p.write("\n")  # blank line separating headers from body
        for st in data:
            p.write(st)
            p.write("\n")  # blank line separating headers from body
        p.write(
            "\nFile NOT imported correctly to Hubspot and moved to erroprocessed: {} ".format(csvfile))
        p.write("\n\nError: {}".format(etext))
        status = p.close()
        if status != 0:
            print("Sendmail exit status", status)

    def convertToTimestamp(self, dateAsStr, pattern):
        pattern = "%d.%m.%Y"
        if "-" in dateAsStr:
            pattern = "%d-%m-%Y"
        if not dateAsStr:
            return dateAsStr
        if dateAsStr == '..':
            return ''
        midnightDate = datetime.combine(datetime.strptime(
            dateAsStr, pattern), datetime.min.time())
        dateutc = calendar.timegm(midnightDate.utctimetuple()) * 1000
        return dateutc


from collections import defaultdict

def is_bipartite(graph: defaultdict[int, list[int]]) -> bool:
    """
    Check whether a graph is Bipartite or not using Depth-First Search (DFS).

    A Bipartite Graph is a graph whose vertices can be divided into two independent
    sets, U and V such that every edge (u, v) either connects a vertex from
    U to V or a vertex from V to U. In other words, for every edge (u, v),
    either u belongs to U and v to V, or u belongs to V and v to U. There is
    no edge that connects vertices of the same set.

    Args:
        graph: An adjacency list representing the graph.

    Returns:
        True if there's no edge that connects vertices of the same set, False otherwise.

    Examples:
        >>> is_bipartite(
        ...     defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4], 3: [1], 4: [2]})
        ... )
        False
        >>> is_bipartite(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))
        True
    """

    def depth_first_search(node: int, color: int) -> bool:
        visited[node] = color
        return any(
            visited[neighbour] == color
            or (
                visited[neighbour] == -1
                and not depth_first_search(neighbour, 1 - color)
            )
            for neighbour in graph[node]
        )

    visited: defaultdict[int, int] = defaultdict(lambda: -1)

    return all(
        not (visited[node] == -1 and not depth_first_search(node, 0)) for node in graph
    )

if __name__ == "__main__":
    import doctest

    result = doctest.testmod()

    if result.failed:
        print(f"{result.failed} test(s) failed.")
    else:
        print("All tests passed!")


from ..date_files import DateFiles
import unittest
from unittest.mock import patch, Mock

import datetime

class DateFileMock:
    def __init__(self, field, results=[], contents=[], path=None):
        self.field = field
        self.build = Mock(side_effect=results)
        self.path = Mock(return_value=path)
        self.getDirContents = Mock(return_value=contents)

class call(unittest.TestCase):
    """ Test cases of call """

    def test_entriesBuilt(self):
        """ Test that entries are built properly """
        date = datetime.date(year=2015, month=1, day=1)
        items = range(10)
        path = "Some/Path"
        expected = ["Something - " + str(i) for i in range(len(items))]
        dateFiles = DateFileMock('not year', results=expected, contents=items, path=path)

        actual = DateFiles.__call__(dateFiles, date)

        dateFiles.path.assert_called_once_with(date)
        dateFiles.getDirContents.assert_called_once_with(path)
        for item in items:
            dateFiles.build.assert_any_call(date, item)
        self.assertEqual(actual, expected)

    @patch('devlog.files.date_files.datetime')
    def test_noDateProvided_Year(self, DatetimeMock):
        """ Test that when no date is provided, but the Date Type is Year, the entries are built properly """
        dateToUse = datetime.date(year=2015, month=1, day=1)
        items = range(10)
        path = "Some/Path"
        expected = ["Something - " + str(i) for i in range(len(items))]
        dateFiles = DateFileMock('year', results=expected, contents=items, path=path)

        DatetimeMock.date.today = Mock(return_value=dateToUse)

        try:
            actual = DateFiles.__call__(dateFiles)

            dateFiles.path.assert_called_once_with(dateToUse)
            dateFiles.getDirContents.assert_called_once_with(path)
            for item in items:
                dateFiles.build.assert_any_call(dateToUse, item)
            self.assertEqual(actual, expected)
        except TypeError:
            self.fail('A TypeError should not be thrown for the date argument when the Date Type is year')

    def test_noDateProvided_NotYear(self):
        """ Test that when no date is provided, but the Date Type is not Year, the call throws an Exception """
        dateFiles = DateFileMock('not year')

        self.assertRaises(TypeError, DateFiles.__call__, dateFiles)

class build(unittest.TestCase):
    """ Test cases of build """

    def test_built(self):
        """ Test that the date is built properly """
        date = datetime.date(year=2015, month=1, day=1)
        newValue = 3
        dateFiles = DateFiles.Days
        expected = "Something"

        builderInstance = Mock()
        builderInstance.build = Mock(return_value=expected)

        with patch('devlog.files.date_files.DateBuilder', return_value=builderInstance) as DateBuilderMock:
            actual = dateFiles.build(date, newValue)
            DateBuilderMock.assert_called_once_with(date)
            builderInstance.build.assert_called_once_with(**{dateFiles.field: newValue})
            self.assertEqual(actual, expected)

class path(unittest.TestCase):
    """ Test cases of path """

    def test_path(self):
        """ Test that the date is built properly """
        date = datetime.date(year=2015, month=1, day=1)
        createFlag = "Gibberish..."
        dateFiles = DateFiles.Days
        expected = "Something"

        builderInstance = Mock()
        builderInstance.getPath = Mock(return_value=expected)

        with patch('devlog.files.date_files.PathBuilder', return_value=builderInstance) as PathBuilderMock:
            actual = dateFiles.path(date, create=createFlag)
            PathBuilderMock.assert_called_once_with()
            builderInstance.getPath.assert_called_once_with(date, dateFiles.field, create=createFlag)
            self.assertEqual(actual, expected)


# https://www.acmicpc.net/problem/10798

texts = []
length = []

for _ in range(5):
    text = input()
    texts.append(text)
    length.append(len(text))

for i in range(max(length)):
    for j in range(len(texts)):
        try:
            print(texts[j][i], end='')
        except IndexError:
            continue


import os
import subprocess
import typing
import unittest

from dottygen.cli import main as run_codegen
from dottygen.tests.system.utils import TEST_DIR
from dottygen.utils import logger

from argparse import ArgumentParser

def _build_test_case(*,
                     filename: str,
                     protocol: str,
                     unop,
                     asynchronous) -> typing.Type[unittest.TestCase]:

    output_file = f"test.scala"
    parent_output = os.path.abspath(os.path.join('effpi_sandbox',output_file))

    class CodeGenerationTest(unittest.TestCase):

        def setUp(self):

            if os.path.exists(parent_output):
                os.remove(parent_output)

        def test_code_generation(self):
            flags = [os.path.join(TEST_DIR, 'examples', filename), protocol ]
            if unop:
                flags += ["--unop"]
            if asynchronous:
                flags += ["--async"]

            phase = 'Run codegen'
            exit_code = run_codegen(flags)
            if exit_code != 0:
                logger.FAIL(phase)
            else:
                logger.SUCCESS(phase)

            self.assertEqual(exit_code, 0)

            phase = 'Check generated Effpi code'
            completion = subprocess.run(f"sbt 'tests/runMain effpi_sandbox.{protocol}.Main'", shell=True, stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)

            exit_code = completion.returncode
            if exit_code != 0:
                logger.FAIL(phase)

                if completion.stdout:
                    logger.ERROR('stdout', completion.stdout)

                if completion.stderr:
                    logger.ERROR('stderr', completion.stderr)
            else:
                logger.SUCCESS(phase)
                # os.remove(parent_type_output)
                # os.remove(parent_function_output)

            self.assertEqual(exit_code, 0)
            print()

    test_name = f'{filename}: {protocol}>'
    CodeGenerationTest.__name__ = test_name
    CodeGenerationTest.__qualname__ = test_name
    return CodeGenerationTest

def parse_arguments(args: typing.List[str]) -> typing.Dict:
    """Prepare command line argument parser and return the parsed arguments
    from the specified 'args'."""

    parser = ArgumentParser()

    parser.add_argument('--unop', help='unoptimised merging', action='store_true')

    parser.add_argument('--async', help='asynchronous communication', action='store_true')

    parsed_args = parser.parse_args(args)
    return vars(parsed_args)

def build_test_suite(tests, args: typing.List[str]) -> unittest.TestSuite:

    parsed_args = parse_arguments(args)
    unop = parsed_args['unop']
    asynchronous = parsed_args['async']

    suite = unittest.TestSuite()
    for test in tests:
        for protocol in test.protocols:
            TestCase = _build_test_case(filename=test.filename,
                                        protocol=protocol.identifier, unop=unop, asynchronous=asynchronous)

            suite.addTests(unittest.makeSuite(TestCase))

    return suite


import tensorflow as  tf
x=tf.placeholder(tf.float32,shape=[],name='input')
y=tf.placeholder(tf.float32,shape=[],name='label')
w = tf.get_variable(
'weight', shape=[], initializer=tf.truncated_normal_initializer())
b = tf.get_variable('bias', shape=[], initializer=tf.zeros_initializer())
Y_predicted = w * x + b
loss = tf.square(y - Y_predicted, name='loss')
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    writer = tf.summary.FileWriter('./linear_log', graph=sess.graph)
    sess.run(init)
    data=[[3,4],[5,6],[8,10]]
    print(sess.run(w) )
    print(sess.run(b) )
    tf.summary.scalar("loss", loss)
    merged_summary = tf.summary.merge_all()
    for i in range(100):
        total_loss = 0
        for a, c in data:
            _, l = sess.run([optimizer, loss], feed_dict={x: a, y: c})
            total_loss+=l
        summary=sess.run(merged_summary,feed_dict={x:3,y:4})
        print(summary)
        writer.add_summary(summary,i)
        writer.flush()
        print("Epoch {0}: {1}".format(i, total_loss / 2))
        print(sess.run(w))
        print(sess.run(b))


import random
import uuid
import csv
from multiprocessing import Pool
from mimesis import Person, Business, Address
from generator_helpers import date_generator
import datetime
from pathlib import Path

def generate_address():
    """
    generate data that can be used by account, member, etc
    :return:
    """
    address = Address("en")

    address_schema = {
        "primary_address_line1": address.address(),
        "primary_address_line2": address.address(),
        "primary_address_city": address.city(),
        "primary_address_state": address.state(abbr=True),
        "primary_address_zipcode": address.postal_code(),
    }

    return address_schema

class MemberRoster:
    """
    Used to generate data for EDI file for adjudication.
    Member scheme is reversed from edi converter -> generate_edi.py
    """

    def __init__(self, processes_number=8):
        self.processes_number = processes_number

    def member_schema(self, _):
        fake_person = Person("en")
        fake_businees = Business("en")
        """
        Values that are commented are not yet needed for use.
        :return: data for 1 member according to edi converter required values
        """
        first_name = fake_person.first_name()
        last_name = fake_person.last_name()
        company = fake_businees.company()
        member_schema = {
            "identity_id": f"{uuid.uuid4()}",
            "last_name": last_name,
            "first_name": first_name,
            "middle_name": f"{random.choice(['A', 'B', 'C', 'D', 'Z'])}",
            "gender": random.choice(["Male", "Female"]),
            "birth_date": date_generator.date_time_between(start_date="-90y").strftime(
                "%m/%d/%Y"
            ),
            "ssn": f"{random.randint(111, 999)}-{random.randint(11, 99)}-{random.randint(1111, 9999)}",
            "mobile_phone_number": f"({random.randint(111, 999)}) {random.randint(111, 999)}-{random.randint(1111, 9999)}",
            "home_phone_number": f"({random.randint(111, 999)}) {random.randint(111, 999)}-{random.randint(1111, 9999)}",
            "ethnicity": random.choice(["Asian", "Black", "White", "Hispanic"]),
            "email": fake_person.email(domains=["example.com"]),
            "Sponsor": company,
            "Plan": "MIGR-10010",
            "banana ID": random.randint(1111111, 9999999),
            "Note": random.choice(["Executive, Sponsor", f"Member - {company}"]),
        }
        member_schema.update(generate_address())

        return member_schema

    def generate(self, members_num):
        """
        Generate member data list
        :param members_num: number of members to generate
        :return: members list ready for use
        """
        pool = Pool(self.processes_number)
        result = pool.map(self.member_schema, range(members_num))
        return result

    def save_to_csv(self, filename, data_list):
        """
        Saves generated datalist int csv file.
        Currently we use member data only.

        :param filename: name of the file we want to save to.
        :param data_list: list of generated entries
        :return: *.csv file on disk
        """
        field_names = [
            "identity_id",
            "last_name",
            "first_name",
            "middle_name",
            "gender",
            "birth_date",
            "ssn",
            "mobile_phone_number",
            "home_phone_number",
            "ethnicity",
            "primary_address_line1",
            "primary_address_line2",
            "primary_address_city",
            "primary_address_state",
            "primary_address_zipcode",
            "email",
            "Sponsor",
            "Plan",
            "banana ID",
            "Note",
        ]
        csv_file = csv.DictWriter(open(f"{filename}", "w+"), field_names)
        csv_file.writeheader()
        csv_file.writerows(data_list)

class VaccinedPatient:
    def __init__(self, entries_number=1, processes_number=8):
        self.processes_number = int(processes_number)
        self.entries_number = int(entries_number)

    def build_schema(self, _):
        self.fake = Person("en")
        vaccine_administered = date_generator.date_time_between(start_date="-3M")
        dob = date_generator.date_time_between(start_date="-70y", end_date="-15y")
        schema = {
            "Vaccine Administered Date/Time": vaccine_administered.strftime(
                "%d/%m/%Y %H:%M:%S"
            ),
            "Manufacturer": random.choice(["PFIZER", "MODERNA", "JOHNSON"]),
            "Email Address": self.fake.email(domains=["example.com"]),
            "Date of Birth": dob.strftime("%d/%m/%Y"),
            "Dose": random.choice(["Initial Dose", "Second Dose"]),
            "First Name": self.fake.first_name(),
            "Last Name": self.fake.last_name(),
            "Full Name": "",
            "Patient ID": str(uuid.uuid4()),
        }
        schema["Full Name"] = f"{schema['First Name']} {schema['Last Name']}"
        return schema

    def generate(self):
        pool = Pool(self.processes_number)
        result = pool.map(self.build_schema, range(self.entries_number))
        return result

    def csv(self, filepath=None):
        now = datetime.datetime.now()
        filepath = (
            filepath
            if filepath
            else Path(f"{Path.cwd()}/{now.year}/{now.month}/{now.day}/")
        )
        Path(filepath).mkdir(exist_ok=True, parents=True)

        filename = f"{filepath}test_delta_match_data_{int(now.timestamp())}.csv"
        data_list = self.generate()
        csv_file = csv.DictWriter(open(filename, "w+"), fieldnames=data_list[-1].keys())
        csv_file.writeheader()
        csv_file.writerows(data_list)
        return filename

if __name__ == "__main__":
    mmbr = VaccinedPatient(entries_number=10)
    data_list = mmbr.generate()
    mmbr.csv("test_data.csv")


vars = {
  # Use this googlecode_url variable only if there is an internal mirror for it.
  # If you do not know, use the full path while defining your new deps entry.
  "googlecode_url": "http://%s.googlecode.com/svn",

  "clang_rev": "@43229",
  "dart_rev": "@44800",
  "gyp_rev": "@1752",
}

deps = {
  # Stuff needed for GYP to run.
  "third_party/gyp":
      (Var("googlecode_url") % "gyp") + "/trunk" + Var("gyp_rev"),

  "third_party/clang":
      ((Var("googlecode_url") % "dart") + "/third_party/clang" +
       Var("clang_rev")),

  "dart":
      ((Var("googlecode_url") % "dart") + "/branches/bleeding_edge/dart" +
       Var("dart_rev")),
}

# To include Mac deps on other OSes, add this to your .gclient file:
#
#     target_os = [ "mac" ]
#
# To ignore the host OS, add this:
#
#     target_os_only = True
deps_os = {
  "android": {
  },

  "mac": {
  },

  "unix": {
  },

  "win": {
  },
}

hooks = [
  {
    'name': 'third_party_libs',
    'pattern': '.',
    'action': [
      'download_from_google_storage',
      '--no_auth',
      '--no_resume',
      '--bucket',
      'dart-dependencies-fletch',
      '-d',
      '-r',
      '--auto_platform',
      'fletch/third_party/libs',
    ],
  },
  {
    'name': 'third_party_binaries',
    'pattern': '.',
    'action': [
      'download_from_google_storage',
      '--no_auth',
      '--no_resume',
      '--bucket',
      'dart-dependencies-fletch',
      '-d',
      '-r',
      '--auto_platform',
      'fletch/third_party/bin',
    ],
  },
  {
    'name': 'dart_test_binary',
    'pattern': '.',
    'action': [
      'download_from_google_storage',
      '--no_auth',
      '--no_resume',
      '--bucket',
      'dart-dependencies-fletch',
      '-d',
      '-r',
      '--auto_platform',
      'fletch/tools/testing/bin',
    ],
  },
  {
    'name': 'GYP',
    'pattern': '.',
    'action': [
      'ninja', '-C', 'fletch',
    ],
  },
]


from django.shortcuts import render, redirect, get_object_or_404, reverse
from django.views.generic import TemplateView, FormView
from app_user.models import User, Project, ProgramLang, ProjectPicture
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
import random
from .forms import (
    ProjectCreationForm,
    ProjectEditForm,
    AddProjectPictureForm,
    UserLangSelectFilterForm,
    ProjectLangSelectFilterForm,
)

class HomeView(TemplateView):
    """
    View for the home page.
    """

    model = User
    template_name = "app_home/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

class AboutView(TemplateView):
    """
    View for the about page.
    """

    model = User
    template_name = "app_home/about.html"

class DeveloperOverview(TemplateView):
    """
    View for the general overview displaying all users except the
    logged in user.
    """

    model = User
    template_name = "app_home/developer_overview.html"

    def get(self, request, *args, **kwargs):
        if request.GET.get("p_language", None):
            p_langs = ProgramLang.objects.filter(
                pk__in=request.GET.getlist("p_language")
            )
        else:
            p_langs = []
        form = UserLangSelectFilterForm(initial={"p_language": p_langs})

        all_users = User.objects.all().exclude(pk=request.user.pk)
        href_filter = ""
        for lang in p_langs:
            all_users = all_users.filter(p_language=lang).order_by("id")
            href_filter += f"&p_language={lang.pk}"

        # set up pagination for users (8 per page)
        # passing in users filtered by p_lang that are distinct
        paginator = Paginator(all_users, 8)
        page_number = request.GET.get("page")
        users = paginator.get_page(page_number)
        p_nums = "p" * users.paginator.num_pages
        context = {
            "form": form,
            "href_filter": href_filter,
            "users": users,
            "p_nums": p_nums,
        }
        return render(request, "app_home/developer_overview.html", context)

class ProfileDetailView(LoginRequiredMixin, TemplateView):
    """
    View for rendering detailed profile view for chosen user.
    """

    model = User
    template_name = "app_home/user_detail_view.html"

    def get(self, request, *args, **kwargs):
        profile_pk = kwargs["pk"]
        user_to_get = get_object_or_404(User, pk=profile_pk)
        try:
            user_to_get_projects = Project.objects.filter(user=user_to_get)
        except Exception:
            user_to_get_projects = None

        try:
            p_langs = user_to_get.p_language.values()
        except Exception:
            p_langs = None

        context = {
            "user": request.user,
            "user_for_profile": user_to_get,
            "p_langs": p_langs,
            "user_projects": user_to_get_projects,
        }
        return render(request, "app_home/user_detail_view.html", context)

class ProjectOverview(TemplateView):
    """
    Project overview view.
    """

    model = Project
    template_name = "app_home/project_overview.html"

    def get(self, request, *args, **kwargs):
        if request.GET.get("p_language", None):
            p_langs = ProgramLang.objects.filter(
                pk__in=request.GET.getlist("p_language")
            )
        else:
            p_langs = []
        form = ProjectLangSelectFilterForm(initial={"p_language": p_langs})

        all_projects = Project.objects.all()
        href_filter = ""
        for lang in p_langs:
            all_projects = all_projects.filter(p_language=lang).order_by("id")
            href_filter += f"&p_language={lang.pk}"

        # set up pagination
        paginator = Paginator(all_projects, 4)
        page_number = request.GET.get("page")
        projects = paginator.get_page(page_number)
        p_nums = "p" * projects.paginator.num_pages
        context = {
            "form": form,
            "href_filter": href_filter,
            "projects": projects,
            "p_nums": p_nums,
        }
        return render(request, "app_home/project_overview.html", context)

class ProjectDetailView(LoginRequiredMixin, TemplateView):
    """
    View for rendering the detail page for a project.
    """

    model = Project
    template_name = "app_home/project_detail_view.html"

    def get(self, request, *args, **kwargs):
        project_pk = kwargs["pk"]
        project_to_get = get_object_or_404(Project, pk=project_pk)

        context = {"user": request.user, "project": project_to_get}

        return render(request, "app_home/project_detail_view.html", context)

class CreateProjectView(LoginRequiredMixin, FormView):
    """
    View to create a project.
    """

    template_name = "app_home/create_project.html"
    form_class = ProjectCreationForm

    def get(self, request):
        project_form = ProjectCreationForm()
        context = {"form": project_form}

        return render(request, "app_home/create_project.html", context)

    def post(self, request):
        user = request.user
        form = self.form_class(request.POST)
        p_langs = form.data.getlist("p_language")

        if form.is_valid():
            new_project = form.save()
            new_project.user.add(user)
            for lang in p_langs:
                new_project.p_language.add(lang)
                new_project.save()
            messages.success(request, "Project successfully created!")
            return redirect(
                reverse(
                    "app_home:project-detail-view",
                    kwargs={"pk": new_project.pk},
                )
            )
        elif "profanity" in form.errors.as_text():
            messages.error(
                request, "Please do not use profanities in your project name!"
            )
        elif "duplicate_name" in form.errors.as_text():
            messages.error(
                request, "Project name already taken! Please choose another."
            )
        else:
            messages.error(
                request, "Please select at least one programming language"
            )
        return redirect(reverse("app_home:create-project"))

class EditProjectView(LoginRequiredMixin, TemplateView):
    """
    View to edit a project
    """

    model = Project
    template_name = "app_home/edit_project.html"

    def get(self, request, *args, **kwargs):
        project = get_object_or_404(Project, pk=kwargs["pk"])
        if project.user.get() != request.user:
            return redirect("app_home:project-overview")
        else:
            context = {
                "project": project,
                "form": ProjectEditForm(instance=project),
            }

        return render(request, "app_home/edit_project.html", context)

    def post(self, request, *args, **kwargs):
        user = request.user
        project = get_object_or_404(Project, pk=kwargs["pk"])
        form = ProjectEditForm(request.POST, instance=project)
        p_langs = form.data.getlist("p_language")
        if form.is_valid():
            project = form.save(commit=False)
            project.p_language.set(p_langs)
            project.save()
            messages.success(request, "Project successfully edited!")
            return redirect(
                reverse(
                    "app_home:project-detail-view", kwargs={"pk": project.pk}
                )
            )
        elif "profanity" in form.errors.as_text():
            messages.error(
                request, "Please do not use profanities in your project name!"
            )
            return render(
                request, "app_home/edit_project.html", {"form": form}
            )
        elif "duplicate_name" in form.errors.as_text():
            messages.error(
                request, "Project name already in use! Please choose another"
            )
            return render(
                request, "app_home/edit_project.html", {"form": form}
            )
        elif not form["p_language"].value():
            messages.error(
                request, "Please select at least one programming language"
            )
        else:
            messages.error(
                request, "Form could not be submitted. Please try again"
            )
        return render(request, "app_home/edit_project.html", {"form": form})

class DeleteProjectView(LoginRequiredMixin, TemplateView):
    """
    View to delete a project
    """

    model = Project
    template_name = "app_home/about.html"

    def get(self, request, *args, **kwargs):
        project = get_object_or_404(Project, pk=kwargs["pk"])
        if project:
            if project.user.get() != request.user:
                return redirect("app_home:project-overview")
            else:
                project.delete()
                messages.success(request, "Project successfully deleted!")
        else:
            messages.error(
                request, "Project could not be deleted. Please try again."
            )
        return redirect(reverse("app_home:project-overview"))

class AddProjectPicture(LoginRequiredMixin, TemplateView):
    """
    View to add a picture to a project
    """

    model = ProjectPicture
    template_name = "app_home/project_picture.html"

    def get(self, request, *args, **kwargs):
        project = get_object_or_404(Project, pk=kwargs["pk"])
        if project.project_pic:
            pic_query_set = project.project_pic.values()
        else:
            pic_query_set = [""]
        form = AddProjectPictureForm()
        context = {
            "project": project,
            "pictures": pic_query_set,
            "form": form,
        }
        return render(request, "app_home/project_picture.html", context)

    def post(self, request, *args, **kwargs):
        project = get_object_or_404(Project, pk=kwargs["pk"])
        project_pk = project.pk

        new_picture = AddProjectPictureForm(
            request.POST, request.FILES, initial={"project": project}
        )
        if new_picture.is_valid():
            new_picture = new_picture.save(commit=False)
            new_picture.project = project
            new_picture.save()
            messages.success(request, "Picture successfully added!")
        else:
            messages.error(
                request, "Your picture could not be added at this time."
            )

        return redirect(
            reverse("app_home:add-project-pic", kwargs={"pk": project_pk})
        )

class DeleteProjectPicture(LoginRequiredMixin, TemplateView):
    """
    View to delete pictures from projects
    """

    model = ProjectPicture
    template_name = "app_home/project_picture.html"

    def get(self, request, *args, **kwargs):
        pic_to_delete = get_object_or_404(ProjectPicture, pk=kwargs["pk"])
        project = pic_to_delete.project
        project_owner_pk = project.user.values()[0]["id"]
        if request.user.pk == project_owner_pk:
            pic_to_delete.delete()
            messages.success(request, "Picture successfully deleted!")
            return redirect(
                reverse("app_home:add-project-pic", kwargs={"pk": project.pk})
            )
        messages.error(request, "Picture could not be deleted!")
        return redirect(reverse("app_home:project-overview"))


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

# In[3]:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pickle

df = pd.read_csv('train.csv')
df.loc[df['Fare']>400, 'Fare'] = df['Fare'].median()

df['Age'].fillna(df['Age'].median(), inplace=True)
df['Embarked'].fillna("S", inplace=True)

del df['Cabin']
del df['Ticket']

def get_title(name):
    if "." in name:
        return name.split(",")[1].split('.')[0].strip()
    else:
        return 'No title in name'

def shorter_titles(x):
    title = x['Title']
    if title in ['Capt', 'Col', 'Major']:
        return 'Officer'
    elif title in ['Jonkheer', 'Lady', 'Don', 'Sir', 'the Countess', 'Dona']:
        return 'Royalty'
    elif title == 'Mme':
        return 'Mrs'
    elif title in ['Mlle', 'Ms']:
        return 'Miss'
    else:
        return title

titles = set([x for x in df.Name.map(lambda x: get_title(x))])
df['Title'] = df['Name'].map(lambda x: get_title(x))
df['Title'] = df.apply(shorter_titles, axis=1)
df.drop('Name', axis=1, inplace=True)

df.Sex.replace(('male', 'female'), (0, 1), inplace=True)
df.Embarked.replace(('S', 'C', 'Q'), (0, 1, 2), inplace=True)
df.Title.replace(('Mr', 'Miss', 'Mrs', 'Master', 'Dr', 'Rev', 'Royalty', 'Officer'), (0, 1, 2, 3, 4, 5, 6, 7), inplace=True)

corr = df.corr()
corr.Survived.sort_values(ascending=False)

y = df['Survived']
x = df.drop(['Survived', 'PassengerId'], axis=1)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1)

randomforest = RandomForestClassifier()
randomforest.fit(x_train, y_train)
pickle.dump(randomforest, open('titanic_model.sav', 'wb'))

# In[ ]:

# In[ ]:


from database_utils import PokeDatabase, DB_FILENAME

def get_poke_by_name(poke_name: str) -> dict:
    with PokeDatabase(DB_FILENAME) as cursor:
        cursor.execute('''SELECT name, type1, type2, sum_stats,
           hp, attack, special_attack, defense,
           special_defense FROM Pokemons WHERE name = ?''',
                       (poke_name,))
        x = cursor.fetchone()
        return x

def get_poke_by_type(type1: str, type2: str = None) -> list:
    with PokeDatabase(DB_FILENAME) as cursor:
        if type2:
            cursor.execute('''
            SELECT name, type1, type2, sum_stats,
           hp, attack, special_attack, defense,
           special_defense FROM Pokemons WHERE type1 = ? AND type2 = ?''',
                           (type1, type2))

        else:
            cursor.execute('''
            SELECT name, type1, type2, sum_stats,
           hp, attack, special_attack, defense,
           special_defense FROM Pokemons WHERE type1 = ?''', (type1,))

        return cursor.fetchall()

def add_poke_to_db(name: str, type1: str, type2: str, sum_stats: int, hp: int,
                   attack: int, special_attack: int, defense: int,
                   special_defense: int) -> None:
    with PokeDatabase(DB_FILENAME) as cursor:
        cursor.execute('''
        INSERT INTO Pokemons ('name', 'type1', 'type2', 'sum_stats',
        'hp', 'attack', 'special_attack', 'defense', 'special_defense')
        VALUES (?,?,?,?,?,?,?,?,?)''', (name, type1, type2, sum_stats,
                                        hp, attack, special_attack, defense,
                                        special_defense))

def update_poke(name: str, type1: str = None, type2: str = None,
                sum_stats: int = None, hp: int = None, attack: int = None,
                special_attack: int = None, defense: int = None,
                special_defense: int = None) -> None:

    params = [type1, type2, sum_stats, hp, attack, special_attack,
                  defense, special_defense]
    params_names = ['type1', 'type2', 'sum_stats', 'hp', 'attack',
                    'special_attack', 'defense', 'special_defense']

    with PokeDatabase(DB_FILENAME) as cursor:
        for param, param_name in zip(params, params_names):
            if param:
                query = '''
                UPDATE Pokemons SET ''' + param_name + '''
                    = ? WHERE name = ?'''
            cursor.execute(query, (param, name))

def delete_poke(name: str) -> None:
    with PokeDatabase(DB_FILENAME) as cursor:
        cursor.execute('''
        DELETE FROM Pokemons WHERE name = ?''', (name,))

def get_poke_by_stats_above_or_below(hp: int, attack: int, sattack: int,
                             defense: int, sdefense: int, above: bool) -> list:
    params = [hp, attack, sattack, defense, sdefense]
    params_names = ['hp', 'attack', 'special_attack', 'defense', 'special_defense']
    operator = " > " if above else " < "

    query = '''SELECT name, type1, type2, sum_stats,
           hp, attack, special_attack, defense,
           special_defense FROM Pokemons WHERE '''

    for param, param_name in zip(params, params_names):
        if param:
            query += param_name + operator + str(param) + " AND "

    query = query[:-len(" AND ")]

    with PokeDatabase(DB_FILENAME) as cursor:
        cursor.execute(query)
        return cursor.fetchall()


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 13:29:11 2023

@author: danpa
"""

import numpy as np
import argparse
import flatgraphene as fg
import optimizer
import TEGT_calculator
import os

def get_top_layer(atoms):
    xyz=atoms.positions

    tags=np.array(atoms.get_chemical_symbols())
    top_pos_ind=np.where(tags!=tags[0])[0]
    top_pos=xyz[top_pos_ind,:]

    return top_pos,top_pos_ind

def get_bottom_layer(atoms):
    xyz=atoms.positions

    tags=np.array(atoms.get_chemical_symbols())
    bot_pos_ind=np.where(tags==tags[0])[0]
    bot_pos=xyz[bot_pos_ind,:]

    return bot_pos,bot_pos_ind

def get_recip_cell(cell):
    periodicR1 = cell[0,:]
    periodicR2 = cell[1,:]
    periodicR3 = cell[2,:]
    V = np.dot(periodicR1,np.cross(periodicR2,periodicR3))
    b1 = 2*np.pi*np.cross(periodicR2,periodicR3)/V
    b2 = 2*np.pi*np.cross(periodicR3,periodicR1)/V
    b3 = 2*np.pi*np.cross(periodicR1,periodicR2)/V
    return np.stack((b1,b2,b3),axis=0)

def get_twist_geom(t,a=2.46):
    sep=3.35
    p_found, q_found, theta_comp = fg.twist.find_p_q(t)
    atoms=fg.twist.make_graphene(cell_type="hex",n_layer=2,
                                        p=p_found,q=q_found,lat_con=a,sym=["B","Ti"],
                                        mass=[12.01,12.02],sep=sep,h_vac=3)
    pos = atoms.positions
    recip_cell = get_recip_cell(atoms.get_cell())
    vecs = np.array([recip_cell[0,:2],recip_cell[1,:2],recip_cell[0,:2]-recip_cell[1,:2]])
    top_pos,top_pos_ind =  get_top_layer(atoms)
    bot_pos,bot_pos_ind = get_bottom_layer(atoms)
    for i in top_pos_ind:
        pos[i,2] += np.sum(np.cos(np.dot(vecs, pos[i,:2])))
    for j in bot_pos_ind:
        pos[j,2] -= np.sum(np.cos(np.dot(vecs, pos[j,:2])))

    atoms.set_positions(pos)

    return atoms,top_pos_ind
if __name__=="__main__":

    #import matplotlib.pyplot as plt
    # atoms,top_pos_ind = get_twist_geom(2.88)
    # pos = atoms.positions[top_pos_ind,:]
    # cell = atoms.get_cell()
    # plt.scatter(pos[:,0],pos[:,1],c=pos[:,2])
    # line = np.linspace(0,1,10)
    # plt.plot(cell[0,0]*line,cell[0,1]*line)
    # plt.plot(cell[1,0]*line,cell[1,1]*line)
    # plt.colorbar()
    # plt.show()
    parser = argparse.ArgumentParser()
    parser.add_argument('-t','--theta',  type=str,default=False)
    args = parser.parse_args()

    theta_str = args.theta.replace(".","_")
    atoms = get_twist_geom(args.theta)
    model_dict = dict({"tight binding parameters":"Popov Van Alsenoy",
                          "orbitals":"pz",
                          "nkp":225,
                          "intralayer potential":"Pz rebo",
                          "interlayer potential":"Pz KC inspired",
                          'use mpi':True,
                          'label':theta_str})

    calc = TEGT_calculator.TEGT_Calc(model_dict)
    atoms.calc = calc
    calc_dir = calc.calc_dir
    dyn = optimizer.TEGT_FIRE(atoms, restart=os.path.join(calc_dir,'qn.pckl')
                    ,logfile=os.path.join(calc_dir,'ase_opt.output'),
                      trajectory=os.path.join(calc_dir,'tblg'+theta_str+'.traj'))
    dyn.run(fmax=1e-4)


import selenium
from  selenium import webdriver
import time
import unittest
import  dbtest
from selenium.webdriver.common.keys import Keys
class demotest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.drver = webdriver.Chrome(r"E:\git project\UIAutomationTest\test\res\driver\chrome\chromedriver.exe")
        cls.drver.maximize_window()
        cls.drver.implicitly_wait(10)
        cls.url = "http://jackey.mileclass.cn:9949/user/login"
        cls.verificationErrors = []
        cls.accept_next_alert = True
        cls.drver.get(cls.url)
        print(cls.verificationErrors)
    @classmethod
    def tearDownClass(cls):
        cls.drver.quit()
    def login(self,username,password):
        drver = self.drver
        # drver.get('http://jackey.mileclass.cn:9949/user/login')
        # drver.find_element_by_xpath('/html/body/div/div[2]/div/div/div[2]/div[1]/input').clear(username)
        # time.sleep(3)
        drver.find_element_by_xpath('/html/body/div/div[2]/div/div/div[2]/div[1]/input').send_keys(username)
        # drver.find_element_by_xpath('//*[@class=\'pwd_item\']').clear(password)
        # time.sleep(3)
        drver.find_element_by_xpath('//*[@class=\'pwd_item\']').send_keys(password)
        drver.find_element_by_xpath('/html/body/div/div[2]/div/div/button').click()

    def test_login_fail(self):
        self.login('11497', '123456')
        drver = self.drver
        # drver.find_element_by_xpath('/html/body/div/div[2]/div/div/div[2]/div[1]/input').send_keys('11497')
        # drver.find_element_by_xpath('//*[@class=\'pwd_item\']').send_keys('123456')
        # drver.find_element_by_xpath('/html/body/div/div[2]/div/div/button').click()
        # time.sleep(3)
        tip = drver.find_element_by_xpath("/html/body/div/div[2]/div/div/div[3]/div/span/span").text
        self.assertEquals(tip, '账户名与密码不匹配，请重新输入')

    def test_login_success(self):
        drver = self.drver
        time.sleep(3)
        # drver.find_element_by_xpath('/html/body/div/div[2]/div/div/div[2]/div[1]/input').clear()
        # drver.find_element_by_xpath('//*[@class=\'pwd_item\']').clear()
        ele1 = drver.find_element_by_xpath('/html/body/div/div[2]/div/div/div[2]/div[1]/input')
        ele2 = drver.find_element_by_xpath('//*[@class=\'pwd_item\']')
        ele1.send_keys(Keys.CONTROL+'a')
        ele1.send_keys(Keys.DELETE)
        ele2.send_keys(Keys.CONTROL+'a')
        ele2.send_keys(Keys.DELETE)
        self.login('11497','123456a')
        time.sleep(5)
        getsql = dbtest.sqlclass.excutesql(sql="SELECT * FROM uc_user_register WHERE username = '11497';")
        tip = drver.find_element_by_xpath('/html/body/div/div[1]/div/div/span[4]/span[1]').text
        self.assertIn(tip, '梁晓蝶')
        drver.find_element_by_xpath('/html/body/div/div[2]/div/div[1]/ul/li[2]/a/span').click()
        time.sleep(3)
        drver.find_element_by_xpath(
            '/html/body/div/div[2]/div/div[2]/div/div[2]/div[2]/div[1]/ul/li[1]/a/div/div[2]/p[1]').click()
        time.sleep(5)

if __name__ == '__main__':
    unittest.main()


import numpy as np

# +------------+
# | Initialize |
# +------------+
# Function for Moving Average
def calculate_sma(price, n, m=0):
    """
    n: n period - calculate period
    m: m period - moving period
    """
    if m != 0: price = price[:-m]
    price = price[-n:]
    sma = price.mean()
    return sma

def calculate_ema(price, n, m=0):
    """
    n: n period - calculate period
    m: m period - moving period
    """
    if m != 0: price = price[:-m]
    price = price[-n:]

    ema_i = price[0]

    for i in range(n):

        day = i+1
        alpha = 2./(day+1)

        ema_i = ema_i*(1-alpha) + price[i]*alpha

    return ema_i

def calculate_ma(price, n, m, mode='sma'):
    if mode == 'sma':
        ma = calculate_sma(price, n, m)
    if mode == 'ema':
        ma = calculate_ema(price, n, m)
    return ma

# Function for Alligator Indicator
def check_sleeping(stock, nday):

    is_sleeping = False

    close = attribute_history(security=stock, count=30+nday, unit='1d', fields='close', df=False)['close']

    for day in range(nday):
        # Blue  Alligator’s Jaw   [13 bars SMMA(SMA) moved into the future by 8 bars]
        ma_b = calculate_ma(price=close, n=13, m=8, mode='sma')
        # Red   Alligator’s Teeth [ 8 bars SMMA(SMA) moved into the future by 5 bars]
        ma_r = calculate_ma(price=close, n=8,  m=5, mode='sma')
        # Green Alligator’s Lips  [ 5 bars SMMA(SMA) moved into the future by 3 bars]
        ma_g = calculate_ma(price=close, n=5,  m=3, mode='sma')

        if abs(ma_b/ma_r-1) < 0.02 and abs(ma_r/ma_g-1) < 0.02:

            is_sleeping = True

            break

        close = close[:-1] # check nday before

    return is_sleeping

# Function Excuted Monthly
def check_monthly(context):

    # Excute Every 3 Month
    month_current = context.current_dt.month
    if (month_current - g.month_start) % 3 != 0: return

    # Reset Position
    for stock in g.stock_list_bought:
        order_target(security=stock, amount=0)
        log.info('[Reset Position] {}'.format(stock))

    # Reset Global Parameters
    g.price_high = {}   # 向上碎形最高价
    g.price_low  = {}   # 向下碎形最低价

    g.fractal_up   = {} # 判断有效向上碎形
    g.fractal_down = {} # 判断有效向下碎形

    g.AO_indicator = {} # 存放连续的AO指标数据
    g.AC_indicator = {} # 存放连续的AC指标数据
    g.amount       = {} # 满仓仓位

    g.stock_list_bought = []

    # Get History Record (Duration: 30 days, Interval: 1 day)
    for stock in g.stock_list:

        is_sleeping = check_sleeping(stock, nday=20)

        if is_sleeping:

            g.stock_list_bought.append(stock)

            # Initial Stock Info
            g.price_high[stock] = 0 # 向上碎形最高价
            g.price_low[stock]  = 0 # 向下碎形最低价

            g.fractal_up[stock]   = False # 判断有效向上碎形
            g.fractal_down[stock] = False # 判断有效向下碎形

            g.AO_indicator[stock] = [0] # 存放连续的AO指标数据
            g.AC_indicator[stock] = [0] # 存放连续的AC指标数据
            g.amount[stock]       = 0   # 满仓仓位

    return None

# Main
def initialize(context):

    g.price_high = {}           # 向上碎形最高价
    g.price_low  = {}           # 向下碎形最低价

    g.fractal_up   = {}         # 判断有效向上碎形
    g.fractal_down = {}         # 判断有效向下碎形

    g.AO_indicator = {}         # 存放连续的AO指标数据
    g.AC_indicator = {}         # 存放连续的AC指标数据

    g.amount = {}               # 满仓仓位
    g.stock_list_bought = []

    g.market_index = '000300.XSHG' # 沪深300
    g.stock_list = get_index_stocks(g.market_index)

    set_benchmark(g.market_index)

    g.month_start = context.current_dt.month

    run_monthly(check_monthly, 1, 'open')

    return

# +-------------+
# | Handle Data |
# +-------------+
# Function for Market Return
def calculate_market_return(market_index, duration):
    """
    计算大盘n日收益率
    """
    hist = attribute_history(security=market_index, count=duration+1, unit='1d', fields='close', df=False)

    close_t = hist['close'][-1]
    close_0 = hist['close'][0]

    market_return = (close_t-close_0)/close_0

    return market_return

def conduct_market_stop_loss(market_index, duration, min_return):
    """
    大盘止损
    """
    market_return = calculate_market_return(market_index, duration)

    if market_return <= min_return:
        for stock in g.stock_list_bought:
            order_target(security=stock, amount=0)
            log.info('[Stop Loss] Sell {}'.format(stock))
        return True

    else:
        return False

# Function for Stock Return
def calculate_stock_return(context, data, stock):
    """
    计算个股累计收益率
    """
    stock_return = None

    if stock in context.portfolio.positions:

        price_bought  = context.portfolio.positions[stock].avg_cost
        price_current = data[stock].avg

        if price_bought != 0:
            stock_return = (price_current-price_bought)/price_bought

    return stock_return

def conduct_stock_stop_loss(context, data, stock, min_return):
    """
    个股止损
    """
    stock_return = calculate_stock_return(context, data, stock)

    if stock_return is not None and stock_return < min_return:
        order_target(security=stock, amount=0)
        log.info('[Stop Loss] Sell {}'.format(stock))
        return True

    else:
        return False

def conduct_stock_take_profit(context, data, stock, max_return):
    """
    个股止盈
    """
    stock_return = calculate_stock_return(context, data, stock)

    if stock_return is not None and stock_return > max_return:
        order_target(security=stock, amount=0)
        log.info('[Take Profit] Sell {}'.format(stock))
        return True

    else:
        return False

# Function for AO Indicator
def calculate_AO_indicator(stock):
    """
    MEDIAN = (HIGH + LOW) / 2
    AO = SMA (MEDIAN, 5) - SMA (MEDIAN, 34)
    """
    hist = attribute_history(security=stock, count=35, unit='1d', fields=['high', 'low'], df=False)
    price_median = (hist['high']+hist['low'])/2

    mid_sma_5d  = calculate_sma(price=price_median, n=5,  m=0)
    mid_sma_34d = calculate_sma(price=price_median, n=34, m=0)

    AO = mid_sma_5d - mid_sma_34d

    g.AO_indicator[stock].append(AO)

    return

# Function for AC Indicator
def calculate_AC_indicator(stock):
    """
    AC = AO - SMA (AO, 5)
    """
    calculate_AO_indicator(stock)

    if len(g.AO_indicator[stock]) >= 5:

        AO = g.AO_indicator[stock][-1]

        price_AO = np.array(g.AO_indicator[stock])

        sma_AO_5d = calculate_sma(price=price_AO, n=5)

        AC = AO - sma_AO_5d

        g.AC_indicator[stock].append(AC)

    return

# Function for Fractal Indicator
def check_fractal_indicator(stock, direction):

    hist_close = attribute_history(security=stock, count=30, unit='1d', fields='close', df=False)['close']

    # Red Alligator’s Teeth [ 8 bars SMMA(SMA) moved into the future by 5 bars]
    ma_r = calculate_ma(price=hist_close, m=8, n=5, mode='sma')

    if direction == 'up':

        hist_high  = attribute_history(security=stock, count=5, unit='1d', fields='high', df=False)['high']

        if max(hist_high) == hist_high[2] and sum(hist_high==hist_high[2]) == 1:

            high = hist_high[2]

            g.price_high[stock] = high

            if high > ma_r:
                g.fractal_up[stock] = True
            else:
                g.fractal_up[stock] = False

    if direction == 'down':

        hist_low  = attribute_history(security=stock, count=5, unit='1d', fields='low', df=False)['low']

        if min(hist_low) == hist_low[2] and sum(hist_low==hist_low[2]) == 1:

            low = hist_low[2]

            g.price_low[stock] = low

            if low < ma_r:
                g.fractal_down[stock] = True
            else:
                g.fractal_down[stock] = False

    return

def is_fractal_broken(stock, direction):

    close = attribute_history(security=stock, count=1, unit='1d', fields='close', df=False)['close'][0]

    if direction == 'up':

        if close > g.price_high[stock]:

            return True

    if direction == 'down':

        if close < g.price_low[stock]:

            return True

    return False

def is_up_going(check_list, nday):
    """
    判断n日上行
    """
    if len(check_list) < nday:

        return False
    for i in range(nday-1):
        if check_list[i] > check_list[i+1]:
            return False
    return True

def is_down_going(check_list, nday):
    """
    判断n日下行
    """
    if len(check_list) < nday:
        return False
    for i in range(nday-1):
        if check_list[i] < check_list[i+1]:
            return False
    return True

def initial_position(stock, context):

    current_data = get_current_data()
    last_price = current_data[stock].last_price

    available_share = np.floor(context.portfolio.available_cash/last_price)

    if available_share >= 100:

        share = 100

        g.amount[stock] = share

        order(security=stock, amount=share)

        log.info('[Initial Position] Buy {} shares of {}'.format(share, stock))

        g.fractal_down[stock] = False

    return

def clear_position(stock, context):

    order_target(security=stock, amount=0)

    log.info('[Clear Position] Sell all shares of {}'.format(stock))

    g.fractal_up[stock] = False

    return

def adjust_position(stock, context, ratio):

    current_data = get_current_data()
    last_price = current_data[stock].last_price

    available_share = np.floor(context.portfolio.available_cash/last_price)

    adjust_share = np.ceil(g.amount[stock]*ratio/100)*100

    if adjust_share <= available_share:

        order(security=stock, amount=adjust_share)

        log.info('[Adjust Position] Buy {} shares of {}'.format(adjust_share, stock))

    return

# Main
def handle_data(context, data):
    """
    日常任务
    """
    log.info('[Portfolio] Available Cash {}'.format(context.portfolio.available_cash))

    # [大盘止损]
    is_market_stop_loss = conduct_market_stop_loss(market_index=g.market_index, duration=3, min_return=-0.3)

    if is_market_stop_loss: return

    for stock in g.stock_list_bought:

        # [个股止损]
        is_stock_stop_loss   = conduct_stock_stop_loss(context, data, stock, min_return=-0.1)
        # [个股止盈]
        is_stock_take_profit = conduct_stock_take_profit(context, data, stock, max_return=0.3)

        if is_stock_stop_loss or is_stock_take_profit: continue

        # [计算AO & AC指标]
        calculate_AC_indicator(stock)

        # [空仓 - 建仓]
        if stock not in context.portfolio.positions:

            # [检查向上碎形]
            check_fractal_indicator(stock, 'up')

            # [检查向上碎形是否被突破]
            if g.fractal_up[stock]:

                if is_fractal_broken(stock,'up'):

                    hist_close = attribute_history(security=stock, count=5, unit='1d', fields='close', df=False)['close']

                    if  is_up_going(check_list=g.AO_indicator[stock], nday=5) and \
                        is_up_going(check_list=g.AC_indicator[stock], nday=3) and \
                        is_up_going(check_list=hist_close, nday=2):

                        # [建仓]
                        initial_position(stock, context)

        # [持仓 - 调整 or 清仓]
        else:

            # [检查向下碎形]
            check_fractal_indicator(stock, 'down')

            # [检查向下碎形是否被突破]
            if g.fractal_down[stock]:

                if is_fractal_broken(stock,'down'):

                    # [清仓]
                    clear_position(stock,context)

                    return

            hist_close = attribute_history(security=stock, count=5, unit='1d', fields='close', df=False)['close']

            # [加仓10% - AO，AC同时5日上行，且收盘价走高]
            if  is_up_going(check_list=g.AO_indicator[stock], nday=5) and \
                is_up_going(check_list=g.AC_indicator[stock], nday=5) and \
                is_up_going(check_list=hist_close, nday=2):

                # [调整]
                adjust_position(stock, context, ratio=0.1)

            # [减仓10% - AO，AC同时3日下行，且收盘价走低]
            if  is_down_going(check_list=g.AO_indicator[stock], nday=3) and \
                is_down_going(check_list=g.AC_indicator[stock], nday=3) and \
                is_down_going(check_list=hist_close, nday=2):

                # [调整]
                adjust_position(stock, context, ratio=-0.1)

    return


from sqlalchemy import create_engine, text

engine = create_engine('sqlite:///thunderbird_manufacturing.db')
conn = engine.connect()

# DELETE records
deleteStmt = text("DELETE FROM CUSTOMER WHERE CUSTOMER_ID > :id")
conn.execute(deleteStmt, id=10)
print("Records deleted")

# UPDATE records
updateStmt = text("UPDATE CUSTOMER SET STATE = lower(STATE)")
conn.execute(updateStmt)
print("Records updated, STATE made lowercase")

# SELECT records to check them
for r in conn.execute(text("SELECT * FROM CUSTOMER")):
    print(r)

# UPDATE records, make STATE UPPERCASE again
updateStmt = text("UPDATE CUSTOMER SET STATE = upper(STATE)")
conn.execute(updateStmt)

conn.close()


import cv2
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten,Dropout
from keras.layers import Conv2D, MaxPooling2D
import numpy as np
import os
import matplotlib.pyplot as plt
import random
import pickle

cur_path = os.path.dirname(__file__)#gets the current path

Folder = ["Dog","Cat"]

# d = 0
# c = 0
x_train = []
y_train = []
x_test = []
y_test = []
test_img = []

#*****************************  PRE-PRROCESSING ******************************************

for i in Folder:
	path = os.path.join(cur_path , i)#opens the folder Dogs in the current directory

	for img in os.listdir(path):#loading images inside the folder Dogs
		try:
			image = cv2.imread(os.path.join(path,img), 0)
		except Exception as e:
			pass

		if image is None:
			continue
		image = cv2.resize(image,(60,60))
		image_flip = cv2.flip(image , 1)
		x_train.append(image)
		x_train.append(image_flip)
		if i == 'Dog':
			y_train.append(0)
			y_train.append(0)
			# d+=1
		else:
			y_train.append(1)
			y_train.append(1)
			# c+=1

# print(d)
# print(c)

for i in range(0,100):
	x_test.append(x_train[0])
	x_train.pop(0)
	y_test.append((y_train[0]))
	y_train.pop(0)
	test_img.append(x_train[0])

for i in range(0,100):
	x_test.append(x_train[-1])
	x_train.pop(-1)
	y_test.append((y_train[-1]))
	y_train.pop(-1)
	test_img.append(-1)

temp = list(zip(x_train,y_train))
random.shuffle(temp)
x_train,y_train = zip(*temp)

temp = list(zip(x_test,y_test,test_img))
random.shuffle(temp)
x_test,y_test,test_img = zip(*temp)

x_train = np.array(x_train)
x_train = x_train/255

x_test = np.array(x_test).reshape(-1 , 60 , 60 , 1)

dbfile = open('TestingIMG','ab')
pickle.dump(test_img , dbfile)
dbfile.close()

dbfile = open('TestingData','ab')
pickle.dump(x_test , dbfile)
dbfile.close()

dbfile = open('TestingLabels','ab')
pickle.dump(y_test , dbfile)
dbfile.close()


DIRECTION_MAPPING = {
    'U': [0, 1],
    'D': [0, -1],
    'L': [-1, 0],
    'R': [1, 0],
}
ROPE_LENGTH = 10

knot_positions = [[0,0] for knot in range(10)]
tail_positions = set()

def new_knot_position(leading_knot, trailing_knot):
    h_displacement = trailing_knot[0] - leading_knot[0]
    v_displacement = trailing_knot[1] - leading_knot[1]

    if (h_displacement ** 2 + v_displacement ** 2) ** 0.5 >= 2:
        return [trailing_knot[0] - min(max(h_displacement, -1), 1), trailing_knot[1] - min(max(v_displacement, -1), 1)]

    return trailing_knot

with open("input") as fp:
    while True:
        line = fp.readline().strip()
        if not line:
            break

        direction, amount = line.split(' ')

        for i in range(int(amount)):
            knot_positions[0] = [knot_positions[0][0] + DIRECTION_MAPPING[direction][0], knot_positions[0][1] + DIRECTION_MAPPING[direction][1]]
            for index in range(ROPE_LENGTH - 1):
                knot_positions[index + 1] = new_knot_position(knot_positions[index], knot_positions[index + 1])
                if index == ROPE_LENGTH - 2:
                    tail_positions.add(','.join([ str(unit) for unit in knot_positions[index + 1]]))

print('Head end position:', knot_positions[0])
print('Tail end position:', knot_positions[-1])
print(len(tail_positions))


import dataclasses
from typing import Optional

from mediapipe.python import packet_creator
from mediapipe.python import packet_getter
from mediapipe.python._framework_bindings import image as image_module
from mediapipe.tasks.cc.vision.face_stylizer.proto import face_stylizer_graph_options_pb2
from mediapipe.tasks.python.core import base_options as base_options_module
from mediapipe.tasks.python.core import task_info as task_info_module
from mediapipe.tasks.python.core.optional_dependencies import doc_controls
from mediapipe.tasks.python.vision.core import base_vision_task_api
from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module
from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module

_BaseOptions = base_options_module.BaseOptions
_FaceStylizerGraphOptionsProto = (
    face_stylizer_graph_options_pb2.FaceStylizerGraphOptions
)
_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions
_TaskInfo = task_info_module.TaskInfo

_STYLIZED_IMAGE_NAME = 'stylized_image'
_STYLIZED_IMAGE_TAG = 'STYLIZED_IMAGE'
_NORM_RECT_STREAM_NAME = 'norm_rect_in'
_NORM_RECT_TAG = 'NORM_RECT'
_IMAGE_IN_STREAM_NAME = 'image_in'
_IMAGE_OUT_STREAM_NAME = 'image_out'
_IMAGE_TAG = 'IMAGE'
_TASK_GRAPH_NAME = 'mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph'
_MICRO_SECONDS_PER_MILLISECOND = 1000

@dataclasses.dataclass
class FaceStylizerOptions:
  """Options for the face stylizer task.

  Attributes:
    base_options: Base options for the face stylizer task.
  """

  base_options: _BaseOptions

  @doc_controls.do_not_generate_docs
  def to_pb2(self) -> _FaceStylizerGraphOptionsProto:
    """Generates an FaceStylizerOptions protobuf object."""
    base_options_proto = self.base_options.to_pb2()
    return _FaceStylizerGraphOptionsProto(base_options=base_options_proto)

class FaceStylizer(base_vision_task_api.BaseVisionTaskApi):
  """Class that performs face stylization on images."""

  @classmethod
  def create_from_model_path(cls, model_path: str) -> 'FaceStylizer':
    """Creates an `FaceStylizer` object from a TensorFlow Lite model and the default `FaceStylizerOptions`.

    Note that the created `FaceStylizer` instance is in image mode, for
    stylizing one face on a single image input.

    Args:
      model_path: Path to the model.

    Returns:
      `FaceStylizer` object that's created from the model file and the default
      `FaceStylizerOptions`.

    Raises:
      ValueError: If failed to create `FaceStylizer` object from the provided
        file such as invalid file path.
      RuntimeError: If other types of error occurred.
    """
    base_options = _BaseOptions(model_asset_path=model_path)
    options = FaceStylizerOptions(base_options=base_options)
    return cls.create_from_options(options)

  @classmethod
  def create_from_options(cls, options: FaceStylizerOptions) -> 'FaceStylizer':
    """Creates the `FaceStylizer` object from face stylizer options.

    Args:
      options: Options for the face stylizer task.

    Returns:
      `FaceStylizer` object that's created from `options`.

    Raises:
      ValueError: If failed to create `FaceStylizer` object from
        `FaceStylizerOptions` such as missing the model.
      RuntimeError: If other types of error occurred.
    """

    task_info = _TaskInfo(
        task_graph=_TASK_GRAPH_NAME,
        input_streams=[
            ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]),
            ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]),
        ],
        output_streams=[
            ':'.join([_STYLIZED_IMAGE_TAG, _STYLIZED_IMAGE_NAME]),
            ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]),
        ],
        task_options=options,
    )
    return cls(
        task_info.generate_graph_config(),
        running_mode=running_mode_module.VisionTaskRunningMode.IMAGE,
    )

  def stylize(
      self,
      image: image_module.Image,
      image_processing_options: Optional[_ImageProcessingOptions] = None,
  ) -> image_module.Image:
    """Performs face stylization on the provided MediaPipe Image.

    Only use this method when the FaceStylizer is created with the image
    running mode.

    Args:
      image: MediaPipe Image.
      image_processing_options: Options for image processing.

    Returns:
      The stylized image of the most visible face. The stylized output image
      size is the same as the model output size. None if no face is detected
      on the input image.

    Raises:
      ValueError: If any of the input arguments is invalid.
      RuntimeError: If face stylization failed to run.
    """
    normalized_rect = self.convert_to_normalized_rect(
        image_processing_options, image
    )
    output_packets = self._process_image_data({
        _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image),
        _NORM_RECT_STREAM_NAME: packet_creator.create_proto(
            normalized_rect.to_pb2()
        ),
    })
    if output_packets[_STYLIZED_IMAGE_NAME].is_empty():
      return None
    return packet_getter.get_image(output_packets[_STYLIZED_IMAGE_NAME])


import numpy as np
import requests
from bs4 import BeautifulSoup
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin, urlparse
from flask_cors import CORS
from flask import Flask, request, jsonify, make_response
import sys
from flask_restx import Api, Resource, fields
class MultiThreadScraper:
    def __init__(self, base_url):
        self.base_url = base_url
        self.root_url ='{}://{}'.format(urlparse(self.base_url).scheme,urlparse(self.base_url).netloc)
        self.pool = ThreadPoolExecutor(max_workers=20)
        self.scraped_pages = set([])
        self.to_crawl = Queue()
        self.to_crawl.put(self.base_url)
        self.data = ''
    def parse_links(self, html):
        soup = BeautifulSoup(html, 'html.parser')
        links = soup.find_all('a', href=True)
        file_name = 'result.txt'
        file = open(file_name,'wb')
        for link in links:
            url = link['href'] + '\n'
            file.write(url.encode())
            if url.startswith('/') or url.startswith(self.root_url):
                url = urljoin(self.root_url, url)
                if url not in self.scraped_pages:
                    self.to_crawl.put(url)
    def scrape_info(self, html):
        return
    def post_scrape_callback(self, res):
        result = res.result()
        if result and result.status_code == 200:
            self.parse_links(result.text)
            self.scrape_info(result.text)
    def scrape_page(self, url):
        try:
            res = requests.get(url, timeout=(3, 30))
            return res
        except requests.RequestException:
            return
    def run_scraper(self):
        while True:
            try:
                target_url = self.to_crawl.get(timeout=60)
                if target_url not in self.scraped_pages:
                    print("Scraping URL: {}".format(target_url))
                    self.scraped_pages.add(target_url)
                    job = self.pool.submit(self.scrape_page, target_url)
                    job.add_done_callback(self.post_scrape_callback)
                    print("Job completed successfully")
            except Empty:
                return
            except Exception as e:
                print(e)
                continue
flask_app = Flask(__name__)
CORS(flask_app)
app = Api(app=flask_app,version="1.0",title="Multi-threaded scraping utility",description="Scrape data from URL")
name_space = app.namespace('scraper', description='Scraping APIs')
model = app.model('Scraping params',{'url': fields.String(required=True,description="URL for scraping",help="URL cannot be left blank"),})

@name_space.route("/")
class MainClass(Resource):
    def options(self):
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "*")
        response.headers.add('Access-Control-Allow-Methods', "*")
        return response
    @app.expect(model)
    def post(self):
        try:
            formData = request.json
            input_raw = [val for val in formData.values()]
            # input_raw[0] is the url
            s = MultiThreadScraper(input_raw[0])
            s.run_scraper()
            response = jsonify({"statusCode": 200,"status": "Scraping Completed","result": "Scraping has been done.Please check the folder for content",})
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        except Exception as error:
            return jsonify({"statusCode": 500,"status": "Could not scrape","result": "Please review your response and try again","error": str(error)})