from googlesearch import search
import speedtest
from recognize import speak
import pywikihow
import wikipedia
import subprocess
import openai
import webbrowser
import csv

openai.api_key = "YOUR'S API KEY HERE"

def get_url(query):
    for url in search(query, num_results=1):
        return url

def speed_test():
    speed = speedtest.Speedtest()
    download_speed = round(float(speed.download()) * 0.000000125, 2)
    upload_speed = round(float(speed.upload()) * 0.000000125, 2)

    print(f"the downloading speed is {download_speed} megabytes and uploading speed is {upload_speed} megabytes")
    speak(f"the downloading speed is {download_speed} megabytes and uploading speed is {upload_speed} megabytes")

def how_question(query):
    searched = pywikihow.search_wikihow(query, max_results=1)
    assert len(searched) == 1
    print(searched[0].summary)

def chatgpt_ai(input_text):
    output = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user",
    "content": input_text}]
    )
    answer = output.choices[0].message.content.replace('"', '')
    if "sorry" in answer or "?" in answer or "but" in answer or "AI language model" in answer:
        print("I cannot understand")
        speak("I cannot understand")
        return False
    else:
        print(answer)
        speak(answer)
        return True

def wikipedia(querylist):
    speak("Searching wikipedia")
    string = ' '.join(querylist)
    query = string.replace("wikipedia", "")
    results = wikipedia.summary(query, sentence=2)
    print(f"according to wikipedia {results}")
    speak(f"according to wikipedia {results}")

def search_and_open_link(search_input):
    csv_file = 'C:\\Users\\aliha\\Documents\\Python Projects\\Voice Assistant\\website_link.csv'
    with open(csv_file, 'r') as file:
        csv_reader = csv.DictReader(file)
        for row in csv_reader:
            if search_input in row['Name']:
                link = row['Links']
                webbrowser.open(link)
                break
        else:
            speak("No matching link found from file.")


from model.airport import AirportSchema
from model.city import CitySchema
from model.flight import FlightSchema
from model.seat import SeatSchema
from model.crew import CrewSchema

guarulhos = {
    "name": "Guarulhos",
    "state": "São Paulo",
    "country": "Brazil",
}

los_angeles = {
    "name": "Los Angeles",
    "state": "California",
    "country": "United States",
}

guarulhos = CitySchema().load(guarulhos)
los_angeles = CitySchema().load(los_angeles)

print(f"=== Serialized City Info ===\n{ guarulhos }\n{ los_angeles }")

guarulhos_airport = {
    # Deserializes the city object to a dictionary
    "city": CitySchema().dump(guarulhos),
    "max_departures": 10,
    "name": "Guarulhos International Airport"
}

guarulhos_airport = AirportSchema().load(guarulhos_airport)

los_angeles_airport = {
    "city": CitySchema().dump(los_angeles),
    "max_departures": 10,
    "name": "Los Angeles International Airport"
}

los_angeles_airport = AirportSchema().load(los_angeles_airport)

print(f"\n=== Serialized Airport Info ===\n{ guarulhos_airport }\n{ los_angeles_airport }")

seats = [
    {
        "id": "A11"
    },
    {
        "id": "A12"
    },
    {
        "id": "A13"
    },
    {
        "id": "A14"
    }
]

seats = SeatSchema(many=True).load(seats)

crew = [
    {
        "name": "John Doe",
        "occupation": "Pilot"
    },
    {
        "name": "Jane Doe",
        "occupation": "Co-Pilot"
    },
    {
        "name": "John Smith",
        "occupation": "Flight Attendant"
    },
    {
        "name": "Jane Smith",
        "occupation": "Flight Attendant"
    }
]

crew = CrewSchema(many=True).load(crew)

flight_a01 = {
    "type": "International",
    "departure": AirportSchema().dump(guarulhos_airport),
    "destination": AirportSchema().dump(los_angeles_airport),
    "departure_time": "10:00:00",
    "departure_date": "2021-01-01",
    "seats": SeatSchema(many=True).dump(seats),
    "crew": CrewSchema(many=True).dump(crew)
}

flight_a01 = FlightSchema().load(flight_a01)

print(f"\n=== Serialized Flight Info ===\n{ flight_a01 }")

free_seats = flight_a01.freeSeats()

print(f"\n=== Free Seats ===")
for seat in free_seats:
    print(seat.id)

crew_members = flight_a01.showCrew()

print(f"\n=== Crew Members ===")
for crew_member in crew_members:
    print(crew_member)


import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('images/cube_indoor.jpg', cv2.IMREAD_GRAYSCALE)
img_fourier = np.fft.fft2(img)
fshift = np.fft.fftshift(img_fourier)
magnitude_spectrum = 20*np.log(1 + np.abs(fshift))

plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()

rows, cols = img.shape
crow, ccol = int(rows/2), int(cols/2)

r = 50

new_fshift = np.zeros(fshift.shape)
new_fshift[crow-r:crow+r, ccol-r:ccol+r] = fshift[crow-r:crow+r, ccol-r:ccol+r]

f_ishift = np.fft.ifftshift(new_fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)

magnitude_spectrum = 20*np.log(1 + np.abs(new_fshift))

plt.subplot(121), plt.imshow(img_back, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()

plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img_back, cmap='gray')
plt.title('Image after LPF'), plt.xticks([]), plt.yticks([])

plt.show()


#!/usr/bin/python
import re
import os
import datetime

print("ACE Responder VMSA-2023-0001 Exploitation Checker")
print("This script will check for VMSA-2023-0001 Exploitation on VMWare vRealize Log Insight servers.")
print()

print("[i] .pak files in /tmp. Check for legitimacy:")
paks = os.listdir('/tmp/')
for p in paks:
    if p.endswith('.pak'):
        print(p)

print()

print("[i] Checking for events in runtime.log. Check to see if the source and file are legitimate!")
print()

remote_pak_pattern = re.compile('^\[([^\]]+)\].*REMOTE_PAK_DOWNLOAD_COMMAND.*requestUrl:([^,]+), fileName:([^\)]+)')
with open('/var/log/loginsight/runtime.log') as f:
    for line in f:
        match = re.search(remote_pak_pattern, line)
        if match:
            print('\033[93m[+] REMOTE_PAK_DOWNLOAD on ' + match.group(1) + ' from ' + match.group(2) + ' to ' + match.group(3) + '\033[0m')
            if match.group(3).startswith('../'):
                print('\033[91m\t [!] directory traversal CVE-2022-31706 Exploitation identified! Indicators: '+match.group(2) +' ' + match.group(3)+ '\033[0m')

print()
print("[i] Checking /usr/lib/loginsight/application/sbin timestamps. If loginsight-pak-upgrade.py was updated on a usual date, it could be an indicator of compromise.")

sbin_path = '/usr/lib/loginsight/application/sbin'

def check_mtimes(paths,file):
    files = {}
    popular = {}
    most_popular_count = 0
    most_popular = ''
    for path in paths:
        for fil in os.listdir(path):
            mtime = os.path.getmtime(path+'/'+fil)
            dt_mod = datetime.datetime.fromtimestamp(mtime)
            day = dt_mod.strftime("%Y%m%d")
            files[fil] = day
            if day not in popular.keys():
                popular[day] = 1
            else:
                popular[day] += 1
        for pop in popular.keys():
            if popular[pop] > most_popular_count:
                most_popular_count = popular[pop]
                most_popular = pop
    if files[file] != most_popular:
        print('\033[93m[+] Unusual file modification date '+files[file]+' for '+ file +' most have the date '+most_popular+ '\033[0m')

check_mtimes([sbin_path],'loginsight-pak-upgrade.py')

print()
print("[i] Checking /usr/lib/sa for unusual modified times.")
for t in ['sa1','sa2','sadc']:
    check_mtimes(['/usr/lib/sa'],t)
print()

print("[i] Checking for unusual cron files.")
cron_files = {'d':['0hourly','dailyjobs','li-stats','sysstat','timesync'],'daily':['audit-rotate'],'hourly':['0anacron','logrotate'], 'weekly':['devcheck','rpmcheck','sgidcheck','suidcheck']}
for cron_int in cron_files.keys():
    for fil in os.listdir('/etc/cron.'+cron_int):
        if fil not in cron_files[cron_int]:
            print('\033[93m[+] Unusual cron file /etc/cron.'+cron_int+'/'+fil+'\033[0m')

for cron_int in cron_files.keys():
    for cronf in cron_files[cron_int]:
        check_mtimes(['/etc/cron.d','/etc/cron.hourly','/etc/cron.daily','/etc/cron.monthly','/etc/cron.weekly'],cronf)


name = input("enter file name: ")
file = open(name)
count = 0
total = 0
final = 0
for line in file:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    count = count + 1
    i=line.find(":")
    number=float(line[i+1:])
    total=number+total
final=total/count
print("average spam confidence:",final)


"""Stage 7: Puzzle 2 of 11

Add "turn right by 90 degrees" code somewhere in the middle of the
program already written below to draw these triangles.

"""

import sys
sys.path.append('..')
import codestudio
artist = codestudio.load('s1level36')
a = artist

artist.color = artist.random_color()
for count in range(3):
    artist.move_forward(100)
    artist.turn_right(120)
artist.color = artist.random_color()
for count in range(3):
    artist.move_forward(100)
    artist.turn_right(120)

artist.check()


'''
takes an image and detectors face by
converting it to grayscale and detecting features
+ a loop to repeat it on each frame
'''

import cv2

# load pretrained data
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# capture video from webcam
webcam = cv2.VideoCapture(0)

while True:

    successful_frame_read, frame = webcam.read()  # successful_frame_read is always True

    # convert to grayscale
    grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces
    face_coordinates = trained_face_data.detectMultiScale(grayscaled_img) # returns list of rectangles where faces are detected

    # print(face_coordinates)

    # Draw rectangles
    for rectangle in face_coordinates:
        cv2.rectangle(frame, ([rectangle[0], rectangle[1]]), ([rectangle[2]+rectangle[0], rectangle[3]+rectangle[1]]), (0,255.0), 2)
        # check documentation to make sure everything is right!

    # display image
    cv2.imshow('Face Detector', frame)

    key = cv2.waitKey(1) # waits 1 milisec
    if key == 113:
        break

