import scrapy
from scrapy.loader import ItemLoader
from itemloaders.processors import TakeFirst
from datetime import datetime
from banquethaler.items import Article

class BanquethalerSpider(scrapy.Spider):
    name = 'banquethaler'
    start_urls = ['http://www.banquethaler.ch/investment-letters']

    def parse(self, response):
        links = response.xpath('//a[@class="readmore"]/@href').getall()
        yield from response.follow_all(links, self.parse_article)

    def parse_article(self, response):
        item = ItemLoader(Article())
        item.default_output_processor = TakeFirst()

        title = "".join(response.xpath('//h1//text()').getall())
        if title:
            title = title.strip()

        date = response.xpath('//span[@class="datum"]/text()').get()
        if date:
            date = date.strip()
        else:
            return

        content = response.xpath('//article//text()').getall()
        content = [text for text in content if text.strip()]
        content = "\n".join(content).strip()

        item.add_value('title', title)
        item.add_value('date', date)
        item.add_value('link', response.url)
        item.add_value('content', content)

        return item.load_item()


import tkinter as tk
from tkinter import ttk

import serial
from serial.tools import list_ports

root = tk.Tk()
msg = tk.StringVar()

def greet():
    print(msg.get())

    serial.Serial()

def main():
    root.title("Autodrone Configurator")

    # frames
    mainframe = tk.Frame(root)
    mainframe.pack()

    tk.Entry(mainframe, textvariable=msg).grid(row=0, column=0)
    ttk.Button(mainframe, text="Click Me!", command=greet).grid(row=0, column=1)

    choicesvar = tk.StringVar(value=list_ports.comports())
    l = tk.Listbox(mainframe, listvariable=choicesvar)
    l.grid(row=1, column=0, columnspan=2)

    if(l.selection_includes(2)):
        print("Selected 2!")

    root.mainloop()

if __name__ == '__main__':
    main()


import gst_streamer as gs
import cv2
#import time

indices =[0,-1,-1]
#manager = gs.Manager(indexes)
#manager.start()

peg = gs.Streamer(indices[0])

while 1:
    peg.stream()
    frame = peg.frame
    cv2.imshow("peg", frame)
    cv2.waitKey(1)


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

import os
import re
import sys
from setuptools import setup, find_packages

name = 'log'
package = 'log'
description = 'because you deserve better than log4j'
url = 'https://github.com/vforgione/log'
author = 'Vince Forgione'
author_email = 'vince.4gione@icloud.com'
license = 'MIT'

install_requires = [
    'PyYAML',
    'six'
]
if sys.version_info < (3, 4, 0):
    install_requires.append('enum34')

timezone_requires = install_requires + [
    'arrow',
]

dev_requires = timezone_requires + [
    'pytest',
    'pytest-cov',
    'capturer',
    'coveralls',
    'flake8',
    'sphinx',
    'sphinx-autobuild',
    'sphinx-rtd-theme',
]

classifiers = [
    'Development Status :: 5 - Production/Stable',
    'Environment :: Console',
    'Environment :: Web Environment',
    'Intended Audience :: Developers',
    'Intended Audience :: Information Technology',
    'Intended Audience :: System Administrators',
    'License :: OSI Approved :: MIT License',
    'Natural Language :: English',
    'Operating System :: MacOS',
    'Operating System :: POSIX',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
]

def get_version(pkg):
    init_py = open(os.path.join(pkg, '__version__.py')).read()
    return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)

setup(
    name=name,
    version=get_version(package),
    url=url,
    license=license,
    description=description,
    author=author,
    author_email=author_email,
    classifiers=classifiers,
    packages=find_packages(exclude=['*tests*']),
    install_requires=install_requires,
    extras_require={
        'timezone': timezone_requires,
        'dev': dev_requires,
    },
)


from pymongo import MongoClient
from time import strftime
import re
from django.http import JsonResponse
from pandas import Series

def main(mydb):
    '''
    获取各种类型下的邮件
    '''
    time_list = []
    myThemeRiver = mydb.theme_river
    myInnerCollection = mydb.inner_email
    myOuterCollection = mydb.outer_email
    # inner_reader = myInnerCollection.aggregate([{"$group":{"_id":"$Type","num":{"$sum":1},"list":{"$addToSet":"$Sent"}}}])
    inner_reader = myInnerCollection.find({})
    print("处理内部邮件类型中...")
    type_list = get_email(inner_reader)
    outer_reader = myOuterCollection.find({},no_cursor_timeout = True)
    print("处理外部邮件中...")
    for row in outer_reader:
        # time_list.append(strftime("%Y-%m-%d",tuple(row["Sent"])))
        time_list.append(strftime("%Y-%m",tuple(row["Sent"])))
    ds = Series(time_list)
    counts = ds.value_counts()
    for date,count in counts.iteritems():
        type_list.append([
            date,
            count,
            "外部邮件"
        ])
    print("正在存入数据库中...")
    for row in type_list:
        myThemeRiver.insert({
            "data":row
        })

def get_email(data_reader):
    '''
    处理邮件类型
    '''
    type_list = []
    email_list = []
    for row in data_reader:
        # for i in range(row["list"].__len__()):
        #     row["list"][i] = strftime("%Y-%m-%d",tuple(row["list"][i]))
        # ds = Series(row["list"])
        # counts = ds.value_counts()
        # for date,count in counts.iteritems():
        #     type_list.append([
        #         date,
        #         count,
        #         row["_id"]
        #     ])
        email_list.append(strftime("%Y-%m",tuple(row["Sent"])))
    ds = Series(email_list)
    counts = ds.value_counts()
    for date,count in counts.iteritems():
        type_list.append([
            date,
            count,
            "内部邮件"
        ])
    return type_list

