import asyncio
import logging
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor

import io
from aiohttp import web

from ept.boundingboxes import BoundingBox2D
from ept.eptresource import EPTResource
from ept.queryparams import QueryParams, sync_read_laz_files, sync_filter_las_points

logger = logging.getLogger(__name__)

RESOURCES = defaultdict(EPTResource)
POOL = ProcessPoolExecutor(8)

async def process(lazes_bytes, query):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(POOL, _process, lazes_bytes, query)

def _process(lazes_bytes, query):
    las = sync_read_laz_files(lazes_bytes)
    sync_filter_las_points(las, query)
    return _las_to_bytes(las)

def _las_to_bytes(las):
    with io.BytesIO() as buffer:
        las.write(buffer, do_compress=True)
        return buffer.getvalue()

async def las_to_bytes(las):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(None, _las_to_bytes, las)

async def get_info(request):
    name = request.match_info["resource_name"]
    address = "https://na-c.entwine.io/{}".format(name)
    ept = EPTResource(address)
    return web.json_response(await ept.info)

async def read(request):
    name = request.match_info["resource_name"]
    address = "https://na-c.entwine.io/{}".format(name)
    xmin, ymin = request.match_info['xmin'], request.match_info['ymin']
    xmax, ymax = request.match_info['xmax'], request.match_info['ymax']

    text = " ".join(a for a in (name, xmin, ymin, xmax, ymax))
    logger.info("The Query: {}".format(text))
    ept = RESOURCES[address]

    query_bounds = BoundingBox2D(int(xmin), int(ymin), int(xmax), int(ymax))
    params = QueryParams(query_bounds)

    logger.info("Downloading")
    tiles_bytes = await ept.query_tile_bytes(params)
    logger.info("Processing")
    las_bytes = await process(tiles_bytes, params)

    logger.info("Sending {} bytes".format(len(las_bytes)))
    return web.Response(body=las_bytes)

async def prepare():
    ept = EPTResource("https://na-c.entwine.io/dk")
    await ept.hierarchy
    RESOURCES["https://na-c.entwine.io/dk"] = ept

if __name__ == '__main__':
    import logging

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    loop = asyncio.get_event_loop()
    future = asyncio.ensure_future(prepare())
    loop.run_until_complete(future)

    app = web.Application()
    app.add_routes(
        [
            web.get("/info/{resource_name}", get_info),
            web.get("/read/{resource_name}/[{xmin},{ymin},{xmax},{ymax}]", read),
        ]
    )

    web.run_app(app)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests role selector widget."""
import unittest
from misura.client.tests import iutils_testing
from misura.client import widgets
from misura.canon import option
from PyQt4 import QtGui

class Role(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.root = option.ConfigurationProxy({
            'self': {'role': {'current': ['/dev/', 'default'], 'type': 'Role'},
                     'roleio': {'options': ['/dev/', 'default', 'value'], 'type': 'RoleIO'}
                     },
            'dev': {'self': {
                'name': {'type': 'String'},
                'value': {'attr': ['History'], 'type': 'Integer'},
                'value2': {'current': 2, 'attr': ['History'], 'unit': 'celsius', 'type': 'Integer'},
            }
            }
        })
        cls.root.validate()
        cls.root.dev.validate()

    def test_role(self):
        w = widgets.build(self.root, self.root, self.root.gete('role'))
        self.assertEqual(w.current, ['/dev/', 'default'])
        e = widgets.RoleEditor(w)
        self.assertEqual(e.tree.current_fullpath(), '/dev/')
        self.assertEqual(e.config.itemData(e.config.currentIndex()), 'default')
        self.assertFalse(hasattr(e, 'io'))

        iutils_testing.show(w, __name__)

    def test_io(self):
        w = widgets.build(self.root, self.root, self.root.gete('roleio'))
        self.assertEqual(w.prop['options'], ['/dev/', 'default', 'value'])
        e = widgets.RoleEditor(w)
        self.assertEqual(e.tree.current_fullpath(), '/dev/')
        ci = e.config.currentIndex()
        self.assertEqual(e.config.itemData(ci), 'default')
        ei = e.io.currentIndex()
        self.assertEqual(e.io.itemData(ei), 'value')
        e.io.setCurrentIndex(ei - 1)
        nval = e.io.itemData(e.io.currentIndex())
        e.apply()

        iutils_testing.show(w, __name__)

if __name__ == "__main__":
    unittest.main(verbosity=2)


"""
Lookout

This is the main control script for the Lookout garden monitor, responsible for executing the overall program flow (as
defined in the UML activity diagram), coordinating and timing the vision and gpio, and auxiliary functions such as
shutting down the pi when the power button is pressed.