print("Code Completed")


#Виконав: Лавренюк Б.В., 1 курс, 122Г, ФТФ
#10. Дані про температуру повітря за декаду листопада зберігаються в масиві.
#Визначити, скільки разів температура опускалася нижче -10 градусів.
import numpy as np #імпортуємо numpy

q = np.zeros(10, dtype = int) #створюємо масив з нулями
for i in range(10):
    while True: #створюємо умову для зациклення, в разі невірного вводу користувачем
        try:
            q[i] = int(input(f'{i+1} температура за декаду листопада: ')) #елементи масиву
            break
        except ValueError:
            print('Введіть лише ціле число')
print(q)

k = 0 #кількість разів, коли температура опускалася нижче -10 градусів
for i in range(len(q)): #проходимося по нашому масиві
    if q[i] < -10: #якщо елемент масиву менший за -10, то добавляємо +1
        k += 1
print(f'Температура опускалася нижче -10 градусів {k} раз(-ів, -и)')


# Backspace String Compare
""" Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

Example 1:

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Example 2:

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Example 3:

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".

Constraints:

    1 <= s.length, t.length <= 200
    s and t only contain lowercase letters and '#' characters.
 """

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        left_1, left_2 = len(s) - 1, len(t) - 1
        sign_1, sign_2 = 0, 0
        while left_1 >= 0 or left_2 >= 0:
            while left_1 >= 0:
                if s[left_1] == '#':
                    sign_1 += 1
                    left_1 -= 1
                elif sign_1 > 0:
                    sign_1 -= 1
                    left_1 -= 1
                else:
                    break

            while left_2 >= 0:
                if t[left_2] == '#':
                    sign_2 += 1
                    left_2 -= 1
                elif sign_2 > 0:
                    sign_2 -= 1
                    left_2 -= 1
                else:
                    break

            if left_1 < 0 and left_2 < 0:
                return True
            if left_1 >= 0 and left_2 < 0:
                return False
            if left_1 < 0 and left_2 >= 0:
                return False
            if s[left_1] != t[left_2]:
                return False

            left_1 -= 1
            left_2 -= 1

        return True


from os import name
import random as rand
from tkinter import messagebox

class Student:
    tries = 0
    score = 0

    def __init__ (self, pname, page, score):
        self.name = pname
        self.age = page
        self.score = score

    def difficulty(self):
        range1 = range(1,8)
        range2 = range(9,16)
        if self.age in range1:
            randnum = 10
        elif self.age in range2:
            randnum = 20
        else:
            randnum = 30
        return randnum


def finder(arr1, arr2):
    arr2.sort()
    for x in arr2:
        if x in arr1:
            arr1.remove(x)
    return arr1[0]

finder = finder([5, 5, 7, 7], [5, 7, 7])
print('The Missing Number is: ', finder)


"""Build bank account UI for deposit and withdraw"""
import tkinter as tk
from tkinter import ttk
from typing import TypeVar

from ..classes.bank import BankAccount, Transaction

BUI = TypeVar("BUI", bound="BankAccountUI")
TH = TypeVar("TH", bound="TransactionHistory")

class BankAccountUI:
    """

    Attributes:
        withdraw_entry:
        bank_acc:
        balance_entry:
        account_balance:
        upper_frame:
        account:
        trx_list:
        middle_frame:
        deposit_entry:
        deposit:
        withdraw:
        root:

    """

    def __init__(self: BUI, account: BankAccount) -> None:
        self.account = account
        self.root = tk.Tk()
        self.bank_acc = tk.Frame(self.root)
        self.upper_frame = tk.Frame(self.bank_acc)
        self.middle_frame = tk.Frame(self.bank_acc)
        self.balance_entry = tk.Entry()
        self.deposit_entry = tk.Entry()
        self.withdraw_entry = tk.Entry()
        self.account_balance = tk.IntVar()
        self.trx_list = TransactionHistory(self.root)

    def create_ui(self: BUI) -> None:
        """ """
        self.create_root()
        self.create_window()
        self.create_upper_frame()
        self.create_balance_display()
        self.create_middle_frame()
        self.create_deposit_view()
        self.create_withdrawal_view()

        self.add_transaction_list()

        self.root.mainloop()

    def create_root(self: BUI) -> None:
        """ """
        root = tk.Tk()
        root.geometry("900x600")
        root.title("Transfer Money")
        root.configure(bg="orange")
        self.root = root

    def create_window(self: BUI) -> None:
        """ """
        bank_acc = tk.Frame(self.root)
        bank_acc.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
        self.bank_acc = bank_acc

    def create_upper_frame(self: BUI) -> None:
        """ """
        frame = tk.Frame(self.bank_acc, bg="#80c1ff")
        frame.place(relx=0.4, rely=0.1)
        self.upper_frame = frame

    def create_balance_display(self: BUI) -> None:
        """ """
        balance_label = tk.Label(self.upper_frame, text="Account balance")
        balance_label.pack(side="left")

        self.account_balance = tk.IntVar()
        self.account_balance.set(self.account.get_balance())
        self.balance_entry = tk.Entry(
            self.upper_frame, textvariable=self.account_balance
        )
        self.balance_entry.pack(side="right")

    def create_middle_frame(self: BUI) -> None:
        """ """
        frame = tk.Frame(self.bank_acc, bg="#80c1ff")
        frame.place(relx=0.4, rely=0.4)
        self.middle_frame = frame

    def create_deposit_view(self: BUI) -> None:
        """ """
        deposit_label = tk.Label(
            self.middle_frame, text="Deposit amount", relief="raised"
        )
        deposit_label.pack(side="top")

        deposit_amount = tk.IntVar()

        self.deposit_entry = tk.Entry(
            self.middle_frame, textvariable=deposit_amount
        )
        self.deposit_entry.place(relx=0.2, rely=0.8)
        self.deposit_entry.pack(side="top")

        deposit_button = tk.Button(
            self.middle_frame, text="Submit", command=self.deposit
        )
        deposit_button.pack(side="top")

    def create_withdrawal_view(self: BUI) -> None:
        """ """
        withdraw_label = tk.Label(
            self.middle_frame, text="Withdrawl amount", relief="raised"
        )
        withdraw_label.pack(side="top")

        withdraw_amount = tk.IntVar()

        self.withdraw_entry = tk.Entry(
            self.middle_frame, textvariable=withdraw_amount
        )
        self.withdraw_entry.place(relx=0.6, rely=0.4)
        self.withdraw_entry.pack(side="top")

        withdraw_button = tk.Button(
            self.middle_frame, text="Withdraw", command=self.withdraw
        )
        withdraw_button.pack(side="top")

    def add_transaction_list(self: BUI) -> None:
        """ """
        self.trx_list.create_transaction_list()

    def update(self: BUI) -> None:
        """ """
        # self.account_balance.set(self.account.get_balance())
        self.display_account_status()

    def deposit(self: BUI) -> None:
        """ """
        trx = self.account.deposit(int(self.deposit_entry.get()))
        if trx:
            self.trx_list.add_to_list(trx)
        self.update()

    def withdraw(self: BUI) -> None:
        """ """
        trx = self.account.withdraw(int(self.withdraw_entry.get()))
        if trx:
            self.trx_list.add_to_list(trx)
        self.update()

    def display_account_status(self: BUI) -> None:
        """ """
        if self.account.is_overdrawn():
            self.balance_entry.config({"background": "Red"})
        else:
            self.balance_entry.config({"background": "Green"})

class TransactionHistory:
    """
    Widget to display transaction history in a list
    """

    def __init__(self: TH, frame: tk.Tk) -> None:
        self.frame = frame
        self.trx_tree = ttk.Treeview(self.frame)
        style = ttk.Style()
        style.configure("Treeview", rowheight=40)

    def create_transaction_list(self: TH) -> None:
        """
        Create table to display transaction history

        """
        list_header_label = tk.Label(self.frame, text="Transaction history")
        list_header_label.pack(side="bottom")

        self.trx_tree["columns"] = ("Type", "Amount", "Balance")
        self.trx_tree.column("#0", width=0, stretch="n")
        self.trx_tree.column("Type", anchor="w", width=120)
        self.trx_tree.column("Amount", anchor="w", width=120)
        self.trx_tree.column("Balance", anchor="w", width=120)

        self.trx_tree.heading("Type", text="Type", anchor="w")
        self.trx_tree.heading("Amount", text="Amount", anchor="w")
        self.trx_tree.heading("Balance", text="Balance", anchor="w")

        # self.trx_tree.insert(
        #     parent="", index="end", values=["Deposit", "12", "12"]
        # )
        self.trx_tree.pack(pady=2)

    def add_to_list(self: TH, trx: Transaction) -> None:
        """

        Args:
            trx (Transaction):

        """
        self.trx_tree.insert(
            parent="", index="end", values=list(trx.serialize().values())
        )


import sys
from flask import Flask
from flask.globals import request
from flask_cors import cross_origin
import json

from spider.jing_dong import jingDongSpider
from fenci.fenci import handleList
from emotion.index import analyzeEmotion

app = Flask(__name__)

# 京东爬虫
@app.route("/jingdong_spider/<id>/<page>/<score>")
@cross_origin()
def jingdong_spider(id, page, score):
    resList = jingDongSpider(id, page, score)
    return {
        'success': True,
        'data': resList,
    }

# 分词处理
@app.route("/fenci", methods=['POST'])
@cross_origin()
def fenci():
    data = request.get_data()
    data = json.loads(data.decode('utf-8'))
    data.setdefault('comments', [])
    seg_data = handleList(data['comments'])
    return {
        'success': True,
        'data': seg_data,
    }

# 分词处理
@app.route("/emotion", methods=['POST'])
@cross_origin()
def emotion():
    print(request)
    data = request.get_data()
    data = json.loads(data.decode('utf-8'))
    data.setdefault('comment', '')
    res = analyzeEmotion(data['comment'])
    return {
        'success': True,
        'data': res,
    }

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5001)


from dataclasses import dataclass
from functools import cached_property
from typing import Mapping

from advent_of_code_2015_python.day_14.parser import Parser
from advent_of_code_2015_python.day_14.shared import Reindeer