if __name__ == "__main__":
    print("开始处理数据")
    conn = MongoClient("127.0.0.1",27017)
    mydb = conn.test
    main(mydb)


import pandas as pd
import numpy as np
from sklearn import neural_network
from sklearn import preprocessing
df_ip=pd.read_csv('onset_ip.csv')
df_op=pd.read_csv('onset_op.csv')

print(df_ip.T.head())
print(df_op.head())
print(len(df_op))
print(len(df_ip))
print(len(df_ip.T))
ip_frame=[]

##### Step 1 : Data Preprocessing
print(len(df_ip.T[1:37]))
for i in range(0,43):
    temp=np.array(df_ip.T[(i)*12:i*12+36].values)
    temp=temp.ravel()
    ip_frame.append(temp)

print(len(ip_frame[1:30]))
print(len(ip_frame))
#print(ip_frame)
df_op_a=np.asarray(df_op)
#print(df_op_a)

df_op_ap=preprocessing.scale(df_op_a)
print(df_op_ap)
clf=neural_network.MLPRegressor(random_state=0,hidden_layer_sizes=500,activation='tanh',max_iter=500)
clf.fit(ip_frame[1:30],df_op_a[1:30])
print(clf.score(ip_frame[1:30],df_op_a[1:30]))

#### Step 2: implementing a predictor

from sklearn import ensemble

clf2=ensemble.AdaBoostRegressor(random_state=0)
clf2.fit(ip_frame[1:30],df_op_a[1:30])

print(clf2.score(ip_frame[1:30],df_op_a[1:30]))
pred_train=clf2.predict(ip_frame[1:30])
pred=clf2.predict(ip_frame[30:40])
print(pred)
print(df_op_a[30:-1])
#pred_train=clf2.predict(input.T[0:384])

#### Step 3:   Plotting the results
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot(range(0,len(ip_frame[30:40])),pred,'red',range(0,len(ip_frame[30:40])),df_op_a[30:40],'blue')
plt.figure(2)
plt.plot(range(0,len(df_op_a[1:30])),pred_train,'red',range(0,len(df_op_a[1:30])),df_op_a[1:30],'blue')
plt.show()


import sys,os,pytest,filecmp,shutil,pytest
main_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(main_dir,'..'))
import model
import itertools
import numpy as np