Author: Finin Quincey
"""

import os                      # Operating system commands
import sys                     # Python system commands
import time                    # Timing functions
from datetime import datetime  # Real-world date and time
import logging as log          # Log messages and log file output
from enum import Enum          # Enumeration types
import cv2                     # OpenCV for image processing
import threading               # Concurrency
import signal                  # System exit signals

### Constants ###

FORCE_SHUTDOWN_TIME = 5 # If the power button is held for longer than this many seconds, it forces a shutdown

# N.B. Because we're using a callback approach here, we can't just have a shutdown method, we also need a way of
# preventing any callbacks from executing. The only way of doing this is to have the callback exit early when the state
# changes to shutting down. (Also, a state pattern would probably be overkill here, this is Python not Java!)
class State(Enum):
    """Enum representing the different states the program can be in"""
    INACTIVE      = "Inactive"      # Waiting to be triggered via the PIR sensor
    ACTIVE        = "Active"        # Currently recording footage
    SHUTTING_DOWN = "Shutting down" # Waiting to shut down the pi (saving and exiting)

### Initial Setup ###

# Global variables
state = State.INACTIVE
idle_timer = 0
buzzer_timer = 0
btn_hold_timer = 0

# Initialise other modules
import settings
import gpio_manager as gpio
gpio.set_power_led_state(True)
gpio.enable_pir_sensor(True)
import camera_manager as camera
import object_detector

if settings.DEV_MODE:
    camera.display_current() # Show blank screen
    cv2.waitKey(2) # For some reason it needs 2ms

### Functions ###

def on_pir_activated():
    """
    Called from the GPIO manager when the PIR sensor activates.
    """
    log.info("PIR sensor activated")
    global state
    state = State.ACTIVE

def on_power_btn_pressed(released):
    """
    Called from the GPIO manager when the power button is pressed or released.
    """
    global btn_hold_timer

    if released:

        if btn_hold_timer != 0 and time.perf_counter() - btn_hold_timer > FORCE_SHUTDOWN_TIME:

            log.warning("Forcing shutdown! Capture data may be lost!")

            if settings.DEV_MODE:
                os.kill(os.getpid(), signal.SIGINT) # sys.exit() won't work here
            else:
                os.system("sudo shutdown -h now")

        else:

            log.info("Shutting down...")

            global state
            state = State.SHUTTING_DOWN

            gpio.set_power_led_state(True)

    else:
        btn_hold_timer = time.perf_counter() # Start hold timer

def capture_video():
    """
    Captures a video from the camera until no objects are present any more (or until the buffer is full), performing object
    detection and controlling the buzzer accordingly.

    Returns:
    - True if the device should go back to sleep, False if it should shut down
    """

    global idle_timer
    global buzzer_timer

    i = 0
    measured_framerate = 0

    while True: # Capture until one of the return statements below is reached

        t = time.perf_counter()

        camera.capture_frame()

        boxes = object_detector.boxes
        labels = object_detector.labels
        scores = object_detector.scores

        if len(labels) > 0: # If we found something

            idle_timer = time.perf_counter() # Reset idle timer

            # Check objects against blacklist/whitelist
            if settings.ENABLE_BUZZER and any(item in settings.OBJECT_BLACKLIST for item in labels) and all(item1 not in settings.OBJECT_WHITELIST for item1 in labels):
                # Activate the buzzer and start the timer
                if buzzer_timer == 0: gpio.set_buzzer_frequency(settings.BUZZER_FREQUENCY)
                buzzer_timer = time.perf_counter()

        if buzzer_timer != 0 and time.perf_counter() - buzzer_timer >= settings.BUZZ_TIME: # If buzzer time has elapsed
            # Deactivate the buzzer and reset the timer
            gpio.set_buzzer_frequency(0)
            buzzer_timer = 0

        camera.annotate_current(boxes, labels, scores, measured_framerate, buzzer_timer != 0)

        if settings.DEV_MODE:
            camera.display_current()

        if not camera.store_current(): # Stop recording if the buffer is full
            log.info("Buffer full, stopping current recording")
            return True

        if time.perf_counter() - idle_timer >= settings.IDLE_TIME: # If idle time has elapsed
            return True

        if state == State.SHUTTING_DOWN:
            return False

        # LED flashing
        if i == 20:
            gpio.set_power_led_state(True)
            i = 0
        else:
            if i == 0:
                gpio.set_power_led_state(False)
            i += 1

        measured_framerate = min(settings.FRAMERATE, round(1/(time.perf_counter() - t), 1))

        # Try to keep a stable framerate by waiting for the rest of the time, if any
        cv2.waitKey(max(1, int(1000 * (1.0/settings.FRAMERATE - (time.perf_counter() - t)))))

### Finish Setup ###

log.info("Setting up callbacks")

gpio.init_pir_callback(on_pir_activated)
gpio.init_btn_callback(on_power_btn_pressed)

gpio.set_power_led_state(False)

log.info("Setup done")

### Main Logic Loop ###

while state != State.SHUTTING_DOWN: # Keep doing this until the program shuts down

    if state == State.ACTIVE:

        idle_timer = time.perf_counter() # Start idle timer

        gpio.set_ir_led_state(True)
        camera.open(settings.SAVE_DIRECTORY) # Do this as close to first capture as possible to minimise delay

        if capture_video():
            # capture_video() returned True so go back to sleep
            log.debug("Going back to sleep, goodnight")
            state = state.INACTIVE
            camera.close()
            gpio.set_buzzer_frequency(0)
            gpio.set_ir_led_state(False)

    time.sleep(0.2) # Save processing power when not doing anything

### Shutdown ###

# Shut down modules and wait for other processes to finish
gpio.prepare_shutdown() # Cancel callbacks first
object_detector.shutdown() # Start shutdown of object detector
camera.shutdown() # Wait for camera to shut down
object_detector.thread.join() # Wait until object detector has finished (it probably has already, but just in case)

# Finally, turn off the power LED and close the GPIO connection once everything is done
gpio.finish_shutdown()

log.info("*** Exiting program ***")

if settings.DEV_MODE:
    sys.exit()
else:
    os.system("poweroff")


import json
import os
import re
import time
from datetime import datetime

import requests
from fake_useragent import UserAgent
from lxml import etree

import Backend.storage.mongodb as mg
import config
import public_fun
from definitions import ROOT_DIR
from utils import bwlist
from utils.errors import updateError

def get_pdf_urls(search_keyword, page):
    """
    获取搜索结果中的文章url
    :param search_keyword: 搜素关键词
    :param page: 页数
    :return: [list of 文章 urls],
    """
    index_url2 = 'https://www.huxiu.com/article/{}.html'
    url = 'https://search-api.huxiu.com/api/article?platform=www&s={}&sort=&page={}&pagesize=20'.format(search_keyword,
                                                                                page)
    print(str(UserAgent().random))
    header = {'user-agent': str(UserAgent().random)}
    res = requests.post(url=url, headers=header)

    try:
        data = json.loads(res.text)
        result = []
        pages = data['data']['total_pages']
        for d in data['data']['datalist']:
            timeArray = time.localtime(d['dateline'])
            date = time.strftime("%Y-%m-%d", timeArray)
            if public_fun.calc_date(date) and not d['is_video_article']:  # 时间过滤且不说视文章
                result.append(index_url2.format(d['aid']))
        print('--------Found %d articles from huxiu--------' % len(result))
        print(result, pages)
        return result, pages
    except Exception as e:
        updateError("ResponseError: Empty response when downloading from huxiu. Status code: " + str(res.status_code))
        return [], 0

def download_articles(url, search_keyword, min_word_count, get_pdf, summary):
    """
    1. 网站来源 “source”（白鲸出海“bjch”/未来智库“wlzk”……）
    2. 文章ID “doc_id”（在所爬取的网页的id）
    3. 发表日期 “date”（格式：20200129）
    4. 下载url “download_url”
    5. 作者/机构 “org_name”（如 xx券商/xx证券)
    6. 页数/字数 “page_num”/ “word_count”，如果有pdf文件就用页数，没有就用字数
    7. 资料种类 “doc_type”（研报： “EXTERNAL_REPORT”/咨询： “NEWS”）
    8. 文章标题 “title” ("中芯国际：首次公开发行股票并在科创板上市招股说明书")
    :param summary: the summary file
    :param get_pdf: 是否要创建html文件
    :param min_word_count: 最少字数限制
    :param search_keyword: 搜索关键词
    :param url:url2 文章内容链接
    :return:
    """
    json_result = {'source': 'huxiu',
                   'doc_id': '',
                   'date': '',
                   'download_url': '',
                   'org_name': '',
                   'doc_type': 'NEWS',
                   'title': '',
                   'oss_path': '',
                   'has_pdf': 'html',
                   'content': '',
                   'filtered': 0,
                   'search_keyword': search_keyword}
    path = os.path.join(ROOT_DIR, 'cache', search_keyword, 'html', 'huxiu')
    header = {'user-agent': str(UserAgent().random)}
    res = requests.get(url=url, headers=header)
    html = etree.HTML(res.text)
    content_text = public_fun.filter_space_json(html.xpath('//*[@class="article__bottom-content__right fl"]//text()'))

    if len(content_text) > min_word_count:
        doc_id = re.findall('\d+', string=url)[0]  # 文章ID

        # Blacklist
        blacklist = bwlist.BWList(search_keyword, 'black')
        blacklist_exist = blacklist.bwlist_exist()

        if blacklist_exist and blacklist.in_bwlist(doc_id, 'huxiu'):
            return

        # whitelist by database
        id_match_res = mg.show_datas('articles', query={'doc_id': str(doc_id),
                                                        'search_keyword': search_keyword})  # new whitelist --vincent
        if id_match_res:
            print('article #' + str(doc_id) + ' is already in database. Skipped.')
            return

        try:
            description = html.xpath('//*[@id="article_read"]')[0]  # 文章内容
            html_list = [description]
            html_result = public_fun.filter_space_html(html_list)

            json_result['doc_id'] = doc_id
            json_result['date'] = html.xpath('//*[@class="article__time"]/text()')[0].split()[0]
            json_result['download_url'] = url
            json_result['org_name'] = html.xpath('//*[@class="author-info__username"]/text()')[0]
            json_result['title'] = html.xpath('//*[@class="article__title"]/text()')[0]
            json_result['content'] = content_text

            # Downloading
            print('Downloading article %s' % doc_id)
            public_fun.write_down_json(path=path, filename=doc_id + '.json', text=json_result)

            if get_pdf:
                public_fun.write_down_html(path=path, filename=doc_id + '.html', text=html_result)

            summary['data'].append(json_result.copy())
        except Exception as e:
            updateError(
                'Download Error: Error occurred when downloading article from huxiu. \n' + str(e.__traceback__.tb_lineno) + ": " + str(e))
    else:
        print('文章字数不足' + str(min_word_count), url)

def run(search_keyword, min_word_count, get_pdf):
    """
    铅笔道爬虫入口函数
    :param min_word_count: 最少字数限制
    :param search_keyword:搜索关键词
    :return: None
    """
    print('--------Begin searching articles from huxiu--------')
    os.chdir(ROOT_DIR)

    page = 1
    url2_list = []
    summary = {}

    summary.update({'source': '36kr'})
    summary.update({'has_pdf': 'html'})
    summary.update({'search_keyword': search_keyword})
    summary.update({'search_time': str(datetime.now().date())})
    summary.update({'data': []})

    while page:
        one_page_url, pages = get_pdf_urls(search_keyword=search_keyword, page=page)
        print(str(page) + '/' + str(pages))
        if pages == 0:
            continue
        url2_list += one_page_url
        if len(url2_list) < 1000 and page < int(pages):
            page += 1
        else:
            print(len(url2_list))
            page = 0

    url2_list = url2_list[:3] if config.DEBUG else url2_list
    for url2 in url2_list:
        download_articles(url=url2, search_keyword=search_keyword, min_word_count=min_word_count, get_pdf=get_pdf,
                          summary=summary)

    with open(os.path.join('cache', search_keyword, 'html', 'huxiu', 'summary.json'), 'w', encoding='utf-8') as f:
        json.dump(summary, f, ensure_ascii=False, indent=4)

    print('--------Finished downloading articles from huxiu--------')

if __name__ == '__main__':
    s_w = '恒大'
    run(search_keyword=s_w, min_word_count=0, get_pdf=True)


import sys

if(sys.version_info[0] < 3):
    print("This program is written with Python 3.x")
    print("Run \'Python3 filename.py\' to propperly run the program")
    sys.exit(1)

else:
    # Do work here

    def main():
        import tkinter as tk

        root = tk.Tk()

        tk.Label(root,
                text="Red Text in Times Font",
                fg = "red",
                font = "Times").pack()

        tk.Label(root,
                text="Green Text in Helvetica Font",
                fg = "light green",
                bg = "dark green",
                font = "Helvetica 16 bold italic").pack()

        tk.Label(root,
                text="Blue Text in Verdana bold",
                fg = "blue",
                bg = "yellow",
                font = "Verdana 10 bold").pack()

        root.mainloop()
        pass

    if __name__ == '__main__':
        sys.exit(main())


# Stwórz moduł, który przechowuje wzór na deltę.
# Skorzystaj z wbudowanego modułu math. W nowym pliku wykorzystaj moduł.
import math

from delta_module import calculate_delta

def enter_user_input():
    a = int(input('Enter a: '))
    b = int(input('Enter b: '))
    c = int(input('Enter c: '))
    print(f'{a}x2 + {b}x + c')
    return a, b, c

def solve_delta(a, b, c):
    calculated_delta = calculate_delta(a, b, c)
    print(f'Delta is: {calculated_delta}')
    return calculated_delta

def find_solutions(delta, a, b):
    try:
        sol1 = round((-b - math.sqrt(delta)) / (2 * a), 2)
        sol2 = round((-b + math.sqrt(delta)) / (2 * a), 2)
        print(f'First solution: {sol1}\nSecond solution: {sol2}')
    except ValueError:
        print(f'Delta {delta} has no solutions.')

if __name__ == '__main__':
    a, b, c = enter_user_input()
    delta = solve_delta(a, b, b)
    find_solutions(delta, a, b)


def solution(board, moves):
    board = [[j for j in i if j] for i in map(list, zip(*board[::-1]))]
    stack = []
    cnt = 0
    for i in moves:
        if board[i - 1]:
            stack.append(board[i - 1].pop())
        while len(stack) > 1 and stack[-1] == stack[-2]:
            stack.pop()
            stack.pop()
            cnt += 2
    return cnt


from datetime import datetime, timedelta
import pandas as pd
from peewee import fn
from database import *
from args import *

def day_interval(date):
    return (
        datetime(date.year, date.month, date.day),
        datetime(date.year, date.month, date.day) + timedelta(days=1),
    )

def report_user_call(date=None, duration=30):
    date_begin, date_end = day_interval(date or datetime.now())

    fields = [
        UsersCall.context,
        UsersCall.processname,
        fn.Count(UsersCall.id).alias('count'),
        fn.Sum(UsersCall.duration).alias('duration'),
        fn.Avg(UsersCall.duration).alias('avg'),
        fn.Max(UsersCall.duration).alias('max'),
    ]

    query = UsersCall.select(*fields).where(
            (UsersCall.date>=date_begin)
            & (UsersCall.date<date_end)
            & (UsersCall.duration>duration*1e6)
        ).group_by(UsersCall.context, UsersCall.processname).order_by(SQL('avg').desc())

    result = list(query.dicts())
    if len(result)==0:
        return "Not data"

    df = pd.DataFrame(result)

    df['duration'] = round(df['duration']/1e6, 3)
    df['avg'] = round(pd.to_numeric(df['avg'])/1e6, 3)
    df['max'] = round(df['max']/1e6, 3)

    df.columns = ['Метод', 'База', 'Количество', 'Суммарная длительность', 'Средняя длительность', 'Максимальная длительность']

    return df.to_html(classes='report')

def report_db_call(date=None, duration=30):
    date_begin, date_end = day_interval(date or datetime.now())

    fields = [
        DBCall.context,
        DBCall.processname,
        DBCall.sql,
        fn.Count(DBCall.id).alias('count'),
        fn.Sum(DBCall.duration).alias('duration'),
        fn.Avg(DBCall.duration).alias('avg'),
        fn.Max(DBCall.duration).alias('max'),
    ]

    query = DBCall.select(*fields).where(
            (DBCall.date>=date_begin)
            & (DBCall.date<date_end)
            & (DBCall.duration>duration*1e6)
        ).group_by(DBCall.context, DBCall.sql, DBCall.processname).order_by(SQL('avg').desc())

    result = list(query.dicts())
    if len(result)==0:
        return "Not data"

    df = pd.DataFrame(result)

    df['duration'] = round(df['duration']/1e6, 3)
    df['avg'] = round(pd.to_numeric(df['avg'])/1e6, 3)
    df['max'] = round(df['max']/1e6, 3)
    df.columns = ['Метод', 'База', 'Текст', 'Количество', 'Суммарная длительность', 'Средняя длительность', 'Максимальная длительность']

    return df.to_html(classes='report')

def report_app_call(date=None, duration=30):
    date_begin, date_end = day_interval(date or datetime.now())

    fields = [
        AppCall.context,
        AppCall.processname,
        fn.Count(AppCall.id).alias('count'),
        fn.Sum(AppCall.duration).alias('duration'),
        fn.Avg(AppCall.duration).alias('avg'),
        fn.Max(AppCall.duration).alias('max'),
        fn.Avg(AppCall.cputime).alias('cpu'),
    ]

    query = AppCall.select(*fields).where(
            (AppCall.date>=date_begin)
            & (AppCall.date<date_end)
            & (AppCall.duration>duration*1e6)
        ).group_by(AppCall.context, AppCall.processname).order_by(SQL('avg').desc())

    result = list(query.dicts())
    #print(result)
    if len(result)==0:
        return "Not data"

    df = pd.DataFrame(result)

    df['duration'] = round(df['duration']/1e6, 3)
    df['avg'] = round(pd.to_numeric(df['avg'])/1e6, 3)
    df['max'] = round(df['max']/1e6, 3)
    df['cpu'] = pd.to_numeric(df['cpu'])
    df.columns = ['Метод', 'База', 'Количество', 'Суммарная длительность', 'Средняя длительность', 'Максимальная длительность', "Сред.CPU"]

    return df.to_html(classes='report')

def report_app_mem(date=None, top=10):
    date_begin, date_end = day_interval(date or datetime.now())

    fields = [
        AppCall.context,
        AppCall.processname,
        fn.Count(AppCall.id).alias('count'),
        fn.Avg(AppCall.memorypeak).alias('avg'),
        fn.Max(AppCall.memorypeak).alias('max'),
    ]

    query = AppCall.select(*fields).where(
            (AppCall.date>=date_begin)
            & (AppCall.date<date_end)
        ).group_by(AppCall.context, AppCall.processname).order_by(SQL('max').desc()).limit(top)

    result = list(query.dicts())
    if len(result)==0:
        return "Not data"

    df = pd.DataFrame(result)

    df['avg'] = round(pd.to_numeric(df['avg']))
    df['max'] = df['max']
    df.columns = ['Метод', 'База', 'Количество', 'Среднее', 'Максимальное']

    return df.to_html(classes='report')

if __name__ == "__main__":
    args = get_args()
    init_database(args.psql_url, drop=False)
    report_app_call(duration=0.001)


import random, time
import os, ctypes
import ctypes,win32con

def getWallpaper():
    ubuf = ctypes.create_unicode_buffer(512)
    ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0) # ..Infow for x64
    return ubuf.value

def setWallpaper(path):
    changed = win32con.SPIF_UPDATEINIFILE | win32con.SPIF_SENDCHANGE
    ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_SETDESKWALLPAPER,0,path,changed) # ..Infow for x64

if __name__ == '__main__':
	minute = 2
	curr_wp = getWallpaper()
	wp_loc = 'imgur_scrape\\rBarn\\'
	wp_listing = os.listdir(wp_loc)
	while True:
		new_wp = random.choice(wp_listing)
		time.sleep(minute*60)
		i_suff = random.choice(wp_listing)
		if i_suff != new_wp:
			new_wp = wp_loc+i_suff
		else:
			time.sleep(minute*60)
			new_wp = random.choice(wp_listing)
		setWallpaper(new_wp)
#print(wp_listing)


# (C) 2018-2020, Tom Eulenfeld, MIT license

import numpy as np
import matplotlib.pyplot as plt
import re

def _f(B, x):
    """Linear function y=m*x+b"""
    return B[0]*x + B[1]

def odr_regr(x, y):
    """Orthogonal distance regression, return m and b of line y=m*x+b"""
    from scipy.odr import Data, Model, ODR
    linear = Model(_f)
    mydata = Data(x, y, wd=1, we=1)
    myodr = ODR(mydata, linear, beta0=[1., 2.])
    res = myodr.run()
    return res.beta

def project_coordinates(x, y, m, b):
    """Project coordinates x,y onto line y=mx+b"""
    # direction of line (1, m)
    c = (1 * x + m * (y - b)) / (1 + m ** 2)
    return 1 * c, m * c + b

def plot_projection(x, y, xp, yp, m, b, fname=None):
    """Plot projection

    x,y: coordinates
    xp,yp: projected coordinates
    m,b: line y=m*x+b
    """
    plt.figure()
    plt.plot(x, y, '.')
    plt.plot(x, m*np.array(x)+b)
    plt.plot(xp, yp, '.')
    plt.axis('scaled')
    if fname:
        plt.savefig(fname)

def plot_html(fname_in, fname_out, zone=None, delimiter=',', encoding=None,
              color=None, color_func=None, reverse=False, **kw):
    """Plot html of coordinates in fname_in"""
    import folium
    import utm
    data = np.genfromtxt(fname_in, dtype=None, delimiter=delimiter, encoding=encoding, **kw)
    names, x, y, z, *_ = list(zip(*reversed(data))) if reverse else zip(*data)
    x0 = np.mean(x)
    y0 = np.mean(y)
    latlon0 = utm.to_latlon(x0, y0, *zone) if zone else (y0, x0)
    m = folium.Map(location=latlon0, zoom_start=15, max_zoom=20, control_scale=True)
    m.add_child(folium.LatLngPopup())
    for name, xp, yp, zp in zip(names, x, y, z):
        if color is None and color_func is None:
            c = '#3186cc'
        elif color is None:
            c = color_func(name)
        else:
            c = color
        latlon = utm.to_latlon(xp, yp, *zone) if zone else (yp, xp)
        folium.CircleMarker(latlon, radius=1,
                            popup='%s %.5f %.5f %.2f' % (name, latlon[0], latlon[1], zp),
                            color=c, fill_color=c
                            ).add_to(m)
    m.save(fname_out)

def read_coords(fname, delimiter=',', sort=True):
    """Read coordinates in fname

    name, x, y, z
    """
    data = np.genfromtxt(fname, dtype=None, encoding=None, delimiter=delimiter)
    names, x, y, z, *_ = zip(*data)
    nums = [int(re.sub('[a-zA-Z]+', '', name)) for name in names]
    if sort:
        ind = sorted(range(len(names)), key=lambda i: nums[i])
        nums = [nums[i] for i in ind]
        names = [names[i] for i in ind]
        x = [x[i] for i in ind]
        y = [y[i] for i in ind]
        z = [z[i] for i in ind]
    return names, np.array(nums), np.array(x), np.array(y), np.array(z)

def test_project_coords():
    x =  np.arange(10)
    y = 0.5 * x + 10 + 2*np.random.random(10)
    m, b = odr_regr(x, y)
    xp, yp = project_coordinates(x, y, m, b)
    plot_projection(x, y, xp, yp, m, b)

def write_geo(x, y, z, x0, y0, sps, fname1, fname2, rec0=1, sort=False,
              xyzs=None, shot0=1):
    """Write profil files (receivers and shots)

    x,y,z: profile coordinates
    x0,y0: profile in m relative to this coordinates
    fname1,fname2: file name for receivers, shots
    sps: shotpoints - geofon dictionary from read_shotpoints
    rec0,shot0: Start number of receivers/shots
    xyzs: sps can be set to None. Then, use xyzs.
          tuple of profile coordinates of shotpoints,
          (x, ys, zs)
    """
    fmt = '%3d  %8.3f  %8.3f'
    pos = ((x - x0) ** 2 + (y - y0) ** 2) ** 0.5
    num = np.arange(len(x)) + rec0

    if xyzs is not None:
        x2, y2, z2 = xyzs
        pos2 = ((x2 - x0) ** 2 + (y2 - y0) ** 2) ** 0.5
        num2 = np.arange(len(x2)) + shot0
    elif sps is not None:
        shot_ind=np.array(list(sps.values())) - 1
        num2 = sps.keys()
        pos2 = pos[shot_ind]
        z2 = z[shot_ind]
    else:
        raise

    if sort:
        z = [a for _, a in sorted(zip(pos, z))]
        z2 = [a for _, a in sorted(zip(pos2, z2))]
        pos = sorted(pos)
        pos2 = sorted(pos2)
    np.savetxt(fname2, list(zip(num2, pos2, z2)), fmt=fmt)
    np.savetxt(fname1, list(zip(num, pos, z)), fmt=fmt)

def profilemeter2xy(meters, x, y, print_lines=False):
    dy = y[-1] - y[0]
    dx = x[-1] - x[0]
    alpha = np.arctan2(dy, dx)
    res = [(meter * np.cos(alpha) + x[0],
            meter * np.sin(alpha) + y[0]) for meter in meters]
    if print_lines:
        for i, (x2, y2), in enumerate(res):
            print(f'x{i}={x2:.3f} y{i}={y2:.3f} z{i}=',)
    return res

def interpolate_geophones(nums, x, y, z, nnums=None):
    if nnums is None:
        nnums = np.arange(nums[0], nums[-1]+1)
    res = [np.interp(nnums, nums, coordpart) for coordpart in (x, y, z)]
    return res

if __name__ == '__main__':
    test_project_coords()


import math as m
a = float(input("Введите число a: "))
b = float(input("Введите число b: "))
c = float(input("Введите число c: "))
if a == 0 and b != 0 and c != 0:
    x = -(c/b)
    print("x =", '{:.4f}'.format(x))
elif a == 0 and b == 0 and c != 0:
    print("Нет корней")
elif a == 0 and b == 0 and c == 0:
    print("x - любое число")
elif a == 0 and b != 0 and c == 0:
    x = 0/b
    print("x = ", '{:.4f}'.format(x))
else:
    d = b**2 - 4 * a * c
    if d > 0:
        x1 = (-b + m.sqrt(d)) / (2 * a)
        x2 = (-b - m.sqrt(d)) / (2 * a)
        print("x1 =", '{:.4f}'.format(x1), "и", "x2 =", '{:.4f}'.format(x2))
    elif d == 0:
        x = -b / (2 * a)
        print("x =", '{:.4f}'.format(x) )
    else:
        print("Нет корней")


from pythonic_testcase import *

from mediadrop.model import DBSession, Media
from mediadrop.lib.filetypes import VIDEO
from mediadrop.lib.i18n import setup_global_translator
from mediadrop.lib.storage.api import add_new_media_file
from mediadrop.lib.test.db_testcase import DBTestCase
from mediadrop.players import AbstractFlashPlayer, FlowPlayer
from mediadrop.plugin import events
from mediadrop.plugin.events import observes

class MediaTest(DBTestCase):
    def setUp(self):
        super(MediaTest, self).setUp()
        setup_global_translator(registry=self.paste_registry)
        self.init_flowplayer()
        self.media = Media.example()
        self.encoding_event = self.create_spy_on_event(events.Media.encoding_done)

    def init_flowplayer(self):
        AbstractFlashPlayer.register(FlowPlayer)
        FlowPlayer.inject_in_db(enable_player=True)

    def create_spy_on_event(self, event):
        encoding_event = create_spy()
        observes(event)(encoding_event)
        return encoding_event

    def add_external_file(self, media, url=u'http://site.example/videos.mp4'):
        previous_files = len(media.files)
        media_file = add_new_media_file(media, url=url)
        # add_new_media_file will set media_file.media AND media.files.append
        # so we have two files for the media until the session is refreshed.
        DBSession.refresh(media)
        assert_length(previous_files+1, media.files)
        return media_file

    def test_can_update_status(self):
        assert_false(self.media.encoded)

        self.media.update_status()
        assert_false(self.media.encoded)
        self.encoding_event.assert_was_not_called()

    def test_triggers_event_when_media_was_encoded(self):
        self.add_external_file(self.media)
        assert_false(self.media.encoded)
        self.media.update_status()

        assert_equals(VIDEO, self.media.type)
        assert_true(self.media.encoded)
        self.encoding_event.assert_was_called_with(self.media)

        # only send event when the encoding status changes!
        second_encoding_event = self.create_spy_on_event(events.Media.encoding_done)
        self.media.update_status()
        second_encoding_event.assert_was_not_called()

    def test_can_generate_plain_text_description_automatically(self):
        expected_plaintext = u'foo bar baz'
        assert_not_equals(expected_plaintext, self.media.description_plain)

        self.media.description = u'
foo bar baz
'
        assert_equals(expected_plaintext, self.media.description_plain)

import unittest
def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(MediaTest))
    return suite

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


#Importing
import matplotlib.pyplot as plt

life_exp = [45,46,45,23,45,67,86,54,75,86,54,87,46,23,45,87,99,65,76,57,56,33]
# Build histogram with 5 bins
plt.hist(life_exp,bins=5)

# Show and clean up plot
plt.show()
plt.clf()

# Build histogram with 20 bins
plt.hist(life_exp,bins=20)

# Show and clean up again
plt.show()
plt.clf()

1 Graphical Analysis/1 Making_Multiple_Graphs_Together.py


from __future__ import print_function
import datetime
from flask import Flask, request, jsonify
import pickle
from flask_cors import CORS
import os.path
import json
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']

app = Flask(__name__)
CORS(app)
cors = CORS(app, resources={r'/*': {'origins': '*'}})
@app.route('/event', methods=["GET", "POST"])
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    content = json.loads(request.data)
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)
    if(service):

            event = {
            'summary': content['summary'],
            'location': content['location'],
            'start': {
                'dateTime': content['stime']+":00",
                'timeZone': 'Asia/Kolkata',
                },
            'end': {
                'dateTime': content['etime'] + ":00",
                'timeZone': 'Asia/Kolkata',
                },
            'attendees': [
                {'email':content['firstemail']},
                {'email': content['secondemail']},
                {'email': content['thirdemail']}
                  ]
        }
            event = service.events().insert(calendarId='primary', body=event).execute()
            print ('Event created: %s' % (event.get('htmlLink')))
            return ("Event created")

    else:
        return("Event not created pls try after some time")

if __name__ == '__main__':
    app.run(threaded=True, debug=True)


import os
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import Sequence
from specinput import params

if os.path.exists('./class-freqs.npy'):
    spf = np.load('./class-freqs.npy')
    spf = {i:[j,k] for (i,j,k) in spf}
else:
    print('Cannot find class-freqs.npy. Please generate the file using get-class-frequencies.ipynb')

class TestDataGenerator(Sequence):
    """Generates spectrogram batches

    Args:
        list_IDs: list of paths to spectrogram files
        dim: (tuple) dimensions of input spectrograms
        resize_dim: (tuple) desired shape of generated images
        batch_size: (int) number of samples per batch
        augment: (boolean) whether to apply data augmentation
        shuffle: (boolean) whether to shuffle the training data after each epoch

    """
    def __init__(self,
                 list_IDs,
#                  labels,
                 dim = (224, 393), # shape of a single patch
                 resize_dim = None,
                 batch_size=1,
                 augment=False,
                 shuffle=True):
        'Initialization'
        self.batch_size = batch_size
        self.dim = dim
        self.resize_dim = resize_dim
        self.list_IDs = list_IDs
        self.augment = augment
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        """Generates one batch of data

        Args:
            index: index of the desired batch

        Returns:
            X: images [<# samples>, <# rows>, <# columns>, <# channels>]
            list_IDs_temp: list of file names

        """
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X = self.__data_generation(list_IDs_temp)

        return X, list_IDs_temp

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)

        # Initialize image arrays
        if self.resize_dim:
            X = np.empty((self.batch_size, *self.resize_dim, 3))
        else:
            X = np.empty((self.batch_size, *self.dim, 3))

        # Generate data
        for i, ID in enumerate(list_IDs_temp):

            sample = np.load(ID, allow_pickle=True)

            # Random time shift up to 1 second
            # Random frequency shift up to 1%
            sample_frames =int(params.sample_seconds/params.stft_hop_seconds)
            if self.augment:
                shft = int(np.random.choice(range(0, int(2/params.stft_hop_seconds)),1)[0])
                sample = sample[:,shft:(shft+sample_frames),:]
                sample = np.roll(sample, np.random.choice(int(sample.shape[0]*0.01)), axis=0)
            else:
                sample = sample[:,int(1/params.stft_hop_seconds):(int(1/params.stft_hop_seconds)+sample_frames),:]

            # dB-scaling
            sample = scalespec(sample)

            # Image preprocessing
            sample = preprocess(tf.convert_to_tensor(sample), resize_dim=self.resize_dim)

            X[i,] = sample

        if self.augment:
            if np.random.uniform(0,1)<0.5:
                X = mixup(X, prob=1)
            else:
                X = cutmix(X, prob=1)

        return X

def scalespec(x, log_offset=0.001):
    """Applies log-scaling to an input amplitude spectrogram

    Args:
        log_offset: offset to add to the input spectrogram to avoid log(0)

    Returns:
        x: log-scaled spectrogram

    """
    return 10*np.log10(x+log_offset)

def preprocess(image, resize_dim=(224, 224)):
    """Preprocesses a greyscale image (spectrogram) for input to a pre-trained ImageNet CNN

    Args:
        resize_dim: desired shape of output image

    Returns:
        image: pre-processed image

    """
    image = tf.image.grayscale_to_rgb(image)
    image = tf.image.resize(image, resize_dim)
    image = tf.image.per_image_standardization(image)
    return image

def mixup(X, prob = 1.0):
    """Applies mixup augmentation to a batch of images

    Mixup augmenation from: https://arxiv.org/pdf/1710.09412.pdf

    Args:
        prob: probability of applying mixup per sample

    Returns:
        X: batch with mixup applied

    """
    # input X - is a batch of images of size [n,height,width,channels]
    # output - a batch of images with cutmix applied
    batch = np.copy(X)
    for j in range(batch.shape[0]):

        # do mixup with specified probability
        if tf.random.uniform([],0,1)<prob:

            # pick another sample
            idx = j
            while idx==j:
                idx = tf.random.uniform([],0,batch.shape[0],dtype=tf.int32)

            # combine
            a = tf.random.uniform([],0.0,1.0)
            batch[j,] = X[j,]*a + X[idx,]*(1-a)

    return batch

def cutmix(X, prob = 1.0):
    """Applies cutmix augmentation to a batch of images

    Cutmix augmentation inspired by: https://arxiv.org/abs/1905.04899

    This augmentation cuts out the frequency band of a labeled species, and mixes only that band with another sample. This implementation also mixes using the maximum value at each pixel.

    Args:
        prob: probability of applying mixup per sample

    Returns:
        X: batch with mixup applied
    """
    # input X - is a batch of batchs of size [n,height,width,channels]
    # output - a batch of batchs with cutmix applied
    batch = np.copy(X)

    for j in range(batch.shape[0]):

        # do cutmix with specified probability
        if tf.random.uniform([],0,1)<prob:

            # pick another sample
            idx = j
            while idx==j:
                idx = tf.random.uniform([],0,batch.shape[0],dtype=tf.int32)

            # combine
            batch[j, int(spf[ids[idx]][0]):int(spf[ids[idx]][1])+1, :] = np.maximum(X[j, int(spf[ids[idx]][0]):int(spf[ids[idx]][1])+1, :], X[idx, int(spf[ids[idx]][0]):int(spf[ids[idx]][1])+1, :])

    return batch


a = [1, 2, 3]
# solution 1
for i in a:
    print('Item %s has index %s' % (i, i - 1))

# solution 2
for index, item in enumerate(a):
    print("Item %s has index %s" % (item, index))

# enumerate creates an enumerate object which yields pairs of indexes and items.


import csv
from typing import Tuple, Set, Dict
from pathlib import Path

import numpy as np
from pygame import Surface

from game.cell import Cell
from game.configs import Colors

class CellPosition(object):
    """Stores a cell position in a board, in units"""

    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash(self.__repr__())

    def __repr__(self):
        return f"CellPosition( x = {self.x}, y = {self.y} )"

    def as_tuple(self) -> Tuple[int, int]:
        return self.x, self.y

def get_position_neighbours(position: 'CellPosition') -> Set['CellPosition']:
    neighbours: Set[CellPosition] = {
        CellPosition(position.x - 1, position.y - 1),
        CellPosition(position.x, position.y - 1),
        CellPosition(position.x + 1, position.y - 1),
        CellPosition(position.x + 1, position.y),
        CellPosition(position.x + 1, position.y + 1),
        CellPosition(position.x, position.y + 1),
        CellPosition(position.x - 1, position.y + 1),
        CellPosition(position.x - 1, position.y)}        # Left

    return neighbours

class Board(object):

    def __init__(self, columns: int, rows: int, cell_side: int,
                 window_size: Tuple[int, int]):

        self.columns = columns
        self.rows = rows
        self.cell_side = cell_side
        self.window_size = window_size

        self.window = Surface(window_size)
        self.window.fill(Colors.BLACK)

        self.board: np.array = np.array([
            [Cell(self.cell_side, (row * cell_side, column * cell_side))
             for column in range(rows)]
            for row in range(columns)
        ])

        self.active_cells: Set[CellPosition] = set()

    def reset(self):
        for cell_position in self.active_cells:
            self.board[cell_position.as_tuple()].die()

    def render(self, window: Surface, position: Tuple[int, int]):

        [[cell.render(self.window) for cell in column] for column in self.board]
        window.blit(self.window, position)

    def handle_click(self, x: int, y: int):

        cell_x = int(x / self.cell_side)
        cell_y = int(y / self.cell_side)
        cell_position = CellPosition(cell_x, cell_y)

        self.board[cell_position.as_tuple()].change_state()

        if self.board[cell_position.as_tuple()].is_alive():
            self.active_cells.add(CellPosition(cell_x, cell_y))
        else:
            self.active_cells.remove(CellPosition(cell_x, cell_y))

    def get_alive_neighbours(self, position: CellPosition) -> int:
        alive_neighbours = 0
        for neighbour in get_position_neighbours(position):
            if self.valid_position(neighbour):
                alive_neighbours += int(self.board[neighbour.as_tuple()].is_alive())

        return alive_neighbours

    def valid_position(self, position: CellPosition):
        x_valid = 0 <= position.x < self.columns
        y_valid = 0 <= position.y < self.rows

        return x_valid and y_valid

    def update_state(self):
        cells_alive_neighbours: Dict[CellPosition, int] = {}
        for active_cell in self.active_cells:

            if active_cell not in cells_alive_neighbours:
                cells_alive_neighbours[active_cell] = self.get_alive_neighbours(active_cell)

            for neighbour in get_position_neighbours(active_cell):
                if neighbour not in cells_alive_neighbours and self.valid_position(neighbour):
                    cells_alive_neighbours[neighbour] = self.get_alive_neighbours(neighbour)

        new_alive: Set[CellPosition] = set()
        for cell_position, alive_neighbours in cells_alive_neighbours.items():
            cell = self.board[cell_position.as_tuple()]
            cell.update(alive_neighbours)
            if cell.is_alive():
                new_alive.add(cell_position)

        self.active_cells = new_alive

    def load_board(self, board_file: Path):
        self.reset()
        with open(board_file, "r", newline="") as f:
            reader = csv.reader(f)

            for y, row in enumerate(reader):
                for x, value in enumerate(row):
                    if value == "1":
                        self.board[(x, y)].populate()
                        self.active_cells.add(CellPosition(x, y))

    def save_board(self, board_file: Path):
        with open(board_file, "w", newline="") as f:
            writer = csv.writer(f)

            for y in range(self.rows):
                write_row = []
                for x in range(self.columns):
                    if self.board[(x, y)].is_alive():
                        write_row.append("1")
                    else:
                        write_row.append("0")
                writer.writerow(write_row)


#!/usr/bin/env python
# encoding: utf-8
from flask import Flask, jsonify, request, send_file
app = Flask(__name__)

import os
# import gnews
import openai # added
from langchain.chat_models import ChatOpenAI
from dotenv import load_dotenv
# from datetime import datetime
# import requests
# import datetime
load_dotenv()
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from moviepy.editor import concatenate_audioclips, AudioFileClip
import uuid
# from elevenlabs import voices, generate, play, save

openai.api_key = os.getenv("OPENAI_API_KEY")
weather_api_key = os.getenv("WEATHER_API_KEY")
ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")
# # Initialize chat model
chat_model = ChatOpenAI(model_name='gpt-3.5-turbo-16k')  # Make sure to set the API key as an environment variable

class Podcast:
    def __init__(self, user_prompt, num_minutes, category):
        self.ID = generate_name()
        self.user_prompt = user_prompt
        self.num_minutes = int(num_minutes)
        self.num_words = int(num_minutes) * 135
        self.category = category
        self.text_list = []
        self.sound_file_name = self.ID + ".wav"
        self.drive_name = ""

    def get_ID(self):
        return self.ID

    def get_drive_name(self):
        return self.drive_name

    def gen_story_podcast(self):

        if self.num_words < 1000:
            prompt = "Create a story about '{}'. The story should be approximately {} number of words".format(self.user_prompt, self.num_words)
            self.text_list = [chat_model.predict(prompt)]
            print("--------")
            print(self.text_list)
        else:
            chapters = int(self.num_words / 300)
            prompt = "Create a detailed outline for a story about '{}' with {} scenes. Return your answer in the following format:".format(self.user_prompt, str(chapters*3))
            for i in range(1, 3*chapters+1):
                prompt += "\nScene {}:".format(str(i))

            outline = chat_model.predict(prompt)
            scene_list = []
            for i in range(1, chapters*3+1):
                scene_before_index = outline.index("Scene {}".format(str(i)))
                if i < chapters*3:
                    scene_after_index = outline.index("Scene {}".format(str(i+1)))
                    scene = outline[scene_before_index:scene_after_index]
                else:
                    scene = outline[scene_before_index:]
                scene_list.append(scene)

            prompt = "Specify the characters and in what scene they enter the story based on this outline:\n{}\n\nReturn in the format:\nName of character - Description - Scene Number".format(outline)
            characters = chat_model.predict(prompt)
            extended_scenes = []

            for i in range(chapters):
                number_of_scenes = 3
                response_format = "Return in the format:\nPart {}:\nPart {}:\nPart {}:".format(str(i*3+1), str(i*3+2), str(i*3+3))
                scenes = scene_list[i*3] + "\n" + scene_list[i*3+1] + "\n" + scene_list[i*3+2]
                if i < chapters - 1:
                        scenes += "\n" + scene_list[i*3+3]
                        response_format += "\nPart {}:".format(str(i*3+4))
                        number_of_scenes = 4

                #prompt = "Turn these {} scenes into storytelling format, add details, return just the text:\n{}\n\nHere is a list of characters and in what scene they will or have been introduced:\n{}\n\n{}".format(str(number_of_scenes), scenes, characters, response_format)
                prompt = "Here are the story's characters and in what scenes they appear:\n{}\n\nRewrite the following scenes into a plain text story that can written in a book. Add unnecessary details so the story feels more alive:\n{}\n\n{}".format(characters, scenes, response_format)
                response = chat_model.predict(prompt)

                k = 0
                for j in range(i*3+1,i*3+number_of_scenes+1):
                    k += 1
                    scene_before_index = response.lower().index("part {}".format(str(j)))
                    if j < i*3+number_of_scenes:
                        scene_after_index = response.lower().index("part {}".format(str(j+1)))
                        scene = response[scene_before_index:scene_after_index]
                    else:
                        scene = response[scene_before_index:]

                    if k < 4:
                        extended_scenes.append(scene)

            cleaned_text = []
            for row in extended_scenes:
                split_row = row.split("\n")[1:]  # Remove the first element
                restored_row = "\n".join(split_row)  # Join the remaining elements with newline
                restored_row = restored_row.strip("\n")
                cleaned_text.append(restored_row)

            self.text_list = cleaned_text
            print("--------")
            print(self.text_list)

    def audiofy_story(self, voice="Adam", sound_effect_name="fairytale"):

        if not os.path.exists("story_audio"):
            os.makedirs("story_audio")

        file_names = []
        # for i in range(len(self.text_list)):
        #     audio = generate(text=self.text_list[i], voice=voice, model="eleven_monolingual_v1", api_key=ELEVEN_API_KEY)
        #     save(audio, "./story_audio/story_{}_{}.wav".format(self.ID, str(i)))

        #     file_names.append("./story_audio/story_{}_{}.wav".format(self.ID, str(i)))
        #     file_names.append("./sound_effects/{}.wav".format(sound_effect_name))

        # file_names = ["./sound_effects/fairytale.wav","./sound_effects/fairytale.wav"]
        file_names = ["./sound_effects/original_transition.wav","./sound_effects/original_transition.wav"]
        concatenate_audio_moviepy(file_names, "./story_audio/{}".format(self.sound_file_name))

    def upload_wav_file_and_get_ID(self):
        print(777777)
        gauth = GoogleAuth()

        # Try to load saved client credentials
        gauth.LoadCredentialsFile("mycreds.txt")

        if gauth.credentials is None:
            # Authenticate if they're not there
            gauth.GetFlow()
            gauth.flow.params.update({'access_type': 'offline'})
            gauth.flow.params.update({'approval_prompt': 'force'})
            gauth.LocalWebserverAuth()
        elif gauth.access_token_expired:
            # Refresh them if expired
            gauth.Refresh()
        else:
            # Initialize the saved creds
            gauth.Authorize()

        # Save the current credentials to a file
        gauth.SaveCredentialsFile("mycreds.txt")

        drive = GoogleDrive(gauth)

        title = generate_name() + ".txt"
        team_drive_id = '1WdeZhQ_vegXPMA-JeoM0pldAOKbCCVcx'
        parent_folder_id = '1TtWk3uo0jTC0BR2CAlaH8DgcRtp0hDCb'
        f = drive.CreateFile({
            'title': title,
            'parents': [{
                'kind': 'drive#fileLink',
                'teamDriveId': team_drive_id,
                'id': parent_folder_id
            }]
        })
        f.SetContentFile("./story_audio/" + self.sound_file_name)
        f.Upload(param={'supportsTeamDrives': True})

        files = drive.ListFile({"q": "'" + parent_folder_id + "' in parents and mimeType!='application/vnd.google-apps.folder'"}).GetList()

        name = ""
        for file in files:
            if file['title'] == title:
                name = file['id']

        self.drive_name = name

    def list_to_text(self):
        text = ""
        for row in self.text_list:
            text += row + "\n"
        return text

def generate_name():
    # Generate a unique ID
    unique_id = str(uuid.uuid4())
    return unique_id

def concatenate_audio_moviepy(audio_clip_paths, output_path):
        """Concatenates several audio files into one audio file using MoviePy
        and save it to `output_path`. Note that extension (mp3, etc.) must be added to `output_path`"""
        clips = [AudioFileClip(c) for c in audio_clip_paths]
        final_clip = concatenate_audioclips(clips)
        final_clip.write_audiofile(output_path)

@app.route('/')
def home():
    return 'Hello, World adam!'

@app.route('/about')
def about():
    return 'adam test'

@app.route('/create')
def get_create():
    print(00000)

    # Argument fetched from url params
    user_prompt = request.args.get('topic') # User input can be any string
    num_minutes = request.args.get('min') # Time [0-5, 5-10, 10-15]
    podcast_type = request.args.get("style") # style ["NEWS", "STORY"]
    # num_words = int(num_minutes)*135

    # Pausar detta för tillfället
    # prompt = "Can you create a documentary/news broadcast/podcast/fantasy story about this input? Respond only by returning 'YES' or explain why it does not work. Input = {}".format(user_prompt)
    # response = chat_model.predict(prompt)
    # if "YES" != response:
    #     return print(response)

    new_podcast = Podcast(user_prompt, num_minutes, podcast_type)

    if podcast_type == "NEWS":
        # Todo fix
        print("IN NEWS")
        podcast_name = temp_gen()
        data = {'text': "TODO", 'name': podcast_name}
        return jsonify(data)
    elif podcast_type == "STORY":
        new_podcast.gen_story_podcast()
        new_podcast.audiofy_story()
        new_podcast.upload_wav_file_and_get_ID()

    data = {'text': new_podcast.list_to_text(), 'name': new_podcast.get_drive_name()}

    return jsonify(data)


import math
from time import time as current_time

from logger import Logger
from camera import Camera
from crash_reporter import AccidentReporter, Accident
from car import Car, CarInfo, CrashDetectorCallback, InterruptionService

from threading import Event

from constants import IS_TESTING, FirebaseConstants

if IS_TESTING:
    # Use emulated GPS
    from pc_toolkit import GPS
else:
    # Use actual GPS module
    from gps import GPS

class AASSL(CrashDetectorCallback, InterruptionService.Callback):

    def __init__(self) -> None:
        self.logger = Logger('AASSL')
        self.setup_signal = Event()
        self.running_signal = Event()
        self.logger.info("Creating AASSL instance...")

        # Car
        self.car = Car(CarInfo.get_default(), self)

        # AccidentReporter
        self.crash_reporter = AccidentReporter()

        # Camera
        self.camera = Camera(duration=5)
        if self.camera is None:
            self.logger.error("No camera was detected.")

        # GPS
        self.gps = GPS()
        if self.gps is None:
            self.logger.error("No GPS module was detected.")

        # InterruptionService
        self.interruption_service = InterruptionService(self)

        self.logger.success("Created AASSL instance. Waiting for setup...")

    def system_ready(self):
        return self.setup_signal.is_set()

    def system_running(self):
        return self.running_signal.is_set()

    def setup_system(self):
        if self.system_ready():
            self.logger.warning("System setup already done.")
            return

        try:
            self.car.setup()
            self.gps.setup()
            self.camera.setup()
            self.crash_reporter.setup()

            self.setup_signal.set()
        except KeyboardInterrupt:
            self.logger.error("SETUP WAS INTERRUPTED")
        except Exception as e:
            if isinstance(e, FileNotFoundError):
                self.running_signal.clear()
                self.logger.error(f"Couldn't find firebase config at path: '{FirebaseConstants.CREDENTIALS_FILE_PATH}'")
            self.logger.error("One or more system components failed to setup. {}".format(e))

    def start_system(self):
        if not self.system_ready():
            self.logger.warning("System isn't ready yet. Please setup the system first.")
            return

        if self.system_running():
            self.logger.warning("System is already running.")
            return

        try:
            self.running_signal.set()
            self.logger.info("Starting system...")
            # Start system components
            self.car.start()
            self.gps.start()
            self.camera.start()
            self.interruption_service.start()
        except Exception:
            self.running_signal.clear()
            self.logger.error("One or more system components failed to start.")

    def stop_system(self):
        if not self.system_running():
            self.logger.warning("System isn't running to stop it.")
            return
        try:
            self.running_signal.clear()
            self.logger.info("Stopping system...")
            # Stop system components
            self.car.stop()
            self.gps.stop()
            self.camera.stop()
            self.logger.info("System stopped.")
        except:
            self.logger.error("One or more system components failed to stop.")
        finally:
            # Exit
            exit(0)

    def on_interrupt(self):
        self.logger.info("SYSTEM WAS INTERRUPTED.")
        return self.stop_system()

    def on_accident_happened(self):
        self.logger.info("Received crash signal from CrashDetector. Handling it...")
        # Wait until camera is initialized if it not
        if not self.camera.initialized:
            self.logger.info("Waiting for camera to initialize.")
            self.camera.initialized_signal.wait()
            self.logger.info("Camera is initialized.")
        # Build accident model
        timestamp = math.floor(current_time() * 1000)  # Timestamp in millis
        self.camera.resume()
        # Get before accident video buffer from camera
        self.logger.info("Capturing before accident video...")
        self.camera.wait_until_buffer_filled()

        self.camera.suspend()
        buffer_before_accident = self.camera.video_buffer.clone()
        self.logger.info("Grabbed before accident video buffer: {}".format(buffer_before_accident))

        # Resume the camera
        self.camera.video_buffer.clear()
        self.logger.info("Capturing 5 secs after accident...")
        # Wait for camera to capture the next 5 secs video
        self.camera.resume()
        self.camera.wait_until_buffer_filled()

        # Get after accident buffer from camera
        buffer_after_accident = self.camera.video_buffer.clone()
        self.logger.info("Grabbed after accident video buffer: {}".format(buffer_after_accident))

        buffer_accident_video = self.camera.create_accident_buffer(
            buffer_before=buffer_before_accident,
            buffer_after=buffer_after_accident
        )
        self.camera.video_buffer.clear()
        self.logger.info("Total accident video buffer: {}".format(buffer_accident_video))
        # Save the video
        filename = self.camera.save_captured_video(buffer_accident_video, timestamp)
        if filename is None:
            self.logger.error("Camera was unable to save accident video. Aborted reporting.")
            return

        # Get last known location from GPS
        location = self.gps.last_known_location

        # Build accident model
        accident = Accident(
            lat=location[0],
            lng=location[1],
            timestamp=timestamp,
            video_filename=filename
        )

        # Report accident
        self.logger.info("Build accident record:\n{}".format(accident.as_json(self.car)))
        reported = self.crash_reporter.report_accident(accident.as_dict(self.car))
        if reported:
            self.logger.success("Accident reported successfully.")
        else:
            self.logger.error("Couldn't report accident.")
        # Resume car crash detector
        self.camera.resume()
        self.car.crash_detector.resume()

if __name__ == '__main__':
    aassl = AASSL()
    aassl.setup_system()
    aassl.start_system()
    # aassl.stop_system()


data_lines = open("input/day1.txt").readlines()
elfs = [0]
elf_index = 0
for line in data_lines:
	line = line.rstrip()
	if len(line) == 0:
		elf_index += 1
		elfs.append(0)
	else:
		elfs[elf_index] += int(line)
sorted_elfs = sorted(elfs)
total_calories = 0
for _ in range(3):
	value = sorted_elfs.pop()
	total_calories += value
	print(_ + 1, value)
print("Total", total_calories)


from ninja_ide.core import plugin

import atexit

from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager

from PyQt4 import QtCore
from PyQt4.QtCore import SIGNAL

from ninja_ide.gui.main_panel import itab_item
from ninja_ide.resources import IMAGES
from PyQt4.QtGui import QWidget

class INinjaConsole(plugin.Plugin):
    def initialize(self):
        # Init your plugin
        self.misc_s = self.locator.get_service('misc')
        explorer_container = self.locator.get_service('explorer')
        tree = explorer_container.get_tree_projects()

        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt4'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()

        self.ipython_console = RichIPythonWidget()
        self.ipython_console.kernel_manager = kernel_manager
        self.ipython_console.kernel_client = kernel_client
        self.ipython_console.exit_requested.connect(stop)
        self.ipython_console.show()

        self.misc_s.add_widget(self.ipython_console, IMAGES["console"],
                                "IPython console")
        addp = SIGNAL("addProjectToConsole(QString)")
        delp = SIGNAL("removeProjectFromConsole(QString)")
        self.connect(tree, addp, self._add_project)
        self.connect(tree, delp, self._del_project)

    def _add_project(self, project_path):
        self.ipython_console.execute("import sys; sys.path += ['%s']" %
                                    project_path)

    def _del_project(self, project_path):
        """This is ugly, but I was in a hurry and copied form console
        widget"""
        self.ipython_console.execute("import sys; "
            "sys.path = [path for path in sys.path "
            "if path != '%s']" % project_path)

    def finish(self):
        # Shutdown your plugin
        pass

    def get_preferences_widget(self):
        # Return a widget for customize your plugin
        pass


import cv2

# Download the haarcascade_frontalcatface.xml from this link
# https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalcatface.xml

# Cascade file that contains all what we need to detect faces
face_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml')

def detect():

    # Setting the webcam of our pc
    cap = cv2.VideoCapture(0)

    while True:
        _,img = cap.read()

        # Setting the gray
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        # Face detected
        # face = face_cascade.detectMultiScale(gray, scale_factor, nb_faces )
        face = face_cascade.detectMultiScale(gray, 1.1, 4)

        # Create a rectangle for faces
        for (x, y, w, h) in face:
            cv2.rectangle(img, (x, y), (x+w, y+h), (255,0,0), 2)

        cv2.imshow("Face Detect", img)

        if cv2.waitKey(1)==27:
            break

    cap.release()

detect()


#!/usr/bin/python3

"""
Ask the user for a number and determine whether the number is prime or not
"""

def GetNumber(txt) :
	return int(input(txt))

def isPrime(x):
	for i in range(2,int(x/2 + 1)) :
		print (i)
		if x%2 == 0 :
			return False
	return True

x= GetNumber("Enter a number")
if isPrime(x) == True :
	print ("%d is a prime number",x)
else :
	print ("%d is not a prime number",x)


# ||AUM||
import scipy.io
import numpy as np
from dfsio import readdfs
from mayavi import mlab
#import h5py
import os
from sklearn.cluster import SpectralClustering
from scipy.stats import trim_mean
p_dir = 'E:\\HCP-fMRI-NLM'
lst = os.listdir(p_dir)
r_factor = 3
ref_dir = os.path.join(p_dir, 'reference')

ref = '100307'
print(ref + '.reduce' + str(r_factor) + '.LR_mask.mat')
fn1 = ref + '.reduce' + str(r_factor) + '.LR_mask.mat'
fname1 = os.path.join(ref_dir, fn1)
msk = scipy.io.loadmat(fname1)  # h5py.File(fname1);
dfs_left = readdfs(os.path.join(p_dir, 'reference', ref + '.aparc.a2009s.32k_fs.reduce3.left.dfs'))
dfs_left_sm = readdfs(os.path.join(p_dir, 'reference', ref + '.aparc.a2009s.32k_fs.reduce3.very_smooth.left.dfs'))
count1 = 0
rho_rho=[];rho_all=[]
for sub in lst: # ['751348']: #; lst:
    try:
        data = scipy.io.loadmat(os.path.join(p_dir, sub, sub + '.rfMRI_REST1_RL.reduce3.ftdata.NLM_11N_hvar_25.mat'))
    except:
        continue

    LR_flag = msk['LR_flag']
    LR_flag = np.squeeze(LR_flag) > 0
    data = data['ftdata_NLM']
    temp = data[LR_flag, :]
    m = np.mean(temp, 1)
    temp = temp - m[:,None]
    s = np.std(temp, 1)+1e-16
    temp = temp/s[:,None]
    msk_small_region = (dfs_left.labels == 46) | (dfs_left.labels == 28) | (dfs_left.labels == 29)  # % motor
    d = temp[msk_small_region, :]
    d_corr = temp[~msk_small_region, :]
    rho = np.corrcoef(d, d_corr)
    rho=rho[range(d.shape[0]),d.shape[0]+1:]
    rho[~np.isfinite(rho)] = 0
    rho_all.append(rho)
    rho_rho.append(np.corrcoef(rho))
    count1+=1
    print(count1),
    #if count1 >10 :
    #    break

A=trim_mean(np.array(rho_rho),.1)#np.mean(np.array(rho_rho),0)
#A=np.mean(np.array(rho_all),0)
print(A.shape)

for nClusters in [2,4,6,8,10,12]:
    SC=SpectralClustering(n_clusters=nClusters,affinity='precomputed',assign_labels='discretize')#,random_state=3425
    labs=SC.fit_predict(A)
    print(labs.shape)

    r = dfs_left_sm;r.labels = r.labels*0;r.labels[msk_small_region] = labs
    mesh = mlab.triangular_mesh(r.vertices[:,0], r.vertices[:,1], r.vertices[:,2], r.faces, representation='surface',
                            opacity=1,scalars=np.float64(r.labels))
    #mlab.pipeline.surface(mesh)
    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=-90)
    mlab.savefig(filename = str(nClusters)+'mean'+'labels1_1.png')
    mlab.view(azimuth=0, elevation=90)
    mlab.savefig(filename = str(nClusters)+'mean'+'labels2_1.png')
    mlab.close()


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

# # Exploring with Visuals
# Use `clean_08.csv` and `clean_18.csv`. You should've created these data files in the previous section: *Fixing Data Types Pt 3*.

# In[1]:

# load datasets
import pandas as pd
get_ipython().run_line_magic('matplotlib', 'inline')
df_08 = pd.read_csv('clean_08.csv')
df_18 = pd.read_csv('clean_18.csv')

# In[2]:

df_08.hist(figsize=(8,8));

# In[3]:

df_18.hist(figsize=(8,8));

# In[4]:

pd.plotting.scatter_matrix(df_08, figsize=(15,15));

# In[5]:

pd.plotting.scatter_matrix(df_18, figsize=(15,15));

# In[6]:

ax1 = df_08.plot(kind='scatter', x='greenhouse_gas_score', y='cmb_mpg', color='r')
ax2 = df_18.plot(kind='scatter', x='greenhouse_gas_score', y='cmb_mpg', color='b')
print(ax1 == ax2)

# In[7]:

ax1 = df_08.plot(kind='scatter', x='displ', y='cmb_mpg', color='r')
ax2 = df_18.plot(kind='scatter', x='displ', y='cmb_mpg', color='b')
print(ax1 == ax2)


#!/usr/bin/env python
"""
_DCCPGenericImpl_

Implementation of StageOutImpl interface for DCCP for a generic
site.

Assumes the target dir will already exist.
Doesnt support deletion yet: This needs to be added

"""
import os
import logging

from WMCore.Storage.StageOutImplV2 import StageOutImplV2

_CheckExitCodeOption = True

class DCCPGenericImpl(StageOutImplV2):
    """
    _DCCPGenericImpl_

    Implement interface for dccp command

    """

    def doTransfer(self, fromPfn, toPfn, stageOut, seName, command, options, protocol  ):
        """
            performs a transfer. stageOut tells you which way to go. returns the new pfn or
            raises on failure. StageOutError (and inherited exceptions) are for expected errors
            such as temporary connection failures. Anything else will be handled as an unexpected
            error and skip retrying with this plugin

            if stageOut is true:
                The fromPfn is the LOCAL FILE NAME on the node, without file://
                the toPfn is the target PFN, mapped from the LFN using the TFC or overrrides
            if stageOut is false:
                The toPfn is the LOCAL FILE NAME on the node, without file://
                the fromPfn is the target PFN, mapped from the LFN using the TFC or overrrides

            this behavior is because most transfer commands will switch their direction
            simply by swapping the order of the arguments. the stageOut flag is provided
            however, because sometimes you want to pass different command line args

        """
        ourCommand = \
            self.generateCommandFromPreAndPostParts(\
                        ["dccp"],
                        [fromPfn, toPfn],
                        options)
        self.runCommandFailOnNonZero(ourCommand)

        return toPfn

    def doDelete(self, pfn, seName, command, options, protocol  ):
        """
            deletes a file, raises on error
            StageOutError (and inherited exceptions) are for expected errors
            such as temporary connection failures. Anything else will be handled as an unexpected
            error and skip retrying with this plugin
        """
        logging.info("Attempted to delete, but delete not supported")
        logging.info(pfn)


# -*- coding: utf-8 -*-
# @Time    : 2023/2/7 10:52
# @Author  : HongFei Wang

import tqdm
from docx import Document
from docxcompose.composer import Composer

def delete_paragraph(paragraph):
	p = paragraph._element
	p.getparent().remove(p)
	paragraph._p = paragraph._element = None

# 定义合并文档的函数
def merge_doc(source_file_path_list, target_file_path):
	"""
	:param source_file_path_list: 源文件路径列表
	:param target_file_path: 目标文件路径
	"""
	# 填充分页符号文档
	page_break_doc = Document()
	page_break_doc.add_section()
	# 定义新文档
	target_doc = Document(source_file_path_list[0])
	target_composer = Composer(target_doc)
	for i in tqdm.tqdm(range(len(source_file_path_list))):
		# 跳过第一个作为模板的文件
		if i == 0: continue
		target_composer.append(page_break_doc)  # 添加空白
		# 拼接文档内容
		f = source_file_path_list[i]
		f = Document(f)
		target_composer.append(f)
	# 保存目标文档
	target_composer.save(target_file_path)


# -*- coding: utf-8 -*-
import scrapy

from appbee_crawler.manager.db_manager import DBManager
from appbee_crawler.spiders.parser.app_item_parser import AppItemParser

class AppInfoUpdateSpider(scrapy.Spider):
    name = "AppInfoUpdateSpider"
    allowed_domains = ["play.google.com"]

    def start_requests(self):
        package_names = DBManager.get_package_names_to_update_info()
        for package_name in package_names:
            if package_name == 'com.formakers.fomes':
                continue

            request = scrapy.Request('https://play.google.com/store/apps/details?id=' + package_name,
                                     meta={'packageName': package_name}, dont_filter=True)
            yield request

    def parse(self, response):
        yield AppItemParser.parse(response)


import logging

from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse

from stu.models import Student, StudentInfo, Class

logger = logging.getLogger('stu')

def index(request):

    if request.method == 'GET':
        stuinfos = StudentInfo.objects.all()
        logger.info('url: %s method:%s 获取学生信息成功' % (request.path, request.method))
        return render(request, 'index.html', {'stuinfos': stuinfos})

def addStu(request):
    if request.method == 'GET':
        return render(request, 'addStu.html')

    if request.method == 'POST':
        name = request.POST.get('name')
        num = request.POST.get('num')

        stu = Student.objects.create(
            stu_name=name,
            stu_num=num
        )
        return redirect(
            reverse('s:addinfo', kwargs={'stu_id': stu.id})
        )

def addStuInfo(request, stu_id):

    if request.method == 'GET':

        return render(request, 'addStuInfo.html', {'stu_id':stu_id})

    if request.method == 'POST':

        stu_id = request.POST.get('stu_id')

        # 添加头像图片
        img = request.FILES.get('img')

        StudentInfo.objects.create(s_id=stu_id, i_image=img)

        return HttpResponseRedirect('/stu/index/')

def addClass(request):

    if request.method == 'GET':

        return render(request, 'addClass.html')

    if request.method == 'POST':

        name = request.POST.get('name')
        num = request.POST.get('num')
        clas = request.POST.get('clas')

        Student.objects.create(
            s_name=name,
            s_num=num,
            s_class=clas
            )
        Class.objects.create(s_class=clas,
                             s_name=name,
                             s_num=num)
        return HttpResponseRedirect('/stu/index/')

def addGrade(request):

    if request.method == 'GET':

        return render(request, 'addGrade.html')

    if request.method == 'POST':

        s_num = request.POST.get('num')
        s_name = request.POST.get('name')
        s_sex = request.POST.get('sex')
        s_Chinese = request.POST.get('Chinses')
        s_Math = request.POST.get('Math')
        s_English = request.POST.get('English')

        StudentInfo.objects.create(s_num=s_num,
                                   s_name=s_name,
                                   s_sex=s_sex,
                                   s_Chinese=s_Chinese,
                                   s_Math=s_Math,
                                   s_English=s_English)

        return HttpResponseRedirect('/stu/index/')

def selectStu(request):
    stus = Student.objects.all()

    if request.method == 'POST':
        s_name = request.POST.get('stuname')
        stus = Student.objects.filter(stu_name=s_name)
        return render(request, 'sel_stut.html', {'stus': stus})

    return render(request, 'sel_stu.html', {'stus': stus})


import sys
import types

from utils import Set

class PDA:
    def __init__(self, Q, Σ, Γ, δ, q0, Z0, F):
        """

        Q  : set of states
        Σ  : finite alphabet
        Γ  : set of alphabet of Stack
        δ  : Q × Σ → Q transition function
        q0 : q0 ∈ Q initial states
        Z0 : initial symbol in Stack
        F  : F ⊆ Q set of accepting states

        """
        import PDA

        assert isinstance(Q, Set), "Q must be a Set of states"
        assert isinstance(Σ, Set), "Σ must be a Set of alphabet"
        if not (isinstance(δ, PDA.δ) or isinstance(δ, PDA.ô)):
            raise AssertionError(
                f"δ must be a transition function PDA.δ, but is {type(δ)}")
        assert q0 in Q, f"condition q0 ∈ Q not met, {q0} not in {Q}"
        assert isinstance(F, Set), "F must be a Set of accepting states"
        assert all(qf in Q for qf in F) or F.empty(
        ), f"condition F ⊆ Q not met, element of {F} not in {Q}"

        self.__dict__.update({
            "Q": Q.map(str), "Σ": Σ.map(str), "Γ": Γ.map(str), "δ": δ, "q0": str(q0), "Z0": str(Z0), "F": F.map(str)})

        self.δ.pda = self

    def __str__(self):
        return (f"A = ({self.Q}, {self.Σ}, {self.Γ}, δ, {self.q0}, {self.Z0}, {self.F}) where\n" +
                f"δ = {self.δ if getattr(self, 'δ', False) else self.ô}\n")

class δ(dict):
    def __setitem__(self, key, val):
        super().__setitem__(tuple(map(str, key)), Set(map(str, val)))

    def __getitem__(self, key):
        if key not in self:
            self.__setitem__(key, Set())
        return super().__getitem__(key)

class ô(dict):
    def __setitem__(self, key, val):
        super().__setitem__(key, val)

    def __getitem__(self, key):
        if key not in self:
            self.__setitem__(key, Set())
        return super().__getitem__(key)

class call(types.ModuleType):
    """
    make the module callable simplifying
    from PDA import PDA
    to
    import PDA
    """

    def __init__(self):
        types.ModuleType.__init__(self, __name__)
        # or super().__init__(__name__) for Python 3
        self.__dict__.update(sys.modules[__name__].__dict__)

    def __call__(self, *args, **kwargs):
        return PDA(*args, **kwargs)

sys.modules[__name__] = call()


import keras
from tensorflow import keras
from keras.models import Sequential
from keras_NN import *
from Plot_Quantities import *
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import train_test_split
from atlasify import atlasify
import pickle

#From Adversarial code
# Import(s)
import os
import h5py

# Set Keras backend
os.environ['KERAS_BACKEND'] = 'tensorflow'

# Keras import(s)
import keras.backend as K
from keras.models import Model
from keras.layers import Input, Dense, Concatenate
from keras.optimizers import Adam

# Local import(s) -- after Keras backend is set
import ops
import plots
import layers

#Total data set provided (signal/backgorund event numberss)
samples = [447834, 2111964]

#Retrieve transformed data
with open("C:/Users/jamie/OneDrive/Documents/Python Scripts/SHproject2/transformed_data.data", 'rb') as f:
    # read the data as binary data stream
    a = pickle.load(f)
df = pd.DataFrame(a[:1000000])#895668

#Reproducability
np.random.seed(5321)

#Standardise data
for i in range(df.shape[1]-2):
        df[i] = (df[i] - df[i].mean()) / (df[i].std())

#Shuffle then separate into training, validation, and test sets
x_train, x_test, y_train, y_test, m_train, m_test = train_test_split(df.iloc[:, :-2].values, df.iloc[:, -1].values,
                                                                     df.iloc[:, -2].values, test_size=0.2, shuffle = True)

#Data metrics
nb_samples = x_train.shape[0]
nb_features = x_train.shape[1]

# Adversary factory method
def adversary_model (nb_gmm):

    # Input(s)
    i = Input(shape=(1,))
    m = Input(shape=(1,))

    # Hidden layer(s)
    x = Dense(4,  activation='relu')(i)
    x = Dense(8,  activation='relu')(x)
    x = Dense(16, activation='relu')(x)
    x = Dense(32, activation='relu')(x)

    # Gaussian mixture model (GMM) components
    coeffs = Dense(nb_gmm, activation='softmax') (x)  # GMM coefficients sum to one
    means  = Dense(nb_gmm, activation='sigmoid') (x)  # Means are on [0, 1]
    widths = Dense(nb_gmm, activation='softplus')(x)  # Widths are positive

    # Posterior p.d.f.
    pdf = layers.PosteriorLayer(nb_gmm)([coeffs, means, widths, m])

    # Build model
    return Model(inputs=[i,m], outputs=pdf, name='adversary')

# Combined factory method
def combined_model (clf, adv, lambda_reg, lr_ratio):

    # Classifier
    input_clf  = Input(shape=clf.layers[0].input_shape[1:])
    input_m    = Input(shape=(1,))
    output_clf = clf(input_clf)

    # Connect with gradient reversal layer
    gradient_reversal = layers.GradientReversalLayer(lambda_reg * lr_ratio)(output_clf)

    # Adversary
    output_adv = adv([gradient_reversal, input_m])

    # Build model
    return Model(inputs=[input_clf, input_m], outputs=[output_clf, output_adv], name='combined')

def KL (y_true, y_pred):
    """
    Kullback-Leibler loss; maximises posterior p.d.f.
    """
    return -K.log(y_pred)

#Compile and fit standard netral network
clf = define_model(nb_features)
hist_clf = clf.fit(x_train, y_train, epochs=5, batch_size=1000, validation_split=0.15)

#Make class predictions with the model
y_pred = clf.predict(x_test).flatten()

sig_smp, bkg_smp = len(y_test[y_test == 1]), len(y_test[y_test == 0])
s_fac_trim = [samples[0]/sig_smp, samples[1]/bkg_smp]
print('Cut Signal: ', sig_smp*8.1330010*(10**-5)*s_fac_trim[0])
print('Cut Background: ', bkg_smp*1.4058503*(10**-4)*s_fac_trim[1])

#Print various metrics and graphs based on standard neural network
#report_NN(clf, hist_clf, y_pred, x_test, y_test, m_test, s_fac_trim)

lam = 100                     # Regularisation parameter, lambda
nb_gmm = 6                   # Number of GMM components
loss_weights = [1.0E-08, 1.]   # Relative learning rates for classifier and adversary, resp.
lr_ratio = loss_weights[0] / loss_weights[1]
optimiser = 'adam'             # Using the Adam optimiser

# Prepare sample weights (i.e. only do mass-decorrelation for signal)
sample_weight = [np.ones(nb_samples, dtype=float), (y_train == 0).astype(float)]
sample_weight[1] *= np.sum(sample_weight[0]) / np.sum(sample_weight[1])

# Rescale mass to [0,1]
mt_train  = m_train - m_train.min()
mt_train /= mt_train.max()

# Get classifier predictions
z_train = clf.predict(x_train).flatten()
z_train_rounded = np.rint(z_train)

# Construct adversary model and fit
adv = adversary_model(nb_gmm)
adv.compile(optimiser, loss=KL)
hist_adv = adv.fit([z_train, mt_train], np.ones_like(mt_train), sample_weight=sample_weight[1], batch_size = 60, epochs=7, validation_split=0.15)

#Demonstrate learned mass ability
plots.posterior(adv, m_train[y_train == 0], z_train[y_train == 0], title='Before adversarial training')
plt.show()

# Construct combined model and fit
cmb = combined_model(clf, adv, lam, lr_ratio)
cmb.compile(optimiser, loss=['binary_crossentropy', KL], loss_weights=loss_weights)
hist_cmb = cmb.fit([x_train, mt_train], [y_train, np.ones_like(mt_train)], sample_weight=sample_weight, batch_size=500, epochs=60, validation_split=0.15)

#Predict using new classifier on train/test sets
z_train    = clf.predict(x_train).flatten()
y_pred_ANN = clf.predict(x_test).flatten()
y_pred_ANN_rounded = np.rint(y_pred_ANN)
plots.posterior(adv, m_train[y_train == 0], z_train[y_train == 0], title='After adversarial training')
plt.show()

#Mass Correlation Graph
plots.profile(m_test[y_test==0], [y_pred[y_test==0], y_pred_ANN[y_test==0]], labels=['NN classifier', 'ANN classifier'])
plt.show()

#Predictions
distribution(y_test, y_pred_ANN, xlabel="Classifier Output")
plt.show()

#Evaluate the naive model
loss, accuracy, precision, recall= clf.evaluate(x_test, y_test)
print('Accuracy: %.2f' % (accuracy*100))
print('Loss: %.2f' % (loss))
print('Precision: %.2f' % (precision))
print('Recall: %.2f' % (recall))
print('F1: ', metrics.f1_score(y_test, y_pred_ANN_rounded))

sig_smp, bkg_smp = len(y_test[y_test == 1]), len(y_test[y_test == 0])
s_fac_trim = [samples[0]/sig_smp, samples[1]/bkg_smp]
print('Cut Signal: ', sig_smp*8.1330010*(10**-5)*s_fac_trim[0])
print('Cut Background: ', bkg_smp*1.4058503*(10**-4)*s_fac_trim[1])

#Scaling constant
SBSF = 24.838677879576565

#Sensitivity for different cuts with ANN
ss = []
t = np.linspace(0.1,0.9,20,endpoint=True)
for i in t:
    true_pos, false_pos, true_neg, false_neg = calc_Truths(y_pred_ANN, y_test, m_test, threshold = i)
    eff_sig = len(true_pos)/(len(true_pos)+len(false_neg))
    eff_bkg = len(false_pos)/(len(false_pos)+len(true_neg))
    sensitivity = Sensitivity(true_pos, false_pos, s_fac_trim, SBSF)
    ss.append(sensitivity)
    print('Sensitivity on cut {}: '.format(i), sensitivity, ' with efsig: ', eff_sig, ' with rj: ', eff_bkg)
print('Best at: ', t[ss.index(max(ss))])

#Plot sensitivities
plt.plot(t, ss, label = 'Sensitivity on Cut')
plt.xlabel('Prediction Cut')
plt.ylabel('Sensitivity')
plt.legend()
plt.show()

#Print graphs for the best cut
true_pos, false_pos, true_neg, false_neg = calc_Truths(y_pred_ANN, y_test, m_test, threshold =t[ss.index(max(ss))])
eff_sig = len(true_pos)/(len(true_pos)+len(false_neg))
eff_bkg = len(false_pos)/(len(false_pos)+len(true_neg))
sensitivity = Sensitivity(true_pos, false_pos, s_fac_trim, SBSF)
print('Best effsig: ', eff_sig)
print('Best rj: ', eff_bkg)
print('Best Sensitivity: ', sensitivity)

# Mass distribution sculpting
plots.sculpting(m_test, y_test, [y_pred, y_pred_ANN], ['NN classifier', 'ANN classifier'], effsig = eff_sig)
plt.show()

plot_Sculpting(true_pos, false_pos, true_neg, false_neg)
plt.show()
fit_Exp(false_pos)

#Plot metrics
plot_ROC(y_test, y_pred_ANN)
plot_PR(y_test, y_pred_ANN)
plot_Seq_Loss(hist_cmb)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

        # Account for special case where head = []
        if head == None:
            return None

        # Base case
        if head.next == None:
            return head

        # Main idea: reverse head.next (i.e., the rest of the linked list), then correct the pointers
        if head.next:
            reversedList = self.reverseList(head.next)
            head.next.next = head
            head.next = None

        return reversedList


import numpy as np
import pandas as pd
import plotly.express as px
from dash import Dash, Input, Output, dcc, html
from umap import UMAP

app = Dash(__name__)
app.title = "UMAP Projections"

app.layout = html.Div(
    [
        html.Div(
            children=[
                html.H1(
                    "UMAP Projections for MNIST and Fashion-MNIST Datasets",
                    style={"text-align": "center"},
                ),
                dcc.Markdown(
                    """
                    Uniform Manifold Approximation and Projection (UMAP) is a general-purpose dimension reduction algorithm. Similar to t-distributed stochastic neighbor embedding (t-SNE), you can use UMAP to visualize the relationships between data points. In this example, we are training a three-component UMAP model on MNIST datasets and then displaying the 3D graph of the result. The color of the point in the graph is based on the label. In the resulting graph, blobs of colors show that UMAP clustered data points with similar labels together.
                """,
                ),
            ],
            style={"padding": 10},
        ),
        html.Div(
            [
                html.Div(
                    children=[
                        html.H1("Input"),
                        html.Label("Dataset"),
                        dcc.Dropdown(
                            ["MNIST-Digits", "MNIST-Fashion"], "MNIST-Digits", id="dataset_dropdown"
                        ),
                    ],
                    style={"padding": 10, "flex": 1},
                ),
                html.Div(
                    children=[
                        html.H1("Output"),
                        dcc.Loading(
                            id="loading-1",
                            children=[dcc.Graph(id="graph")],
                            type="circle",
                        ),
                    ],
                    style={"padding": 10, "flex": 3},
                ),
            ],
            style={"display": "flex", "flex-direction": "row"},
        ),
    ]
)

@app.callback(
    Output("graph", "figure"),
    Input("dataset_dropdown", "value"),
)
def update_figure(selected_dataset):
    if selected_dataset == "MNIST-Digits":
        X = pd.read_csv(
            "https://saturn-public-data.s3.us-east-2.amazonaws.com/MNIST-1000/mnist-1000-input.csv"
        )
        y = pd.read_csv(
            "https://saturn-public-data.s3.us-east-2.amazonaws.com/MNIST-1000/mnist-1000-labels.csv"
        )
        y = np.unique(y, return_inverse=True)[1]

    elif selected_dataset == "MNIST-Fashion":
        X = pd.read_csv(
            "https://saturn-public-data.s3.us-east-2.amazonaws.com/MNIST-1000/fashion-1000-input.csv"
        )
        y = pd.read_csv(
            "https://saturn-public-data.s3.us-east-2.amazonaws.com/MNIST-1000/fashion-1000-labels.csv"
        )
        y = np.unique(y, return_inverse=True)[1]

    else:
        return None, "Please select a dataset."

    umap_3d = UMAP(n_components=3, init="random", random_state=0)

    proj_3d = umap_3d.fit_transform(X, y=y)

    fig = px.scatter_3d(proj_3d, x=0, y=1, z=2, color=y)

    fig.update_layout(transition_duration=500, height=1000)
    fig.update(layout_coloraxis_showscale=False)
    fig.update_traces(marker_size=2)

    return fig

if __name__ == "__main__":
    app.run_server(host="0.0.0.0", port="8000")