@dataclass
class Day14PartASolver:
    reindeer: set[Reindeer]
    total_seconds: int

    @property
    def solution(self) -> int:
        return max(self.reindeer_distance.values())

    @cached_property
    def reindeer_distance(self) -> Mapping[Reindeer, int]:
        output: dict[Reindeer, int] = dict()
        for r in self.reindeer:
            full_cycles = int(self.total_seconds / r.cycle_time)
            distance_for_full_cycles = r.km_per_cycle * full_cycles
            remaining_time = self.total_seconds % r.cycle_time
            full_distance = (
                distance_for_full_cycles + min(remaining_time, r.fly_time) * r.km_per_s
            )
            output[r] = full_distance
        return output

def solve(input: str, total_seconds=2503) -> int:
    data = Parser.parse(input)
    solver = Day14PartASolver(data, total_seconds)

    return solver.solution

def get_solution() -> int:
    with open("advent_of_code_2015_python/day_14/input.txt", "r") as f:
        input = f.read()
    return solve(input)

if __name__ == "__main__":
    print(get_solution())


Dans_Girlfriend = [{'name': 'Amber Staff', 'price': 8000, 'quantity': 230, 'market': 7000},
                   {'name': 'Angelic Axe', 'price': 5000, 'quantity': 140, 'market': 4750},
                   {'name': 'Assassin Dagger', 'price': 20000, 'quantity': 180, 'market': 18135},
                   {'name': 'Beastslayer Axe', 'price': 1500, 'quantity': 165, 'market': 1170},
                   {'name': 'Blue Robe', 'price': 10000, 'quantity': 400, 'market': 9700},
                   {'name': 'Boots Of Haste', 'price': 30000, 'quantity': 800, 'market': 29630},
                   {'name': 'Broadsword', 'price': 500, 'quantity': 140, 'market': 200},
                   {'name': 'Butchers Axe', 'price': 18000, 'quantity': 200, 'market': 17100},
                   {'name': 'Composite Hornbow', 'price': 25000, 'quantity': 115, 'market': 20000},
                   {'name': 'Crown Armor', 'price': 12000, 'quantity': 800, 'market': 11315},
                   {'name': 'Crown Helmet', 'price': 2500, 'quantity': 530, 'market': 2380},
                   {'name': 'Crown Legs', 'price': 12000, 'quantity': 390, 'market': 11740},
                   {'name': 'Crown Shield', 'price': 8000, 'quantity': 425, 'market': 7830},
                   {'name': 'Crusader Helmet', 'price': 6000, 'quantity': 205, 'market': 5700},
                   {'name': 'Death Ring', 'price': 1000, 'quantity': 275, 'market': 750},
                   {'name': 'Demon Shield', 'price': 30000, 'quantity': 185, 'market': 27505},
                   {'name': 'Devil Helmet', 'price': 1000, 'quantity': 65, 'market': 300},
                   {'name': 'Diamond Sceptre', 'price': 3000, 'quantity': 245, 'market': 2000},
                   {'name': 'Dragon Scale Mail', 'price': 40000, 'quantity': 95, 'market': 37000},
                   {'name': 'Dragon Shield', 'price': 4000, 'quantity': 300, 'market': 3630},
                   {'name': 'Dragon Slayer', 'price': 15000, 'quantity': 70, 'market': 6750},
                   {'name': 'Dragonbone Staff', 'price': 3000, 'quantity': 200, 'market': 2500},
                   {'name': 'Epee', 'price': 8000, 'quantity': 140, 'market': 7000},
                   {'name': 'Fire Axe', 'price': 8000, 'quantity': 335, 'market': 7230},
                   {'name': 'Fire Sword', 'price': 4000, 'quantity': 715, 'market': 3635},
                   {'name': 'Furry Club', 'price': 1000, 'quantity': 120, 'market': 550},
                   {'name': 'Glacier Amulet', 'price': 1500, 'quantity': 190, 'market': 2300},
                   {'name': 'Glacier Kilt', 'price': 11000, 'quantity': 75, 'market': 10035},
                   {'name': 'Glacier Mask', 'price': 2500, 'quantity': 70, 'market': 2140},
                   {'name': 'Glacier Robe', 'price': 11000, 'quantity': 40, 'market': 10020},
                   {'name': 'Glacier Shoes', 'price': 2500, 'quantity': 25, 'market': 2000},
                   {'name': 'Glorious Axe', 'price': 3000, 'quantity': 785, 'market': 2590},
                   {'name': 'Gold Ring', 'price': 8000, 'quantity': 60, 'market': 7200},
                   {'name': 'Golden Armor', 'price': 20000, 'quantity': 90, 'market': 18540},
                   {'name': 'Golden Legs', 'price': 30000, 'quantity': 50, 'market': 27630},
                   {'name': 'Guardian Shield', 'price': 2000, 'quantity': 820, 'market': 1800},
                   {'name': 'Hibiscus Dress', 'price': 3000, 'quantity': 225, 'market': 2000},
                   {'name': 'Ice Rapier', 'price': 1000, 'quantity': 565, 'market': 750},
                   {'name': 'Lightning Headband', 'price': 2500, 'quantity': 130, 'market': 2100},
                   {'name': 'Lightning Legs', 'price': 11000, 'quantity': 90, 'market': 10000},
                   {'name': 'Lightning Pendant', 'price': 1500, 'quantity': 350, 'market': 1000},
                   {'name': 'Lightning Robe', 'price': 11000, 'quantity': 50, 'market': 10575},
                   {'name': 'Lunar Staff', 'price': 5000, 'quantity': 30, 'market': 4550},
                   {'name': 'Magic Plate Armor', 'price': 90000, 'quantity': 45, 'market': 90100},
                   {'name': 'Magma Amulet', 'price': 1500, 'quantity': 290, 'market': 3700},
                   {'name': 'Magma Boots', 'price': 2500, 'quantity': 115, 'market': 2300},
                   {'name': 'Magma Coat', 'price': 11000, 'quantity': 150, 'market': 10000},
                   {'name': 'Magma Legs', 'price': 11000, 'quantity': 90, 'market': 9750},
                   {'name': 'Magma Monocle', 'price': 2500, 'quantity': 35, 'market': 2100},
                   {'name': 'Mastermind Shield', 'price': 50000, 'quantity': 175, 'market': 48500},
                   {'name': 'Medusa Shield', 'price': 9000, 'quantity': 260, 'market': 7500},
                   {'name': 'Mercenary Sword', 'price': 12000, 'quantity': 260, 'market': 10000},
                   {'name': 'Mycological Bow', 'price': 35000, 'quantity': 25, 'market': 32600},
                   {'name': 'Nightmare Blade', 'price': 35000, 'quantity': 205, 'market': 34505},
                   {'name': 'Noble Axe', 'price': 10000, 'quantity': 160, 'market': 8650},
                   {'name': 'Obsidian Lance', 'price': 500, 'quantity': 100, 'market': 200},
                   {'name': 'Onyx Pendant', 'price': 3500, 'quantity': 20, 'market': 2500},
                   {'name': 'Oriental Shoes', 'price': 15000, 'quantity': 70, 'market': 14030},
                   {'name': 'Paladin Armor', 'price': 15000, 'quantity': 70, 'market': 12900},
                   {'name': 'Pirate Voodoo Doll', 'price': 500, 'quantity': 180, 'market': 200},
                   {'name': 'Platinum Amulet', 'price': 2500, 'quantity': 450, 'market': 2000},
                   {'name': 'Relic Sword', 'price': 25000, 'quantity': 100, 'market': 23400},
                   {'name': 'Rift Bow', 'price': 45000, 'quantity': 50, 'market': 43500},
                   {'name': 'Rift Crossbow', 'price': 45000, 'quantity': 40, 'market': 42100},
                   {'name': 'Rift Lance', 'price': 30000, 'quantity': 20, 'market': 26000},
                   {'name': 'Rift Shield', 'price': 50000, 'quantity': 40, 'market': 45200},
                   {'name': 'Ring Of The Sky', 'price': 30000, 'quantity': 85, 'market': 28000},
                   {'name': 'Royal Helmet', 'price': 30000, 'quantity': 355, 'market': 29000},
                   {'name': 'Sacred Tree Amulet', 'price': 3000, 'quantity': 180, 'market': 2330},
                   {'name': 'Shadow Sceptre', 'price': 10000, 'quantity': 460, 'market': 9700},
                   {'name': 'Shockwave Amulet', 'price': 3000, 'quantity': 150, 'market': 2000},
                   {'name': 'Spiked Squelcher', 'price': 5000, 'quantity': 290, 'market': 4800},
                   {'name': 'Steel Boots', 'price': 30000, 'quantity': 250, 'market': 28050},
                   {'name': 'Taurus Mace', 'price': 500, 'quantity': 100, 'market': 170},
                   {'name': 'Terra Amulet', 'price': 1500, 'quantity': 360, 'market': 1000},
                   {'name': 'Terra Boots', 'price': 2500, 'quantity': 475, 'market': 2100},
                   {'name': 'Terra Hood', 'price': 2500, 'quantity': 300, 'market': 2110},
                   {'name': 'Terra Legs', 'price': 11000, 'quantity': 500, 'market': 9700},
                   {'name': 'Terra Mantle', 'price': 11000, 'quantity': 355, 'market': 10470},
                   {'name': 'Wand Of Cosmic Energy', 'price': 2000, 'quantity': 700, 'market': 1850},
                   {'name': 'Wand Of Decay', 'price': 1000, 'quantity': 290, 'market': 860},
                   {'name': 'Wand Of Draconia', 'price': 1500, 'quantity': 720, 'market': 1335},
                   {'name': 'Wand Of Inferno', 'price': 3000, 'quantity': 1450, 'market': 2850},
                   {'name': 'Wand Of Starstorm', 'price': 3600, 'quantity': 550, 'market': 3330},
                   {'name': 'Wand Of Voodoo', 'price': 4400, 'quantity': 390, 'market': 4000},
                   {'name': 'War Hammer', 'price': 1200, 'quantity': 465, 'market': 950}]


'''
Dijstra's Algorithm Implementation - relies on BFS and a priority queue
to keep track of edges with min_distance.
Running time with priority queue O(v + ElogE)
'''
import heapq

# assume that input graph is an adjacency list as a nested dictionary