def test_linearExpansionModel():
    """This function tests that linearExpansion connects is working properly."""
    #This portions test to make sure the code fails with n values that cause non-integer steps
    with pytest.raises(SystemExit) as output:
        model.PlumeModel.linearExpansionModel(14)
        assert output.type == SystemExit
        assert output.value.code == 42

    #Manually check that it produces correct adj matrix otherwise
    n=10
    connects = model.PlumeModel.linearExpansionModel(n).connects
    ones = [(0,1),(0,2),(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
    ones += [(3,6),(3,7),(3,8),(3,9),(4,6),(4,7),(4,8),(4,9),(5,6),(5,7),(5,8),(5,9)]
    ones += [(n,0),(n,1),(n,2),(n,3),(n,5),(n,6),(n,9)]
    trange = range(connects.shape[0])
    for i in trange:
        for j in trange:
            if (i,j) in ones:
                assert connects[i,j] == 1
            else:
                assert connects[i,j] == 0

def test_gridModel():
    """Use this function to test grid model connects matrix."""
    #Manually check that it produces correct adj matrix otherwise
    n = m = 3
    connects = model.PlumeModel.gridModel(n=n,m=m).connects
    ones = np.zeros(connects.shape)
    diag=4
    ones[0,1:diag] = 1
    diagStart = diag
    for i in range(1,int(n*m-2)):
        ones[i,diagStart] = 1
        diagStart+=1
    for ext in [0,1,3,4,6,7,9]:
        ones[-1,ext] = 1
    trange = range(connects.shape[0])
    for i in trange:
        for j in trange:
            assert connects[i,j] == ones[i,j]

def test_simpleModel():
    """Use this function to test grid model connects matrix."""
    #Manually check that it produces correct adj matrix otherwise
    n = m = 3
    connects = model.PlumeModel.simpleModel().connects
    ones = np.zeros(connects.shape)
    for i,row in enumerate(connects):
        for j,val in enumerate(row):
            if i == 1 and j == 0:
                assert connects[i,j] == 1
            else:
                assert connects[i,j] == 0

def test_connectReactors():
    """Use this function to test the mass flow connections"""

def test_createReactors():
    """Use this function to test creation of reactors."""

def runTests():
    """Use this function to run pytests."""
    pytest.main([__file__,"--verbose"])


from django.contrib import admin
from django.urls import path
from .views import (
    home,
    content_view ,
    login_view,
    logout_view,
    register_view
    )

from django.conf import settings

urlpatterns = [
    path("", home , name='home' ),
    path("content/<int:id>/", content_view , name='content' ),
    path('login/', login_view, name='login'),
    path('logout/', logout_view, name='logout'),
    path('register/', register_view, name='register'),

]

if settings.DEBUG:
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import numpy as np
import pytest
from spatial_image import SpatialImage
from spatialdata._core.operations.rasterize import rasterize
from spatialdata._io._utils import _iter_multiscale
from spatialdata.models import get_axes_names
from spatialdata.models._utils import get_spatial_axes

from tests.conftest import _get_images, _get_labels

@pytest.mark.parametrize("_get_raster", [_get_images, _get_labels])
def test_rasterize_raster(_get_raster):
    def _get_data_of_largest_scale(raster):
        if isinstance(raster, SpatialImage):
            return raster.data.compute()

        xdata = next(iter(_iter_multiscale(raster, None)))
        return xdata.data.compute()

    rasters = _get_raster()
    for raster in rasters.values():
        dims = get_axes_names(raster)
        all_slices = {"c": slice(0, 1000), "z": slice(0, 1000), "y": slice(5, 20), "x": slice(0, 5)}
        slices = [all_slices[d] for d in dims]

        data = _get_data_of_largest_scale(raster)
        data[tuple(slices)] = 1

        for kwargs in [
            {"target_unit_to_pixels": 2.0},
            {"target_width": 10.0},
            {"target_height": 10.0},
            {"target_depth": 10.0},
        ]:
            if "z" not in dims and "target_depth" in kwargs:
                continue
            spatial_dims = get_spatial_axes(dims)
            result = rasterize(
                raster,
                axes=spatial_dims,
                min_coordinate=[0] * len(spatial_dims),
                max_coordinate=[10] * len(spatial_dims),
                target_coordinate_system="global",
                **kwargs,
            )

            result_data = _get_data_of_largest_scale(result)
            n_equal = result_data[tuple(slices)] == 1
            ratio = np.sum(n_equal) / np.prod(n_equal.shape)

            # 0.1: the z dim of the data is 2, the z dim of the target image is 20, because target_unit_to_pixels
            # is 2 and the bounding box is a square with size 10 x 10
            # 0.2: the z dim of the data is 2, the z dim of the target image is 10, because target_width is 10 and
            # the boundigbox is a square
            target_ratio = (0.1 if "target_unit_to_pixels" in kwargs else 0.2) if "z" in dims else 1

            # image case (not labels)
            if "c" in dims:
                # this number approximately takes into account for this interpolation error, that makes some pixel
                # not match. The problem is described here: https://github.com/scverse/spatialdata/issues/166
                target_ratio *= 0.66
            # this approximately takes into account for the pixel offset problem, that makes some pixels not match.
            # The problem is described here: https://github.com/scverse/spatialdata/issues/165
            target_ratio *= 0.73

            EPS = 0.01
            if ratio < target_ratio - EPS:
                raise AssertionError(
                    "ratio is too small; ideally this number would be 100% but there is an offset error that needs "
                    "to be addressed. Also to get 100% we need to disable interpolation"
                )

@pytest.mark.skip(reason="Not implemented yet")
def test_rasterize_shapes(shapes):
    pass

@pytest.mark.skip(reason="Not implemented yet")
def test_rasterize_points(points):
    pass

@pytest.mark.skip(reason="Not implemented yet")
def test_rasterize_spatialdata(full_sdata):
    pass


# Imports the Google Cloud client library
from google.cloud import language_v1
import os
import pickle
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/Users/jennyromero/Desktop/code/STOCKS/moodFinder-2d03c34a57da.json"

# Instantiates a client
client = language_v1.LanguageServiceClient()

titles = []
tickers = []
time = []
upvotes = []
magnitude = []
sent = []

FullList = open("wallStreetBets_hot.txt","r")
entries = FullList.read().split("|")

remainder = 0
for i in range(len(entries)):
    if i%2 == remainder:
        TUN = entries[i].split("\t")
        if len(TUN) == 4:
            time.append(TUN[0])
            tickers.append(TUN[1])
            upvotes.append(int(TUN[2]))
            titles.append(TUN[3])
        else:
            if remainder == 0:
                remainder = 1
            else:
                remainder = 0

for i in range(len(titles)):
    # The text to analyze
    text = titles[i]
    up = upvotes[i]

    document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)

    # Detects the sentiment of the text
    sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment
    sc = sentiment.score
    mag = sentiment.magnitude

    sent.append(sc)
    magnitude.append(mag)

    print("Text: {}".format(text))
    print("Sentiment: {}, {}".format(sc, mag))

# titles = []
# tickers = []
# time = []
# upvotes = []
# magnitude = []
# sent = []

pickle.dump( titles , open( "titles.p", "wb" ) )
pickle.dump( tickers , open( "tickers.p", "wb" ) )
pickle.dump( time, open( "time.p", "wb" ) )
pickle.dump( upvotes, open( "upvotes.p", "wb" ) )
pickle.dump( magnitude, open( "magnitude.p", "wb" ) )
pickle.dump( sent, open( "sent.p", "wb" ) )


import numpy as np
import logging
from .UserTrip import UserTrip
from .Location import Location

class UserAutonomous:
    id_count = -1

    def __init__(
        self, env, graph, ui, config, results, origin, destination, departure_time, target_time,
    ):
        self.next_id()
        self.id = UserAutonomous.id_count

        self.env = env
        self.graph = graph
        self.ui = ui
        self.config = config
        self.results = results
        self.user_trip = UserTrip()

        self.origin = origin
        self.destination = destination
        self.departure_time = departure_time
        self.target_time = target_time

        self.location = None
        self.bike_id = None
        self.bike_location = Location()
        self.time_wait = None
        self.time_ride = None
        self.instant_bike = False

        self.WALKING_SPEED = config["WALKING_SPEED"] / 3.6  # m/s
        self.INSTANT_BETA = config["INSTANT_BETA"] # %

    @classmethod
    def reset(cls):
        UserAutonomous.id_count = -1

    def next_id(self):
        UserAutonomous.id_count += 1

    def walk_to(self, location):
        distance = self.dist(self.location, location)
        time = distance / self.WALKING_SPEED
        yield self.env.timeout(time)
        logging.info("[%.2f] User %d walked from [%.4f, %.4f] to location [%.4f, %.4f]" % (self.env.now, self.id, self.location.lon, self.location.lat, location.lon, location.lat,))
        self.location = location

    def ride_bike_to(self, location):
        logging.info(
            "[%.2f] User %d biking with bike %d from [%.4f, %.4f] to location [%.4f, %.4f]" % (self.env.now, self.id, self.bike_id, self.location.lon, self.location.lat, location.lon, location.lat,)
        )
        yield self.env.process(self.ui.bike_ride(self.bike_id, location))
        self.location = location

    def dist(self, a, b):
        return self.graph.get_shortest_path_length(a, b)

    def start(self):
        self.env.process(self.process())

    def init_user(self):
        # waits until its the hour to initialize user
        yield self.env.timeout(self.departure_time)
        self.location = self.origin
        logging.info("[%.2f] User %d initialized at location [%.4f, %.4f]" % (self.env.now, self.id, self.location.lon, self.location.lat))

    def process(self):
        # 0-Setup

        # 1-Init on origin
        yield self.env.process(self.init_user())

        # 2-Call autonomous bike
        self.bike_id, bike_location = self.call_autonomous_bike(self.location)

        if self.bike_id is None:
            rand_number = np.random.randint(100)
            if rand_number <= self.INSTANT_BETA:
                self.instant_bike = True
                self.bike_id, bike_location = self.call_autonomous_instant_bike(self.location)

        if self.bike_id is None:
            logging.info("[%.2f] User %d will not make the trip" % (self.env.now, self.id))
            self.save_user_trip()
            return

        logging.info("[%.2f] User %d was assigned the autonomous bike %d" % (self.env.now, self.id, self.bike_id))

        # 3-Wait for autonomous bike
        yield self.env.process(self.autonomous_drive(self.instant_bike))

        self.bike_location = bike_location
        self.time_wait = self.env.now - self.departure_time
        yield self.env.process(self.unlock_bike())

        # 4-Ride bike
        yield self.env.process(self.ride_bike_to(self.destination))

        # 5-Lock bike
        yield self.env.process(self.lock_bike())

        # 6-Finish
        # TODO: estimate travel from building to nearest node
        logging.info("[%.2f] User %d arrived to final destination" % (self.env.now, self.id))

        self.time_ride = self.env.now - self.time_wait - self.departure_time
        # 7-Charge bike if low battery
        yield self.env.process(self.charge_bike())

        # 8-Save state
        self.save_user_trip()

    def autonomous_drive(self, instant=False, rebalancing=False, liberate=False, charge=False):
        yield self.env.process(self.ui.autonomous_drive(self.bike_id, self.location, self.id, instant, rebalancing, liberate, charge))

    def call_autonomous_bike(self, location):
        return self.ui.call_autonomous_bike(location)

    def call_autonomous_instant_bike(self, location):
        return self.ui.call_autonomous_instant_bike(location)

    def charge_bike(self):
        yield self.env.process(self.ui.bike_charge(self.bike_id))

    def unlock_bike(self):
        self.ui.bike_unlock(self.bike_id, self.id)
        yield self.env.timeout(1)
        logging.info("[%.2f] User %d unlocked bike %d" % (self.env.now, self.id, self.bike_id))

    def lock_bike(self):
        yield self.env.timeout(1)
        self.ui.bike_lock(self.bike_id)
        logging.info("[%.2f] User %d locked bike %d" % (self.env.now, self.id, self.bike_id))

    def save_user_trip(self):
        self.user_trip.set("user_id", self.id)
        self.user_trip.set("bike_id", self.bike_id)
        self.user_trip.set("mode", 2)

        self.user_trip.set("time_departure", self.departure_time, 0)
        self.user_trip.set("time_target", self.target_time, 0)
        self.user_trip.set("time_ride", self.time_ride, 0)
        self.user_trip.set("time_wait", self.time_wait, 0)

        self.user_trip.set("origin_lon", self.origin.lon, 5)
        self.user_trip.set("origin_lat", self.origin.lat, 5)
        self.user_trip.set("destination_lon", self.destination.lon, 5)
        self.user_trip.set("destination_lat", self.destination.lat, 5)

        self.user_trip.set("bike_lon", self.bike_location.lon)
        self.user_trip.set("bike_lat", self.bike_location.lat)

        self.user_trip.set("instant_bike", self.instant_bike)

        self.results.add_user_trip(self.user_trip)


from cx_Freeze import setup,Executable

includefiles = ['1.txt','2.txt','3.txt','4.txt','5.txt','6.txt','7.txt','Comic.ttf','dog1.jpeg','Papyrus.ttc','boardre.py','Tetris.ogg']
includes = []
excludes = ['Tkinter']
packages = ['pygame']

setup(
    name = 'myapp',
    version = '0.1',
    description = 'A general enhancement utility',
    author = 'lenin',
    author_email = 'le...@null.com',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
    executables = [Executable('Game.py')]
)


from django.urls import path
from django.contrib.auth.views import LoginView, LogoutView

from .views import (IndexView, CreateUserReplyView, CreatePostView,
                    EditPostView, UserProfileView, accept_reply,
                    DeleteUserReplyView, UserSignupView, UserConfirmCodeView)

urlpatterns = [
    path('', IndexView.as_view(), name='index'),
    path('login/', LoginView.as_view(template_name='login.html'), name='login'),
    path('logout/', LogoutView.as_view(template_name='logout.html'), name='logout'),
    path('signup/', UserSignupView.as_view(), name='signup'),
    path('profile/', UserProfileView.as_view(), name='profile'),
    path('create/', CreatePostView.as_view(), name='create_post'),
    path('edit/<int:pk>', EditPostView.as_view(), name='edit_post'),
    path('reply/<int:pk>', CreateUserReplyView.as_view(), name='create_reply'),
    path('accept/<int:pk>', accept_reply, name='accept_reply'),
    path('delete/<int:pk>', DeleteUserReplyView.as_view(), name='delete_reply'),
    path('confirm/', UserConfirmCodeView.as_view(), name='confirm_code'),
]


from django.shortcuts import render
from .models import Plants
from .filters import plantsFilter
from .forms import SearchForm

# Create your views here.
def home(request):
    plantsByFamily = None
    # 請求方法為POST（使用者查詢）時，依據請求傳入的查詢條件篩選資料
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            plantsByFamily = plantsFilter(formdata=form.cleaned_data)
    else:
        form = SearchForm()
    context = {
        'form': form,
        'plantsByFamily': plantsByFamily
    }
    return render(request, 'home.html', context)


import time
import threading
import allure
import pytest
from selenium import webdriver
from datetime import datetime

from test_Task04_MultiThreading import Testa

masters = "//a[@id='iMenuID_1']"
link = "http://localhost:8080/QuaLISWeb/index.html"

un="it"
pswd="123"
class Testabc():
    # In pytest data can't be passed at runtym
    # fixture represents a before method, scope = class it means this has to be run only once
    @pytest.fixture(scope="class")
    def test_parent(self):
        global kk
        global inputtime
        # inputtime = input("Enter the date & time: ")
        driver = webdriver.Chrome(executable_path="C:\\Users\\ate142\\PycharmProjects\\pythonProject1\\Automation\\chromedriver.exe")
        kk = Testa(driver)
# Parameterisation
    @pytest.mark.parametrize("var1,var2",[(un,pswd),(un,pswd)])
    def test_child(self, test_parent, var1, var2):
        inputtime = "07-03-2022 13:36:30"

        i=1
        while i > 0:
            systime = datetime.today()
            print(systime)
            timeconversion = systime.strftime("%d-%m-%Y %H:%M:%S")
            print(inputtime)
            print(timeconversion)
            if inputtime == timeconversion:
                kk.test_login(link, var1, var2)
                time.sleep(4)
                kk.test_xpathclick(masters)
                time.sleep(10)
                break

# For Parallel run, slave can be used. pytest -m markername -n marker count to run depends on parameter arguments


from audioop import reverse
from platform import release
from turtle import title
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from .models import Tvshow, Network
from datetime import datetime

def redirigir(request):
    return redirect('/shows')

def index(request):
    context = {
        'alltvshows': Tvshow.objects.all(),
        'allnetworks': Network.objects.all(),
    }
    return render(request, 'app/index.html', context)

def newtvshow(request):
    return render(request, 'app/formulario_new.html')

def createtvshow(request):
    if request.method == 'POST':
        if Network.objects.all().filter(name=request.POST['network']):
            print(Network.objects.all().filter(name=request.POST['network']))
            networks_query = Network.objects.all().filter(
                name=request.POST['network'])
            for query in networks_query:
                this_network = Network.objects.get(id=query.id)
                print(this_network.name)
                print(this_network.id)
                tv_show = Tvshow.objects.create(
                    title=request.POST['title'], network=this_network, releasedate=request.POST['releasedate'], description=request.POST['description'])
                print(tv_show.__dict__)
                showid = tv_show.id
            return redirect(f"/shows/{showid}")
        else:
            print(request.POST)
            create = Tvshow.objects.create(title=request.POST['title'], network=Network.objects.create(name=request.POST['network']),
                                           releasedate=request.POST['releasedate'], description=request.POST['description'])
            showid = create.id
            return redirect(f"/shows/{showid}")

def details(request, id):
    detalle = Tvshow.objects.get(id=id)
    context = {
        "detailstvshow": detalle,
    }
    return render(request, 'app/detalle.html', context)

def edit(request, id):
    if request.method == 'GET':
        editar = Tvshow.objects.get(id=id)
        network = editar.network.name
        release_date = editar.releasedate
        release_date = release_date.strftime('%Y-%m-%d')
        print(release_date)
        context = {
            "edit": editar,
            "release_date": release_date,
            "network": network
        }
    return render(request, 'app/formulario_edit.html', context)

def update(request, id):
    print(request.POST)
    update = Tvshow.objects.get(id=id)
    update_network = Network.objects.get(id=update.network.id)
    update.title = request.POST['title']
    update_network.name = request.POST['network']
    update.description = request.POST['description']
    update.releasedate = request.POST['releasedate']
    update_network.save()
    update.save()
    return redirect(f"/shows/{id}")

def destroy(request, id):
    print(request.POST)
    deleteshow = Tvshow.objects.get(id=id)
    deleteshow.delete()
    return redirect("/shows")


from __future__ import absolute_import

import logging

import globals.globals as g

from globals.six import text_type
import globals.constants as c
if c.PYQT5notPYQT4:
    from PyQt5.QtWidgets import QGraphicsView, QMenu
    from PyQt5 import QtCore
else:
    from PyQt4.QtGui import QGraphicsView, QMenu
    from PyQt4 import QtCore

logger = logging.getLogger("DxfImport.myCanvasClass")

"""
This Canvas function can be called as any class.
Since it will pretend to be, depending on the settings,
to be the canvas3d or canvas2d class
"""
def Canvas(parent=None):
    if g.config.mode3d:
        from gui.canvas3d import GLWidget
        return GLWidget(parent)
    else:
        from gui.canvas2d import MyGraphicsView
        return MyGraphicsView(parent)

def CanvasObject():
    if g.config.mode3d:
        QtVersion = QtCore.QT_VERSION_STR.split(".")
        if not (int(QtVersion[0]) >= 5 and int(QtVersion[1]) >= 4):
            raise Exception("For the 3d mode you need a PyQt version that includes a Qt version of at least 5.4.\n"
                            "Set mode3d to False in the config file, or update your PyQt version.\n"
                            "Current version found: PyQt%s (which includes Qt%s)"
                            % (QtCore.PYQT_VERSION_STR, QtCore.QT_VERSION_STR))
        from PyQt5.QtWidgets import QOpenGLWidget
        return QOpenGLWidget
    else:
        return QGraphicsView

class CanvasBase(CanvasObject()):
    def __init__(self, parent=None):
        super(CanvasBase, self).__init__(parent)

        self.isMultiSelect = False

class MyDropDownMenu(QMenu):
    def __init__(self, canvas_scene, position, clicked, offset=None):
        QMenu.__init__(self)

        self.clicked = clicked
        self.offset = offset

        self.canvas_scene = canvas_scene

        self.selectedItems = [shape for shape in canvas_scene.shapes if shape.isSelected()]

        if len(self.selectedItems) == 0:
            return

        invertAction = self.addAction(self.tr("Invert Selection"))
        disableAction = self.addAction(self.tr("Disable Selection"))
        enableAction = self.addAction(self.tr("Enable Selection"))

        self.addSeparator()

        swdirectionAction = self.addAction(self.tr("Switch Direction"))
        SetNxtStPAction = self.addAction(self.tr("Set Nearest StartPoint"))

        if g.config.machine_type == 'drag_knife':
            pass
        else:
            self.addSeparator()
            submenu1 = QMenu(self.tr('Cutter Compensation'), self)
            self.noCompAction = submenu1.addAction(self.tr("G40 No Compensation"))
            self.noCompAction.setCheckable(True)
            self.leCompAction = submenu1.addAction(self.tr("G41 Left Compensation"))
            self.leCompAction.setCheckable(True)
            self.reCompAction = submenu1.addAction(self.tr("G42 Right Compensation"))
            self.reCompAction.setCheckable(True)

            logger.debug(self.tr("The selected shapes have the following direction: %i") % (self.calcMenuDir()))
            self.checkMenuDir(self.calcMenuDir())

            self.addMenu(submenu1)

        invertAction.triggered.connect(self.invertSelection)
        disableAction.triggered.connect(self.disableSelection)
        enableAction.triggered.connect(self.enableSelection)

        swdirectionAction.triggered.connect(self.switchDirection)
        SetNxtStPAction.triggered.connect(self.setNearestStPoint)

        if g.config.machine_type == 'drag_knife':
            pass
        else:
            self.noCompAction.triggered.connect(self.setNoComp)
            self.leCompAction.triggered.connect(self.setLeftComp)
            self.reCompAction.triggered.connect(self.setRightComp)

        self.exec_(position)

    def tr(self, string_to_translate):
        """
        Translate a string using the QCoreApplication translation framework
        @param string_to_translate: a unicode string
        @return: the translated unicode string if it was possible to translate
        """
        return text_type(QtCore.QCoreApplication.translate('MyDropDownMenu',
                                                           string_to_translate))

    def calcMenuDir(self):
        """
        This method returns the direction of the selected items. If there are
        different cutter directions in the selection 0 is returned, else
        1 for Left and 2 for right.
        """
        dir = self.selectedItems[0].cut_cor
        for item in self.selectedItems:
            if not(dir == item.cut_cor):
                return -1

        return dir-40

    def checkMenuDir(self, dir):
        """
        This method checks the buttons in the Contextmenu for the direction of
        the selected items.
        @param dir: The direction of the items -1=different, 0=None, 1=left, 2=right
        """
        self.noCompAction.setChecked(False)
        self.leCompAction.setChecked(False)
        self.reCompAction.setChecked(False)

        if dir == 0:
            self.noCompAction.setChecked(True)
        elif dir == 1:
            self.leCompAction.setChecked(True)
        elif dir == 2:
            self.reCompAction.setChecked(True)

    def invertSelection(self):
        """
        This function is called by the Contextmenu of the Graphicsview.
        @purpose: Inverts the selection of all shapes.
        """
        for shape in self.canvas_scene.shapes:
            shape.setSelected(not shape.isSelected())
            g.window.TreeHandler.updateShapeSelection(shape, shape.isSelected())
        self.canvas_scene.update()

    def disableSelection(self):
        """
        Disable all shapes which are currently selected. Based on the view
        options they are not shown, or showed in a different color
        """
        for shape in self.selectedItems:
            if shape.allowedToChange:
                shape.setDisable(True)
                g.window.TreeHandler.updateShapeEnabling(shape, False)
        self.canvas_scene.update()

    def enableSelection(self):
        """
        Enable all shapes which are currently selected. Based on the view
        options they are not shown, or showed in a different color
        """
        for shape in self.selectedItems:
            if shape.allowedToChange:
                shape.setDisable(False)
                g.window.TreeHandler.updateShapeEnabling(shape, True)
        self.canvas_scene.update()

    def switchDirection(self):
        """
        Switch the Direction of all items. For example from CW direction to CCW
        """
        for shape in self.selectedItems:
            shape.reverse()
            logger.debug(self.tr('Switched Direction at Shape Nr: %i') % shape.nr)
            self.canvas_scene.repaint_shape(shape)
        self.canvas_scene.update()
        g.window.TreeHandler.prepareExportOrderUpdate()

    def setNearestStPoint(self):
        """
        Search the nearest StartPoint to the clicked position of all selected shapes.
        """
        xyForZ = {}
        for shape in self.selectedItems:
            clicked = self.clicked
            if self.offset is not None:
                z = shape.axis3_start_mill_depth
                if z not in xyForZ:
                    clicked = xyForZ[z] = self.canvas_scene.determineSelectedPosition(self.clicked, z, self.offset)
            shape.setNearestStPoint(clicked)
            self.canvas_scene.repaint_shape(shape)
        self.canvas_scene.update()
        g.window.TreeHandler.prepareExportOrderUpdate()

    def setNoComp(self):
        """
        Sets the compensation to 40, which is none, for the selected shapes.
        """
        for shape in self.selectedItems:
            shape.cut_cor = 40
            logger.debug(self.tr('Changed Cutter Correction to None for shape: %i') % shape.nr)
            self.canvas_scene.repaint_shape(shape)
        self.canvas_scene.update()

    def setLeftComp(self):
        """
        Sets the compensation to 41, which is Left, for the selected shapes.
        """
        for shape in self.selectedItems:
            shape.cut_cor = 41
            logger.debug(self.tr('Changed Cutter Correction to left for shape: %i') % shape.nr)
            self.canvas_scene.repaint_shape(shape)
        self.canvas_scene.update()

    def setRightComp(self):
        """
        Sets the compensation to 42, which is Right, for the selected shapes.
        """
        for shape in self.selectedItems:
            shape.cut_cor = 42
            logger.debug(self.tr('Changed Cutter Correction to right for shape: %i') % shape.nr)
            self.canvas_scene.repaint_shape(shape)
        self.canvas_scene.update()


from flask.ext import restful
from flask import request
from flask import jsonify
from flask import Response
from tools.info import Info
from conf import httpserver, httpport
from tools.crossdomain import allow_cross_domain
from orml.visitororml import Visitororml

class OpenLink(restful.Resource):

    @allow_cross_domain
    def get(self):
        link = request.args.get("questionnaire_link")
        vo = Visitororml()
        result = vo.openlink(link)
        if result == False:
            return jsonify(Info(False,'数据库错误',None).tojson())
        else:
            return jsonify(Info(True,'返回成功',result).tojson())

class FillIn(restful.Resource):

    @allow_cross_domain
    def post(self):
        questionid = request.form["questionnaire_id"]
        options = request.form["options"]
        vo = Visitororml()
        result = vo.fillin(questionid,options)
        if result == False:
            return jsonify(Info(False,'数据库错误',None).tojson())
        elif result == 'false':
            return jsonify(Info(False,'该问卷已过期',None).tojson())
        else:
            return jsonify(Info(True,'成功填写',None).tojson())

class Alarm(restful.Resource):

    @allow_cross_domain
    def post(self):
        questionid = request.form["questionnaire_id"]
        vo = Visitororml()
        result = vo.alarm(questionid)
        if result == False:
            return jsonify(Info(False,'数据库错误',None).tojson())
        else:
            return jsonify(Info(True,'成功举报',None).tojson())

class OpenTitle(restful.Resource):

    @allow_cross_domain
    def get(self):
        link = request.args.get("questionnaire_id")
        vo = Visitororml()
        result = vo.opentitle(link)
        if result == False:
            return jsonify(Info(False,'数据库错误').tojson())
        else:
            return jsonify(Info(True,'返回成功',result).tojson())


"""
Linear Least-Squares Inversion
==============================

Here we demonstrate the basics of inverting data with SimPEG by considering a
linear inverse problem. We formulate the inverse problem as a least-squares
optimization problem. For this tutorial, we focus on the following:

    - Defining the forward problem
    - Defining the inverse problem (data misfit, regularization, optimization)
    - Specifying directives for the inversion
    - Recovering a set of model parameters which explains the observations

"""

#########################################################################
# Import Modules
# --------------
#

import numpy as np
import matplotlib.pyplot as plt

from discretize import TensorMesh

from SimPEG import (
    simulation,
    maps,
    data_misfit,
    directives,
    optimization,
    regularization,
    inverse_problem,
    inversion,
)

# sphinx_gallery_thumbnail_number = 3

#############################################
# Defining the Model and Mapping
# ------------------------------
#
# Here we generate a synthetic model and a mappig which goes from the model
# space to the row space of our linear operator.
#

nParam = 100  # Number of model paramters

# A 1D mesh is used to define the row-space of the linear operator.
mesh = TensorMesh([nParam])

# Creating the true model
true_model = np.zeros(mesh.nC)
true_model[mesh.cell_centers_x > 0.3] = 1.0
true_model[mesh.cell_centers_x > 0.45] = -0.5
true_model[mesh.cell_centers_x > 0.6] = 0

# Mapping from the model space to the row space of the linear operator
model_map = maps.IdentityMap(mesh)

# Plotting the true model
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
ax.plot(mesh.cell_centers_x, true_model, "b-")
ax.set_ylim([-2, 2])

#############################################
# Defining the Linear Operator
# ----------------------------
#
# Here we define the linear operator with dimensions (nData, nParam). In practive,
# you may have a problem-specific linear operator which you would like to construct
# or load here.
#

# Number of data observations (rows)
nData = 20

# Create the linear operator for the tutorial. The columns of the linear operator
# represents a set of decaying and oscillating functions.
jk = np.linspace(1.0, 60.0, nData)
p = -0.25
q = 0.25

def g(k):
    return np.exp(p * jk[k] * mesh.cell_centers_x) * np.cos(
        np.pi * q * jk[k] * mesh.cell_centers_x
    )

G = np.empty((nData, nParam))

for i in range(nData):
    G[i, :] = g(i)

# Plot the columns of G
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
for i in range(G.shape[0]):
    ax.plot(G[i, :])

ax.set_title("Columns of matrix G")

#############################################
# Defining the Simulation
# -----------------------
#
# The simulation defines the relationship between the model parameters and
# predicted data.
#

sim = simulation.LinearSimulation(mesh, G=G, model_map=model_map)

#############################################
# Predict Synthetic Data
# ----------------------
#
# Here, we use the true model to create synthetic data which we will subsequently
# invert.
#

# Standard deviation of Gaussian noise being added
std = 0.01
np.random.seed(1)

# Create a SimPEG data object
data_obj = sim.make_synthetic_data(true_model, relative_error=std, add_noise=True)

#######################################################################
# Define the Inverse Problem
# --------------------------
#
# The inverse problem is defined by 3 things:
#
#     1) Data Misfit: a measure of how well our recovered model explains the field data
#     2) Regularization: constraints placed on the recovered model and a priori information
#     3) Optimization: the numerical approach used to solve the inverse problem
#

# Define the data misfit. Here the data misfit is the L2 norm of the weighted
# residual between the observed data and the data predicted for a given model.
# Within the data misfit, the residual between predicted and observed data are
# normalized by the data's standard deviation.
dmis = data_misfit.L2DataMisfit(simulation=sim, data=data_obj)

# Define the regularization (model objective function).
reg = regularization.WeightedLeastSquares(mesh, alpha_s=1.0, alpha_x=1.0)

# Define how the optimization problem is solved.
opt = optimization.InexactGaussNewton(maxIter=50)

# Here we define the inverse problem that is to be solved
inv_prob = inverse_problem.BaseInvProblem(dmis, reg, opt)

#######################################################################
# Define Inversion Directives
# ---------------------------
#
# Here we define any directiveas that are carried out during the inversion. This
# includes the cooling schedule for the trade-off parameter (beta), stopping
# criteria for the inversion and saving inversion results at each iteration.
#

# Defining a starting value for the trade-off parameter (beta) between the data
# misfit and the regularization.
starting_beta = directives.BetaEstimate_ByEig(beta0_ratio=1e-4)

# Setting a stopping criteria for the inversion.
target_misfit = directives.TargetMisfit()

# The directives are defined as a list.
directives_list = [starting_beta, target_misfit]

#####################################################################
# Setting a Starting Model and Running the Inversion
# --------------------------------------------------
#
# To define the inversion object, we need to define the inversion problem and
# the set of directives. We can then run the inversion.
#

# Here we combine the inverse problem and the set of directives
inv = inversion.BaseInversion(inv_prob, directives_list)

# Starting model
starting_model = np.zeros(nParam)

# Run inversion
recovered_model = inv.run(starting_model)

#####################################################################
# Plotting Results
# ----------------
#

# Observed versus predicted data
fig, ax = plt.subplots(1, 2, figsize=(12 * 1.2, 4 * 1.2))
ax[0].plot(data_obj.dobs, "b-")
ax[0].plot(inv_prob.dpred, "r-")
ax[0].legend(("Observed Data", "Predicted Data"))

# True versus recovered model
ax[1].plot(mesh.cell_centers_x, true_model, "b-")
ax[1].plot(mesh.cell_centers_x, recovered_model, "r-")
ax[1].legend(("True Model", "Recovered Model"))
ax[1].set_ylim([-2, 2])


# -*- coding:utf-8 -*-
from typing import List

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        if not nums: return []

        nums = nums + nums
        nums_len = len(nums)
        stack = []
        tmp = []
        for i in range(len(nums)):
            while stack and nums[stack[-1]] < nums[i]:
                cur = stack.pop()
                tmp.append([cur, nums[i]])

            stack.append(i)

        for i in range(len(stack)):
            tmp.append([stack[i], -1])
        tmp = sorted(tmp, key=lambda d: d[0])
        ans = []
        for i in range(nums_len // 2):
            ans.append(tmp[i][1])
        return ans

if __name__ == '__main__':
    # nums = [4, 2, 3, 1]
    nums = [1, 2, 1]
    ans = Solution().nextGreaterElements(nums)
    print(ans)