def dijstras(graph, start):
    distances = {}
    for v in graph.keys():
        distances[v] = float('inf')
    distances[start] = 0
    pq = [(distances[start], start)]

    while pq:
        cur_distance, u = heapq.heappop(pq)
        if cur_distance > distances[u]:
            continue
        for v, dist in graph[u].items():
            if cur_distance + dist < distances[v]:
                distances[v] = cur_distance + dist
                heapq.heappush(pq, (distances[v], v))
    return distances

graph = {
    'A': {'B': 1, 'C': 2},
    'B': {'C': 4},
    'C': {'D': 2},
    'D': {'A': 2}
}

print(dijstras(graph, 'A'))


from django.urls import path
from file import views
urlpatterns = [

    path('', views.index, name='home'),
    path('login', views.Login, name='login'),
    path('logout', views.Logout, name='logout'),
    path('content', views.Download, name='download'),
    path('content/search=<str:search>',views.Search, name='download')

]


import gradio as gr
import numpy as np
import os

os.environ['GRADIO_ALLOW_FLAGGING'] = 'never'
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'

APP_TITLE = 'Gradio ⚡'
INITIAL_IMAGE = 'img/github_image.png'

def main() -> int:
	app = create_app()
	return run_app(app)

def process_flip_img(image:np.ndarray, colors_flip:bool, horizontal_flip:bool, vertical_flip:bool) -> np.ndarray:
	if vertical_flip:
		image = image[::-1]  # <= np.flipud(image) == np.flip(image, 1)
	if horizontal_flip:
		image = image[:, ::-1]  # <= np.fliplr(image) == np.flip(image, 0)
	if colors_flip:
		dtype_info = np.iinfo(image.dtype) if 'int' in image.dtype.name else np.finfo(image.dtype)
		img_depth = min(max(image.shape[2], 1), 3)
		image[:, :, :img_depth] = np.full(fill_value=dtype_info.max, shape=(*image.shape[:2], img_depth), dtype=image.dtype) - image[:, :, :img_depth]
	return image

def create_app(app_title:str = APP_TITLE) -> gr.Blocks:
	app_theme = gr.themes.Base(
		primary_hue=gr.themes.colors.sky,
		secondary_hue=gr.themes.colors.sky,
		neutral_hue=gr.themes.colors.neutral,
		font=('Segoe UI', 'Arial', 'DejaVu Sans', 'ui-sans-serif', 'system-ui', 'sans-serif'),
		font_mono=('Consolas', 'monospace'))

	with gr.Blocks(title=app_title, theme=app_theme) as app:
		inputs = []
		outputs = []

		gr.HTML(f'
{app_title}
', show_label=False)

		with gr.Row():
			with gr.Column(variant='panel'):
				inputs.append(gr.Image(
					INITIAL_IMAGE,
					type='numpy',
					sources=['upload'],
					image_mode='RGBA',
					show_label=False,
					show_share_button=False,
					show_download_button=False))

			with gr.Column(variant='panel'):
				outputs.append(gr.Image(
					type='numpy',
					sources=[],
					image_mode='RGBA',
					show_label=False,
					show_share_button=False,
					show_download_button=True))

		with gr.Row():
			with gr.Column():
				inputs.append(gr.Checkbox(label='Colors Flip (Image Negative)', value=True))
				inputs.append(gr.Checkbox(label='Horizontal Flip (Left–Right)', value=False))
				inputs.append(gr.Checkbox(label='Vertical Flip (Up–Down)', value=False))

		submit_btn = gr.Button(value='Run', variant='primary')
		submit_btn.click(fn=process_flip_img, inputs=inputs, outputs=outputs)

	return app

def run_app(app:gr.Blocks) -> int:
	app.launch(
		server_name='127.0.0.1',
		server_port=7860,
		share=False,
		debug=False,
		show_api=False,
		quiet=True)
	return 0

if __name__ == '__main__':
	raise SystemExit(main())


#   Look for #IMPLEMENT tags in this file. These tags indicate what has
#   to be implemented to complete the warehouse domain.

#   You may add only standard python imports---i.e., ones that are automatically
#   available on TEACH.CS
#   You may not remove any imports.
#   You may not import or otherwise source any of your own files

import os  # for time functions
import math  # for infinity
import heapq
from search import *  # for search engines
from sokoban import SokobanState, Direction, PROBLEMS  # for Sokoban specific classes and problems

def sokoban_goal_state(state):
    '''
    @return: Whether all boxes are stored.
    '''
    for box in state.boxes:
        if box not in state.storage:
            return False
    return True

def heur_manhattan_distance(state):
    # IMPLEMENT
    '''admissible sokoban puzzle heuristic: manhattan distance'''
    '''INPUT: a sokoban state'''
    '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.'''
    # We want an admissible heuristic, which is an optimistic heuristic.
    # It must never overestimate the cost to get from the current state to the goal.
    # The sum of the Manhattan distances between each box that has yet to be stored and the storage point nearest to it is such a heuristic.
    # When calculating distances, assume there are no obstacles on the grid.
    # You should implement this heuristic function exactly, even if it is tempting to improve it.
    # Your function should return a numeric value; this is the estimate of the distance to the goal.
    h_val = 0
    for box in state.boxes:
        dist = math.inf
        for storage in state.storage:
            if abs(box[0] - storage[0]) + abs(box[1] - storage[1]) < dist:
                dist = abs(box[0] - storage[0]) + abs(box[1] - storage[1])
        h_val += dist
    return h_val

# SOKOBAN HEURISTICS
def trivial_heuristic(state):
    '''trivial admissible sokoban heuristic'''
    '''INPUT: a sokoban state'''
    '''OUTPUT: a numeric value that serves as an estimate of the distance of the state (# of moves required to get) to the goal.'''
    return 0  # CHANGE THIS

def heur_alternate(state):
    # IMPLEMENT
    '''a better heuristic'''
    '''INPUT: a sokoban state'''
    '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.'''
    # heur_manhattan_distance has flaws.
    # Write a heuristic function that improves upon heur_manhattan_distance to estimate distance between the current state and the goal.
    # Your function should return a numeric value for the estimate of the distance to the goal.

    # This heuristic is admissible.
    val = 0
    for box in state.boxes:
        if box in state.storage:
            continue
        if check_corner(state, box): # if any box is in a corner and not a storage point, it can no longer be moved, hence return infinity (will never reach goal)
            return math.inf
        dist = math.inf
        for storage in state.storage:
            if storage in state.boxes: # If storage point already has box on it, don't consider this storage point
                continue
            if abs(box[0] - storage[0]) + abs(box[1] - storage[1]) < dist:
                dist = abs(box[0] - storage[0]) + abs(box[1] - storage[1])
        val += dist
    return val # Measure manhattan distance, but now when any storage point already has boxes on it, it will not count towards the h_val.

def heur_zero(state):
    '''Zero Heuristic can be used to make A* search perform uniform cost search'''
    return 0

def fval_function(sN, weight):
    # IMPLEMENT
    """
    Provide a custom formula for f-value computation for Anytime Weighted A star.
    Returns the fval of the state contained in the sNode.

    @param sNode sN: A search node (containing a SokobanState)
    @param float weight: Weight given by Anytime Weighted A star
    @rtype: float
    """
    return sN.gval + weight * sN.hval

# SEARCH ALGORITHMS
def weighted_astar(initial_state, heur_fn, weight, timebound):
    '''Provides an implementation of weighted a-star, as described in the HW1 handout'''
    '''INPUT: a warehouse state that represents the start state and a timebound (number of seconds)'''
    '''OUTPUT: A goal state (if a goal is found), else False as well as a SearchStats object'''
    '''implementation of weighted astar algorithm'''
    start_time = os.times()[0]
    end_time = start_time + timebound
    se = SearchEngine('custom', 'full')
    wrapped_fval_function = (lambda sN: fval_function(sN, weight))
    se.init_search(initial_state, sokoban_goal_state, heur_fn, wrapped_fval_function)
    goal, ss = se.search(end_time - os.times()[0])

    return goal, ss

def iterative_astar(initial_state, heur_fn, weight=1, timebound=5):  # uses f(n), see how autograder initializes a search line 88
    # IMPLEMENT
    '''Provides an implementation of realtime a-star, as described in the HW1 handout'''
    '''INPUT: a warehouse state that represents the start state and a timebound (number of seconds)'''
    '''OUTPUT: A goal state (if a goal is found), else False as well as a SearchStats object'''
    '''implementation of realtime astar algorithm'''
    start_time = os.times()[0]
    end_time = start_time + timebound
    goal, ss = weighted_astar(initial_state, heur_fn, weight, end_time - os.times()[0])
    while os.times()[0] < end_time:
        diff = end_time - os.times()[0]
        costbound = (math.inf, math.inf, goal.gval)
        reduced_weight = (1 + weight) // 2
        se = SearchEngine('custom', 'full')
        wrapped_fval_function = (lambda sN: fval_function(sN, reduced_weight))
        se.init_search(initial_state, sokoban_goal_state, heur_fn, wrapped_fval_function)
        it_goal, it_ss = se.search(diff, costbound)
        if it_goal and (it_goal.gval < goal.gval):
            goal, ss = it_goal, it_ss
    return goal, ss

def iterative_gbfs(initial_state, heur_fn, timebound=5):  # only use h(n)
    # IMPLEMENT
    '''Provides an implementation of anytime greedy best-first search, as described in the HW1 handout'''
    '''INPUT: a sokoban state that represents the start state and a timebound (number of seconds)'''
    '''OUTPUT: A goal state (if a goal is found), else False'''
    start_time = os.times()[0]
    end_time = start_time + timebound

    se = SearchEngine('best_first', 'full')
    se.init_search(initial_state, sokoban_goal_state, heur_fn)
    goal, ss = se.search(end_time - os.times()[0])

    while os.times()[0] < end_time:
        diff = end_time - os.times()[0]
        costbound = (goal.gval, math.inf, math.inf)
        se.init_search(initial_state, sokoban_goal_state, heur_fn)
        it_goal, it_ss = se.search(diff, costbound)
        if it_goal and (it_goal.gval < goal.gval):
            goal, ss = it_goal, it_ss
    return goal, ss

def check_corner(state, box):
    '''Check if the input box (as a tuple of x and y coordinate) is in a corner'''
    '''return true if in corner (hence we can prune the state)'''
    '''prerequisite: box is not in storage point'''
    up = (box[1] - 1 < 0) or ((box[0], box[1] - 1) in state.obstacles)
    right = (box[0] + 1 >= state.width) or ((box[0] + 1, box[1]) in state.obstacles)
    down = (box[1] + 1 >= state.height) or ((box[0], box[1] + 1) in state.obstacles)
    left = (box[0] - 1 < 0) or ((box[0] - 1, box[1]) in state.obstacles)

    return (up or down) and (left or right)


from __future__ import print_function # use python 3 syntax but make it compatible with python 2
from __future__ import division       #                           ''

import time     # import the time library for the sleep function
import brickpi3 # import the BrickPi3 drivers

BP = brickpi3.BrickPi3() # Create an insta
import numpy as np

WHEEL_RADIUS = 2.8
AXIS_RADIUS = 6.6

def move_forward(distance):
    encoder_value = int(distance * 180/(np.pi * WHEEL_RADIUS))
    print(encoder_value)
    status_A = BP.get_motor_status(BP.PORT_A)
    print('motor A: ',status_A)
    status_D = BP.get_motor_status(BP.PORT_D)
    print('motor D: ',status_D)
    BP.set_motor_position(BP.PORT_A, encoder_value)
    BP.set_motor_position(BP.PORT_D, encoder_value)
    BP.offset_motor_encoder(BP.PORT_A, BP.get_motor_encoder(BP.PORT_A))
    BP.offset_motor_encoder(BP.PORT_D, BP.get_motor_encoder(BP.PORT_D))
    time.sleep(4)

def rotate(alpha):
    #alpha = angle in radians
    encoder_value = int(alpha*AXIS_RADIUS* 180/(np.pi * WHEEL_RADIUS))
    BP.set_motor_position(BP.PORT_A, encoder_value)
    print(encoder_value)
    BP.set_motor_position(BP.PORT_D, -encoder_value)
    BP.offset_motor_encoder(BP.PORT_A, BP.get_motor_encoder(BP.PORT_A))
    BP.offset_motor_encoder(BP.PORT_D, BP.get_motor_encoder(BP.PORT_D))
    time.sleep(4)

def run():
    BP.set_motor_position_kp(BP.PORT_A,25)
    BP.set_motor_position_kd(BP.PORT_A,70)
    BP.set_motor_limits(BP.PORT_A,200,250)

    BP.set_motor_position_kp(BP.PORT_D,25)
    BP.set_motor_position_kd(BP.PORT_D,70)
    BP.set_motor_limits(BP.PORT_D,200,250)

    for i in range(4):
        print("Run #:", i)
        print("Encoder positions:")
        print(BP.get_motor_encoder(BP.PORT_A),BP.get_motor_encoder(BP.PORT_D))
        print('Move forward')
        #print(WHEEL_RADIUS)
        #self.move_forward(66)
        move_forward(40.85) #distance in cm
        print(BP.get_motor_encoder(BP.PORT_A),BP.get_motor_encoder(BP.PORT_D))
        #print('Rotate')
        rotate(np.pi/2 * 1.02)
        print(BP.get_motor_encoder(BP.PORT_A),BP.get_motor_encoder(BP.PORT_D))

if __name__== "__main__":
    try:
        try:
            run()
        except IOError as error:
            print(error)
        time.sleep(0.02)
    except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard.
        BP.reset_all()        # Unconfigure the sensors, disable the motors, and restore the LED to the control of the BrickPi3 firmware.


def pedir_numero():
    while True:
        try:
            numero = int( input( 'Informe um numero' ))
            return numero
            break
        except ValueError:
            print( 'numero invalido' )
    return pedir_numero()

def tratar_numero():
    numeros = pedir_numero()
    soma = 0
    maior = 0
    menor = 0
    for i in range(numeros):
        n = float( input( 'digite um numero' ) )
        maior+=1
        menor+=1
        soma+=n
        if maior != 0 and maior > n :
            print(maior)
        elif menor != 0 and menor < n :
            print(menor)
    print(f' O menor numero é: {menor}, O mairo número é: {maior}' )
    media = soma / numeros
    print( 'A média dos numeros digitadas foi de:', media )
    return tratar_numero

pedir_numero()
tratar_numero()


import pandas as pd
from surprise import Dataset, Reader
from surprise import SVD
from surprise import accuracy
from surprise.model_selection import train_test_split

class Recommender:
    def __init__(self, data_dict):
        # Convert the input dictionary to a pandas DataFrame
        self.df = pd.DataFrame(data_dict)

        # Create a reader with the appropriate rating scale, derived from the purchase counts
        reader = Reader(rating_scale=(self.df['purchaseCount'].min(), self.df['purchaseCount'].max()))

        # Convert the DataFrame to a Surprise dataset
        self.data = Dataset.load_from_df(self.df, reader)

        # Split the data into a training and a test set for later evaluation
        self.trainset, self.testset = train_test_split(self.data, test_size=.25)

        # Initialize the Singular Value Decomposition (SVD) model
        self.model = SVD()

        # Train the SVD model using the training data
        self.model.fit(self.trainset)

    def _get_top_n_recommendations(self, predictions, n=10):
        # Create a dictionary to hold the top n item recommendations for each user
        top_n = {}

        # Process each prediction
        for uid, iid, true_r, est, _ in predictions:
            # Append item predictions for each user
            top_n.setdefault(uid, []).append((iid, est))

        # Sort and retrieve the top n items for each user
        for uid, user_ratings in top_n.items():
            user_ratings.sort(key=lambda x: x[1], reverse=True)
            top_n[uid] = user_ratings[:n]

        return top_n

    def recommend_for_user(self, user_id, n=10):
        # Build a training set from the entire dataset
        trainset = self.data.build_full_trainset()

        # Create an anti-testset: all the items that the user has not interacted with
        anti_testset = trainset.build_anti_testset()

        # Filter out interactions for all users except the target user
        anti_testset = filter(lambda x: x[0] == user_id, anti_testset)

        # Use the trained model to predict ratings for the user-item pairs in the anti-testset
        predictions = self.model.test(anti_testset)

        # Retrieve the top n items for the user based on the predictions
        top_n = self._get_top_n_recommendations(predictions, n=n)
        return [item[0] for item in top_n[user_id]]

    def evaluate(self):
        # Use the trained model to predict ratings for the test set
        predictions = self.model.test(self.testset)

        # Calculate and return the Root Mean Squared Error (RMSE) for the predictions
        return accuracy.rmse(predictions)

# # Sample usage:
# data_dict = {
#     'userID': [1, 1, 2, 2, 3, 3, 4, 4, 5, 5],
#     'itemID': ['A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'A'],
#     'purchaseCount': [5, 3, 3, 1, 1, 5, 5, 4, 4, 2]
# }

# Load data from CSV
df = pd.read_csv('test_data.csv')

# Convert DataFrame to dictionary format
data_dict = {
    'userID': df['userID'].tolist(),
    'itemID': df['itemID'].tolist(),
    'purchaseCount': df['purchaseCount'].tolist()
}

recommender = Recommender(data_dict)
print(f"RMSE: {recommender.evaluate()}")
user_id = 20
recommended_items = recommender.recommend_for_user(user_id)
print(f"Recommended items for user {user_id}: {recommended_items}")


# -*- coding: utf-8 -*-
"""
时间: 2021/2/19 11:14

作者: lixianchun@cyai.com

更改记录:

重要说明:
    结合鼠标事件，创建一个画板，可自选各种颜色画笔绘制各种图形
"""

import cv2
import numpy as np

def nothing(x):
    """回调函数

    Args:
        x(int):  滑动条的位置，即滑动条上显示的数字

    Returns:
        None

    """
    pass

drawing = False  # 当鼠标按下时变为True， 默认是False
mode = True  # mode默认为True绘制矩形，按下“m”变成绘制曲线
ix, iy = 1, -1  # 绘制起点

def draw_func(event, x, y, flags, param):
    """回调函数

    Args:
        event(int): 事件
        x(int):  起点横坐标
        y(int): 起点纵坐标
        flags(int):  事件，查看是否按下
        param:

    Returns:
        None

    """
    red = cv2.getTrackbarPos('R', 'image')
    green = cv2.getTrackbarPos('G', 'image')
    blue = cv2.getTrackbarPos('B', 'image')
    color = (blue, green, red)

    global ix, iy, drawing, mode

    if event == cv2.EVENT_LBUTTONDOWN:  # 按下左键，开始画，初始位置为起点
        drawing = True
        ix, iy = x, y
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:  # 鼠标按下并移动画矩形
        if drawing:
            if mode:
                cv2.rectangle(img, (ix, iy), (x, y), color, -1)  # 实心矩形
                # cv2.rectangle(img, (ix, iy), (x, y), color, 1)  # 空心矩形
            else:
                cv2.circle(img, (x, y), 3, color, 1)  # 半径为3的空心圆
                # 起点为圆心， 起点到终点为半径的圆（ps：鼠标移动步子小一点）
                # r = int(np.sqrt(x - ix) ** 2 + (y - iy) ** 2)
                # cv2.circle(img, (x, y), r, color, -1)  # 实心圆
    elif event == cv2.EVENT_LBUTTONUP:  # 鼠标左键松开，停止绘画
        drawing = False
    else:
        pass

img = np.zeros((512, 512, 3), np.uint8)

cv2.namedWindow('image')

# 参数一：滑动条名称；参数二：滑动条被放置窗口名称；参数三：滑动条默认位置；参数四：滑动条最大值；参数五：回调函数
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)

cv2.setMouseCallback('image', draw_func)  # 回调函数与窗口绑定

while 1:
    cv2.imshow('image', img)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('m'):  # 按下m切换模式，将键盘上的m键与模式转换绑定在一起
        mode = not mode
    elif key == 27:  # ESC
        break

cv2.destroyAllWindows()


def scan(word):
    m_list = []
    leximes = {'north': 'direction', 'south': 'direction',
                'east': 'direction', 'west': 'direction',
                'down': 'direction', 'up': 'direction',
                'left': 'direction', 'right': 'direction', 'back':'direction',
                'go': 'verb', 'stop': 'verb', 'kill': 'verb', 'eat': 'verb',
                'the': 'stop', 'in': 'stop', 'of': 'stop',
                'from': 'stop', 'at': 'stop', 'it': 'stop',
                'door': 'noun', 'bear': 'noun', 'princess': 'noun', 'cabinet': 'noun'
                }
    words = word.split()
    for word in words:
        temp = convert_number(word)
        if isinstance(temp, int):
            num_tuple = ('number', temp)
            m_list.append(num_tuple)
        else:
            word_type = leximes.get(word, 'error')
            m_list.append((word_type, word))
    return m_list

def convert_number(string):
    try:
        return int(string)
    except ValueError:
        return None

class ParserError(Exception):
    pass

class Sentence(object):

    def __init__(self, subject, verb, object):
        # remember we take ('noun','princess') tuples and convert them
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = object[1]

def peek(word_list):
    if word_list:
        word = word_list[0]
        return word[0]
    else:
        return None

def match(word_list, expecting):
    if word_list:
        word = word_list.pop(0)

        if word[0] == expecting:
            return word
        else:
            return None
    else:
        return None

def skip(word_list, word_type):
    while peek(word_list) == word_type:
        match(word_list, word_type)

def parse_verb(word_list):
    skip(word_list, 'stop')

    if peek(word_list) == 'verb':
        return match(word_list, 'verb')
    else:
        raise ParserError("Expected a verb next.")

def parse_object(word_list):
    skip(word_list, 'stop')
    next = peek(word_list)

    if next == 'noun':
        return match(word_list, 'noun')
    if next == 'direction':
        return match(word_list, 'direction')
    else:
        raise ParserError("Expected a noun or direction next.")

def parse_subject(word_list, subj):
    verb = parse_verb(word_list)
    obj = parse_object(word_list)

    return Sentence(subj, verb, obj)

def parse_sentence(word_list):
    skip(word_list, 'stop')

    start = peek(word_list)

    if start == 'noun':
        subj = match(word_list, 'noun')
        return parse_subject(word_list, subj)
    elif start == 'verb':
        # assume the subject is the player then
        return parse_subject(word_list, ('noun', 'player'))
    else:
        raise ParserError("Must start with subject, object, or verb not: %s" % start)

game_running = True
while game_running:
    parse_sentence(scan(raw_input("> ")))


import networkx as nx
import numpy as np

def graph_synth(n, p = .2):
    er_graph = nx.fast_gnp_random_graph(n, p)
    while not nx.is_connected(er_graph):
        er_graph = nx.fast_gnp_random_graph(n, p)
    return nx.adjacency_matrix(er_graph).toarray()

def varm_filter(D,x):
    p = D.shape[0]-1
    n = x.shape[0]
    m = x.shape[1]
    y = np.zeros((n,m))
    for i in range(p):
        y[i,:] = x[i,:]
        for k in range(1,i+1):
            y[i,:] = y[i,:] + np.dot(D[k,:,:],y[i-k+1,:].T).T
    for i in range(p,n):
        y[i,:] = x[i,:]
        for k in range(1,p+1):
            y[i,:] = y[i,:] + np.dot(D[k,:,:],y[i-k+1,:].T).T
    return y

def custom_AR_fit(x, P):
    N = len(x)
    r = np.correlate(x,x,mode='full')
    r = r[N-1:]/N
    A_r = np.zeros(P+1)
    A_r[0] = 1
    eps = np.zeros(P+1)
    eps[0] = r[0]
    alpha = np.zeros(P+1)
    alpha[0] = r[1]
    k = np.zeros(P+1)
    k[0] = -alpha[0]/eps[0]
    for i in range(1,P+1):
        A_r = A_r + np.concatenate(([0],k[i-1]*np.flipud(A_r[0:i]),np.zeros(P-i)))
        eps[i] = (1-k[i-1]**2)*eps[i-1]
        alpha[i] = r[i+1]
        for ii in range(1,i+1):
            alpha[i] = alpha[i] + r[(i+1)-ii]*A_r[ii]
        k[i] = -alpha[i]/eps[i]
    return A_r#, eps

def create_signals_AR(n, P, interval, inov, N, Fs, freqs, noise):
    D = np.zeros((P+1,n,n))
    D[0,:,:] = np.eye(n)
    D[P,:,:] = graph_synth(n)
    # print(D)
    # make D directed to remove unstableness
    D[P,:,:] = np.triu(D[P,:,:])
    D[P,:,:] = [[0,1,0,0,0],[0,0,1,0,0],[0],[],[]]
    x = np.zeros((N,n))
    #x is a sine wave
    for i in range(inov):
        for m in range(n):
            x[i,m] = np.sin(i*2*np.pi*freqs[m]/Fs)
    x = x + np.random.normal(0,noise,(N,n))
    y = varm_filter(D,x)
    coeffs = np.zeros((int(N/interval),P+1,n))
    for k in range(int(N/interval)):
        tmp = y[k*interval:(k+1)*interval,:]
        # errors = np.zeros((P+1,n))
        for i in range(n):
            coeffs[k,:,i] = custom_AR_fit(tmp[:,i], P)
    return coeffs, y, D[-1,:,:]#, errors


import torch
from torch.nn import functional as F

"""
Red tipo lenet para partir
"""
class LeNet5(torch.nn.Module):

    def __init__(self, n_output=21):
        super(LeNet5, self).__init__()
        #self.conv1 = torch.nn.Conv2d(in_channels=1, out_channels=6, kernel_size=3) 1 input channel
        self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=6, kernel_size=3)
        self.conv2 = torch.nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3)
        self.adapool  = torch.nn.AdaptiveMaxPool2d((5, 5))
        self.fc1 = torch.nn.Linear(in_features=16*5*5, out_features=120)
        self.fc2 = torch.nn.Linear(in_features=120, out_features=84)
        self.fc3 = torch.nn.Linear(in_features=84, out_features=n_output)
        self.activation = torch.nn.ReLU()
        self.dropout = torch.nn.Dropout(p=0.2, inplace=False)

    def forward(self, x):
        z = self.activation(self.conv1(x))
        z = F.max_pool2d(z, 2)
        z = self.activation(self.conv2(z))
        #z = F.max_pool2d(z, 2)
        z = self.adapool(z)
        z = z.view(z.size(0), -1)
        z = self.activation(self.fc1(z))
        z = self.activation(self.fc2(z))
        y = self.fc3(z)
        y = self.dropout(y)
        return y

    def save_weights(self, path):
        torch.save(self.state_dict(), path)

    def load_weights(self, path):
        self.load_state_dict(torch.load(path))

class AlexNet(torch.nn.Module):

    def __init__(self, n_output=21):
        super(AlexNet, self).__init__()
        self.features = torch.nn.Sequential(
            torch.nn.Conv2d(3, 64, kernel_size=3, stride=1),
            torch.nn.ReLU(inplace=True),
            torch.nn.MaxPool2d(kernel_size=3, stride=2),
            torch.nn.Conv2d(64, 192, kernel_size=5, padding=2),
            torch.nn.ReLU(inplace=True),
            torch.nn.MaxPool2d(kernel_size=3, stride=2),
            torch.nn.Conv2d(192, 384, kernel_size=3, padding=1),
            torch.nn.ReLU(inplace=True),
            torch.nn.Conv2d(384, 256, kernel_size=3, padding=1),
            torch.nn.ReLU(inplace=True),
            torch.nn.Conv2d(256, 256, kernel_size=3, padding=1),
            torch.nn.ReLU(inplace=True),
            torch.nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.avgpool = torch.nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = torch.nn.Sequential(
            torch.nn.Dropout(),
            torch.nn.Linear(256 * 6 * 6, 4096),
            torch.nn.ReLU(inplace=True),
            torch.nn.Dropout(),
            torch.nn.Linear(4096, 4096),
            torch.nn.ReLU(inplace=True),
            torch.nn.Linear(4096, n_output),
        )

    def forward(self, x):
        #print(x.shape) torch.Size([1, 3, 224, 224])
        x = self.features(x)
        x = self.avgpool(x)
        x = x.view(x.size(0), 256 * 6 * 6)
        x = self.classifier(x)
        return x

    def save_weights(self, path):
        torch.save(self.state_dict(), path)

    def load_weights(self, path):
        self.load_state_dict(torch.load(path))


import os
import shutil
import subprocess
import sys

STORAGE_CONF = "/tmp/storage.conf"  # NOSONAR
TEMP_DIR = "/tmp/PSCO"  # NOSONAR
JAVA_API_JAR = ""
STORAGE_API = None

def __initialize_storage() -> None:
    """Initializes the dummy storage backend.
    Compiles the dummy storage backend from the tests sources.
    Sets the JAVA_API_JAR on the first call to this initialization.

    :return: None
    """
    global JAVA_API_JAR
    global STORAGE_API
    current_path = os.path.dirname(os.path.abspath(__file__))
    # Add python storage api to sys.path
    STORAGE_API = os.path.join(current_path, "resources")
    sys.path.insert(0, STORAGE_API)
    if JAVA_API_JAR == "":
        # Compile jar
        jar_source_path = os.path.join(
            current_path,
            "..",
            "..",
            "..",
            "..",
            "..",
            "..",
            "..",
            "..",
            "..",
            "utils",
            "storage",
        )
        compile_command = ["mvn", "clean", "package"]
        process = subprocess.Popen(
            compile_command, stdout=subprocess.PIPE, cwd=jar_source_path
        )
        output, error = process.communicate()
        if error:
            print(output.decode())
            print(error.decode())
        # Set JAVA_API_JAR
        JAVA_API_JAR = os.path.join(
            jar_source_path, "dummyPSCO", "target", "compss-dummyPSCO.jar"
        )
        print("Storage api jar: " + JAVA_API_JAR)
    # Set global environment
    os.environ["CLASSPATH"] = JAVA_API_JAR + ":" + os.environ["CLASSPATH"]
    os.environ["PYTHONPATH"] = STORAGE_API + ":" + os.environ["PYTHONPATH"]
    # Prepare temporary directory
    if os.path.exists(TEMP_DIR):
        shutil.rmtree(TEMP_DIR)
    os.mkdir(TEMP_DIR)
    # Prepare storage configuration
    if not os.path.exists(STORAGE_CONF):
        with open(STORAGE_CONF, "w") as fd:
            fd.write("localhost")

def __clean_storage():
    # Remove python storage api from sys.path
    sys.path.pop(0)
    # Clean directories
    if os.path.exists(STORAGE_CONF):
        os.remove(STORAGE_CONF)
    if os.path.exists(TEMP_DIR):
        shutil.rmtree(TEMP_DIR)

def test_launch_application():
    from pycompss.runtime.launch import launch_pycompss_application

    global JAVA_API_JAR
    global STORAGE_API

    current_path = os.path.dirname(os.path.abspath(__file__))
    app = os.path.join(current_path, "resources", "storage_app", "pscos.py")
    __initialize_storage()
    launch_pycompss_application(
        app,
        "main",
        debug=True,
        app_name="pscos",
        storage_conf=STORAGE_CONF,
        storage_impl=JAVA_API_JAR,
        classpath=JAVA_API_JAR,
        pythonpath=STORAGE_API,
    )
    __clean_storage()


#проверка возможности входа в систему с корректными данными

from selenium import webdriver
import time
import urllib

try:
    #ссылка на вход и драйвер
    browser = webdriver.Opera()
    link="http://web01/Energy_test/Account/Login"
    browser.get(link)

    #ввод логина
    lg_element = browser.find_element_by_id("UserName")
    lg_element.send_keys("bel_pnpo")

    #ввод пароля
    ps_element = browser.find_element_by_id("Password")
    ps_element.send_keys("Qwerty12345")

    #нажимаем кнопку "Вход"
    button = browser.find_element_by_id("btnSignIn")
    button.click()

    #Ищем на страницу логин
    login = browser.find_element_by_class_name("user-block__fullname")
    login_text =login.text
    assert "Белкина" == login_text, "Вход не осуществлен (тест 1)"

except:
    print("Элемент не найден")

finally:
    # ожидание чтобы визуально оценить результаты прохождения скрипта
    time.sleep(10)
    # закрываем браузер после всех манипуляций
    browser.quit()


import PrimeHandler

class Factorizer(object):
	def __init__(self):
		self.alive = True

	def get_all_factors(self, num):
		if num <= 1:
			return []

		factors = []
		twos = 0
		while not num % 2:
			twos += 1
			num /= 2

		if twos:
			factors.append((2, twos))

		x = 3
		while num > 1:
			total = 0
			while not num % x:
				total += 1
				num /= x
			if total:
				factors.append((x, total))
			x += 2
		return factors

	def get_proper_divisors(self, num):
		factors = [1]

		for x in xrange(2, num/2 + 1):
			if not num % x:
				factors.append(x)

		return factors

	def get_divisors(self, num):
		return self.get_proper_divisors(num) + [num]


'''
Exercise 9-5.
---------------
Write a function named uses_all that takes a word and a string of required letters, and
that returns True if the word uses all the required letters at least once. How many words
are there that use all the vowels aeiou ? How about aeiouy'''

def usesAll(word, letters):
    for l in letters:
        if l not in word:
            return False
    return True

words = open('words.txt','r')
count = 0
letters = 'aeiou'
for word in words:
    if usesAll(word, letters):
         print(word)
         count += 1
print('%d words uses all the letters in %s at least once'%(count, letters))


from Toribash_stuff.library.toripy import *

session = login()
token = getToken(session)

transactions = []
offset = 0
# Load all transactions matching the parameters.
# All can be found here http://forum.toribash.com/showpost.php?p=7455329&postcount=26
while True:
	payload = {
		'owner_username': '',
		'ip': '',
		'date_from': '',
		'date_to': '',
		'offset': offset,
		'token': token
	}

	history = session.get(BASE_URL + '/tori_transaction_log.php?format=json', params=payload).json()
	offset += 50
	transactions.extend(
		history['transactions']
	)

	if offset > len(transactions):
		break

# Make a list of all of the loaded items' inventids.
items = [x['inventid'] for x in transactions]

# Send them all somewhere.
for i in items:
	sendItem(session, i, 'itemdump', shop_admin=True, override=True)


import numpy as np
from scipy.integrate import trapz #台形近似 https://showa-yojyo.github.io/notebook/python-scipy/integrate.html
from HestonProbZeroSigma import HestonProbZeroSigma
def HestonPriceZeroSigma(PutCall, kappa, theta, lambd, tau, K, S, r, q, Uphi, dphi, Lphi):

    # Get the integrands for the two Heston ITM probabilities p1 and p2
    phi = np.arange(Lphi, Uphi + dphi, dphi)
    P1_int = np.array([HestonProbZeroSigma(x, kappa, theta, lambd, tau, K, S, r, q, 1) for x in phi])
    P2_int = np.array([HestonProbZeroSigma(x, kappa, theta, lambd, tau, K, S, r, q, 2) for x in phi])

    # Integrate to get p1 and p2
    p1 = 0.5 + (1 / np.pi) * trapz(P1_int, phi)
    p2 = 0.5 + (1 / np.pi) * trapz(P2_int, phi)

    # Restrict p1 and p2 to the interval [0,1]
    p1 = max(min(1, p1), 0)
    p2 = max(min(1, p2), 0)

    # Heston Call price directly.
    HestonC = S * p1 * np.exp(-q * tau) - K * np.exp(-r * tau) * p2

    # Heston put price by put-call parity;
    HestonP = HestonC + K * np.exp(-r * tau) - S * np.exp(-q * tau)

    if PutCall == 'C':
        y = HestonC
    else:
        y = HestonP

    return y


from .base import Layer
from ..functions import NoActivation, Sigmoid
import numpy as np

class LSTM(Layer):
    def __init__(
        self,
        n_inputs,
        seq_length,
        n_hidden,
        n_outputs,
        activation=None,
        return_sequences: bool = False,
    ):
        self.n_inputs = n_inputs
        self.seq_length = seq_length
        self.n_hidden = n_hidden
        self.n_outputs = n_outputs
        self.sigmoid = Sigmoid()
        self.return_sequences = return_sequences
        self.activation = activation or NoActivation()

        # Forget gate weight (n_inputs + n_hidden) -> (n_hidden)
        self.Wf = np.random.randn(n_inputs + n_hidden, n_hidden) * 0.01
        # Input gate weight (n_inputs + n_hidden) -> (n_hidden)
        self.Wi = np.random.randn(n_inputs + n_hidden, n_hidden) * 0.01
        # Candidate cell state weight (n_inputs + n_hidden) -> (n_hidden)
        self.Wc = np.random.randn(n_inputs + n_hidden, n_hidden) * 0.01
        # Output gate weight (n_inputs + hidden) -> (n_hidden)
        self.Wo = np.random.randn(n_inputs + n_hidden, n_hidden) * 0.01
        # Output weight (n_hidden) -> (n_outputs)
        self.Wy = np.random.randn(n_hidden, n_outputs) * 0.01
        # biases
        self.bf = np.zeros((1, n_hidden))
        self.bi = np.zeros((1, n_hidden))
        self.bc = np.zeros((1, n_hidden))
        self.bo = np.zeros((1, n_hidden))
        self.by = np.zeros((1, n_outputs))

        self.params = ["Wf", "Wi", "Wc", "Wo", "Wy", "bf", "bi", "bc", "bo", "by"]
        self.grads = [
            "dWf",
            "dWi",
            "dWc",
            "dWo",
            "dWy",
            "dbf",
            "dbi",
            "dbc",
            "dbo",
            "dby",
        ]

    def forward(self, X, *args, **kwargs):
        self.X = X.T
        self.y = np.zeros((self.X.shape[0], self.seq_length, self.n_outputs))
        for t in range(self.seq_length):
            X_t = self.X[:, t, :]
            if t == 0:
                self.c = np.zeros((X_t.shape[0], self.n_hidden))
                self.a = np.zeros((X_t.shape[0], self.n_hidden))

            X_t = np.hstack((X_t, self.a))

            # Forget gate
            self.f = self.sigmoid.forward(X_t @ self.Wf + self.bf)

            # Input gate
            self.i = self.sigmoid.forward(X_t @ self.Wi + self.bi)

            # Candidate cell state
            self.c_ = np.tanh(X_t @ self.Wc + self.bc)

            # Update cell state
            self.c = self.f * self.c + self.i * self.c_

            # Output gate
            self.o = self.sigmoid.forward(X_t @ self.Wo + self.bo)

            # Update hidden state
            self.a = self.o * np.tanh(self.c)
            self.y_ = self.a @ self.Wy + self.by
            self.y[:, t, :] = self.activation.base(self.y_)

        if self.return_sequences:
            return self.y.T
        return self.y[:, -1, :].T

    def backward(self, dY, *args, **kwargs):
        dY = dY.T
        # Initialize gradients for each parameter
        dWf, dWi, dWc, dWo, dWy = [
            np.zeros_like(w) for w in (self.Wf, self.Wi, self.Wc, self.Wo, self.Wy)
        ]
        dbf, dbi, dbc, dbo, dby = [
            np.zeros_like(b) for b in (self.bf, self.bi, self.bc, self.bo, self.by)
        ]

        # Initialize gradients w.r.t. hidden state and cell state
        da_next, dc_next = np.zeros_like(self.a[0]), np.zeros_like(self.c)

        # Backpropagation through time
        for t in reversed(range(self.seq_length)):
            if not self.return_sequences:
                dY_t = dY if t == self.seq_length - 1 else np.zeros_like(dY)
            else:
                dY_t = dY[:, t, :]

            # Gradient w.r.t. output
            da = dY_t * self.activation.derivative(self.y_) @ self.Wy.T + da_next
            dby += np.sum(dY_t, axis=0, keepdims=True)
            dWy += self.a.T @ dY_t

            # Gradient w.r.t. hidden state
            do = da * np.tanh(self.c)
            do = do * self.sigmoid.derivative(self.o)
            dbo += np.sum(do, axis=0, keepdims=True)
            dWo += np.hstack((self.X[:, t, :], self.a)).T @ do

            # Gradient w.r.t. cell state
            dc = da * self.o * (1 - np.tanh(self.c) ** 2) + dc_next
            dc_ = dc * self.i
            dc_ = dc_ * (1 - self.c_**2)
            dbc += np.sum(dc_, axis=0, keepdims=True)
            dWc += np.hstack((self.X[:, t, :], self.a)).T @ dc_

            # Gradient w.r.t. input gate
            di = dc * self.c_
            di = di * self.sigmoid.derivative(self.i)
            dbi += np.sum(di, axis=0, keepdims=True)
            dWi += np.hstack((self.X[:, t, :], self.a)).T @ di

            # Gradient w.r.t. forget gate
            df = dc * self.c
            df = df * self.sigmoid.derivative(self.f)
            dbf += np.sum(df, axis=0, keepdims=True)
            dWf += np.hstack((self.X[:, t, :], self.a)).T @ df

            # Gradient w.r.t. input at time t
            dX_t = df @ self.Wf.T + di @ self.Wi.T + dc_ @ self.Wc.T + do @ self.Wo.T

            # Update gradients w.r.t. next hidden state and next cell state
            da_next = dX_t[:, self.n_inputs :]
            dc_next = self.f * dc

        # Store gradients
        self.dWf, self.dWi, self.dWc, self.dWo, self.dWy = dWf, dWi, dWc, dWo, dWy
        self.dbf, self.dbi, self.dbc, self.dbo, self.dby = dbf, dbi, dbc, dbo, dby

        for grad in self.grads:
            self.__dict__[grad] = -self.__dict__[grad]

        # Return gradient w.r.t. input for further backpropagation
        return dX_t[:, : self.n_inputs]


# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-

import os

def build(bld):

    # Find the kodo-c shared library in the local "lib" folder
    kodoc_path = os.path.join(bld.path.abspath(), 'lib')
    bld.read_shlib('kodoc', paths=[kodoc_path])

    def set_properties(obj):
        # Add the local 'include' folder to the normal ns-3 includes
        # The kodo-cpp headers are installed in the 'include' folder
        obj.includes = ['#', 'include']
        # shared_ptr is used in kodo-cpp so we need to add the -std=c++11 flag
        obj.cxxflags = ['-std=c++11']
        # The example uses the specified ns-3 modules and the kodo-c shared lib
        obj.use = obj.ns3_module_dependencies + ['kodoc']
        # Set the rpath to the kodo-c shared lib, so the system can find it
        # when running the example binary
        obj.rpath = [kodoc_path]
        obj.install_path = None

    # Wifi Broadcast Network Coding Example
    obj = bld.create_ns3_program('nc-wifi-broadcast',
       ['network-coding', 'applications', 'point-to-point',
       'point-to-point-layout', 'internet', 'wifi', 'netanim'])
    obj.source = 'nc-wifi-broadcast.cc'
    set_properties(obj)

    # Wired Broadcast Network Coding Example
    obj = bld.create_ns3_program('nc-wired-broadcast',
       ['network-coding', 'applications', 'point-to-point',
       'point-to-point-layout', 'internet'])
    obj.source = 'nc-wired-broadcast.cc'
    set_properties(obj)

    # Intermediate Node Recoding Example
    obj = bld.create_ns3_program('nc-recoders',
       ['core', 'applications', 'point-to-point',
       'point-to-point-layout', 'internet'])
    obj.source = 'nc-recoders.cc'
    set_properties(obj)

    # Network coding layer test Example
    obj = bld.create_ns3_program('nc-test',
       ['network-coding'])
    obj.source = ['nc-test.cc', 'nc-coding-protocol.cc']
    set_properties(obj)

    # Network coding layer test Example with recoding
    obj = bld.create_ns3_program('nc-recoding-test',
       ['network-coding', 'netanim'])
    obj.source = ['nc-recoding-test.cc', 'nc-coding-protocol.cc']
    set_properties(obj)


# pylint: disable=unused-argument

import pytest

from bookmarker.utils import user

pytestmark = pytest.mark.asyncio

class TestGetUserHandler:
    async def test_get_user_no_user(self, database, test_user_data):
        assert (
            await user.get_user(session=database, username=test_user_data.username) is None
        )  # REVIEW: check get from db manually?

    async def test_get_user_ok(self, database, created_user):
        user_model = await user.get_user(session=database, username=created_user.data.username)
        assert user_model
        assert user_model == created_user.model

class TestRegisterUserHandler:
    async def test_register_user_exists(self, database, potential_user, created_user):
        is_ok, _ = await user.register_user(session=database, potential_user=potential_user)
        assert not is_ok

    async def test_register_user_ok(self, database, potential_user):
        is_ok, _ = await user.register_user(session=database, potential_user=potential_user)
        assert is_ok

class TestDeleteUserHandler:
    async def test_delete_user_ok(self, database, created_user):
        await user.delete_user(session=database, user=created_user.model)
        user_model = await user.get_user(
            session=database, username=created_user.data.username
        )  # REVIEW: best practice?
        assert user_model is None


#def someoutput

for num in range(21):
    someoutput = ''
    if num % 3 == 0:
        someoutput += 'Fizz'
    if num % 5 == 0:
        someoutput += 'Buzz'
    if (num % 3 != 0 and num % 5 != 0):
        continue
        #someoutput = str(num)
    # need to convert int to string (duh)
    print(str(num) + " " + someoutput)


#!bin/python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import re
import sys
import tarfile
import time
import numpy as np
from six.moves import urllib
import tensorflow as tf
import picamera
import picamera.array
import cv2

FLAGS = tf.app.flags.FLAGS

model_dir='/tmp/imagenet'
num_top_predictions=1
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'

camera = picamera.PiCamera()
rawCapture = picamera.array.PiRGBArray(camera)

class NodeLookup(object):
    def __init__(self,label_lookup_path=None,uid_lookup_path=None):
        if not label_lookup_path:
            label_lookup_path = os.path.join(model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
        if not uid_lookup_path:
            uid_lookup_path = os.path.join(model_dir, 'imagenet_synset_to_human_label_map.txt')
        self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

    def load(self, label_lookup_path, uid_lookup_path):
        if not tf.gfile.Exists(uid_lookup_path):
            tf.logging.fatal('File does not exist %s', uid_lookup_path)
        if not tf.gfile.Exists(label_lookup_path):
            tf.logging.fatal('File does not exist %s', label_lookup_path)

        proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        p = re.compile(r'[n\d]*[ \S,]*')
        for line in proto_as_ascii_lines:
            parsed_items = p.findall(line)
            uid = parsed_items[0]
            human_string = parsed_items[2]
            uid_to_human[uid] = human_string

        # Loads mapping from string UID to integer node ID.
        node_id_to_uid = {}
        proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        for line in proto_as_ascii:
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])
            if line.startswith('  target_class_string:'):
                target_class_string = line.split(': ')[1]
                node_id_to_uid[target_class] = target_class_string[1:-2]

        # Loads the final mapping of integer node ID to human-readable string
        node_id_to_name = {}
        for key, val in node_id_to_uid.items():
            if val not in uid_to_human:
                tf.logging.fatal('Failed to locate: %s', val)
            name = uid_to_human[val]
            node_id_to_name[key] = name

        return node_id_to_name

    def id_to_string(self, node_id):
        if node_id not in self.node_lookup:
            return ''
        return self.node_lookup[node_id]

def create_graph():
    with tf.gfile.FastGFile(os.path.join(model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

def run_inference_on_image():
    #if not tf.gfile.Exists(image):
    #    tf.logging.fatal('File does not exist %s', image)
    #image_data = tf.gfile.FastGFile(image, 'rb').read()

      # Creates graph from saved GraphDef.
    start_time = time.time()
    create_graph()
    graph_time = time.time() - start_time
    print('Build graph time: %0.4f' % graph_time)

    with tf.Session() as sess:
        # Some useful tensors:
        # 'softmax:0': A tensor containing the normalized prediction across
        #   1000 labels.
        # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
        #   float description of the image.
        # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
        #   encoding of the image.
        # Runs the softmax tensor by feeding the image_data as input to the graph.
        softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
        node_lookup = NodeLookup()
        # MODIFICATION BY SAM ABRAHAMS
        while True:
            camera.capture(rawCapture,format="rgb")
            img = rawCapture.array
            img = cv2.resize(img, (224, 224,))
            cv2.imshow("Image",img)

            start_time = time.time()
            predictions = sess.run(softmax_tensor,
                                 {'DecodeJpeg:0': img})
            running_time = time.time() - start_time
            predictions = np.squeeze(predictions)
            top_k = predictions.argsort()[-num_top_predictions:][::-1]

            #for node_id in top_k:
            #    human_string = node_lookup.id_to_string(node_id)
            #    score = predictions[node_id]
            #    print('Test time : %.3f %s (score = %.5f)' % (running_time,human_string, score))
            human_string = node_lookup.id_to_string(top_k[0])
            print('Test time %.3f result= %s (score = %.5f)' % (running_time,human_string,predictions[top_k[0]]))
            key = cv2.waitKey(1) & 0xFF
            rawCapture.truncate(0)

def maybe_download_and_extract():
    """Download and extract model tar file."""
    dest_directory = model_dir
    if not os.path.exists(dest_directory):
        os.makedirs(dest_directory)
    filename = DATA_URL.split('/')[-1]
    filepath = os.path.join(dest_directory, filename)
    if not os.path.exists(filepath):
        def _progress(count, block_size, total_size):
            sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, float(count * block_size) / float(total_size) * 100.0))
            sys.stdout.flush()
        filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath,reporthook=_progress)
        print()
        statinfo = os.stat(filepath)
        print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
    tarfile.open(filepath, 'r:gz').extractall(dest_directory)

def main(_):
    maybe_download_and_extract()
    run_inference_on_image()

if __name__ == '__main__':
    tf.app.run()


# GovRptWordCloudV1.py
from random import randint

import jieba
import wordcloud
from scipy.misc import imread

# 设置颜色函数color_func
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = randint(120, 250)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(randint(60, 120)) / 255.0)
    # h = s = l
    # print("hsl({}, {}%, {}%)".format(h, s, l))
    # return "hsl({}, {}%, {}%)".format(h, s, l)
    # 黑色
    return "black"

mask = imread("fivestars.jpg")
f = open("关于实施乡村振兴战略的意见.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = "".join(ls)
# 生成wordcloud的对象

w = wordcloud.WordCloud(font_path="msyh.ttc", width=1000, height=700, background_color="white"
                        , max_words=15, mask=mask, color_func=random_color_func)
w.generate(txt)
w.to_file("grwordcloud11.png")