# This file is part of the GBI project.
# Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import urllib

from werkzeug.exceptions import NotFound
from flask import (render_template, Blueprint, flash,
    redirect, url_for, request, current_app, jsonify, g)

# XXX olt: do not import from flask.ext, makes trouble with pyinstaller
from flaskext.babel import gettext as _

from geobox.lib.couchdb import CouchFileBox
from geobox.lib.file_validation import get_file_information
from geobox.web.forms import UploadForm, ImportGeoJSONEdit
from geobox.model import VectorImportTask, User, GBIServer
from geobox.lib.server_logging import send_task_logging
from .vector import prepare_geojson_form

boxes = Blueprint('boxes', __name__)

@boxes.route("/box/<box_name>", methods=["GET", "POST"])
def files(box_name, user_id=None):
    is_consultant = current_app.config.geobox_state.user.is_consultant
    if (box_name == 'file' and not is_consultant):
        raise NotFound()
    if ((box_name == 'download' or box_name == 'upload') and is_consultant):
        raise NotFound()
    form = UploadForm()
    import_form = ImportGeoJSONEdit()
    import_form = prepare_geojson_form(import_form)

    couch_box = get_couch_box_db(box_name)

    host = request.headers.get('Host').split(':')[0]
    couch = CouchFileBox(
        'http://%s:%s' % (
            host,
            current_app.config.geobox_state.config.get('couchdb', 'port')
        ), couch_box)
    if form.validate_on_submit():
        file = request.files['file']
        overwrite = True if request.form.get('overwrite') == 'true' else False
        if file:
            data = get_file_information(file)
            if data:
                couch.store_file(data, overwrite=overwrite)
                flash(_('upload success'), 'success')
            else:
                flash(_('file type not allowed'), 'error')

    files = couch.all_files()
    for f in files:
        f['download_link'] = couchid_to_link(f['id'],
                                             couch_url=couch.couch_url)

    return render_template("boxes/%s.html" % box_name, form=form, files=files,
                           box_name=box_name, import_form=import_form)

def couchid_to_link(filename, couch_url):
    if isinstance(filename, unicode):
        filename = filename.encode('utf-8')
    return "%s/%s/file" % (couch_url, urllib.quote(filename))

def get_couch_box_db(box_name):
    app_state = current_app.config.geobox_state
    if box_name == 'download':
        couch_box_name = app_state.config.get('couchdb', 'download_box')
    elif box_name == 'upload':
        couch_box_name = app_state.config.get('couchdb', 'upload_box')
    elif box_name == 'file':
        couch_box_name = app_state.config.get('couchdb', 'file_box')
    else:
        raise NotFound()
    gbi_server = GBIServer.current_home_server(g.db)
    if gbi_server is None:
        return couch_box_name
    return '%s_%s' % (gbi_server.prefix, couch_box_name)

@boxes.route("/box/<box_name>/check_file", methods=["POST"])
def check_file_exists(box_name):

    couch_box = get_couch_box_db(box_name)
    couch = CouchFileBox('http://127.0.0.1:%s' % current_app.config.geobox_state.config.get('couchdb', 'port'), couch_box)
    existing_doc = couch.get(request.form['filename'])

    if existing_doc:
        return jsonify(existing=True)
    return jsonify(existing=False)

@boxes.route("/box/<box_name>/import/<id>", methods=["POST"])
def import_json(box_name, id):
    layer = request.form.get('layers', False)
    new_layer = request.form.get('name', False)
    file_name = request.form.get('file_name', False)
    title = None

    if (layer and new_layer) or (not layer and not new_layer):
        flash(_('please select new layer or current layer to import'), 'error')
        return redirect(url_for('.files', box_name=box_name))
    if layer:
        layer = layer
    else:
        title = new_layer
        layer = 'local_vector_' + re.sub(r'[^a-z0-9]*', '',  new_layer.lower())
        if layer == 'local_vector_':
            flash(_('None of the characters used for the layer is allowed'))
            return redirect(url_for('.files', box_name=box_name))

    task = VectorImportTask(
        db_name=layer,
        title=title,
        file_name=file_name,
        type_ = 'geojson',
        source = get_couch_box_db(box_name)
    )
    g.db.add(task)
    g.db.commit()
    flash(_("file will be imported"), 'success')
    return redirect(url_for('tasks.list'))

@boxes.route('/box/<box_name>/delete/<id>/<rev>', methods=["GET", "POST"])
def delete_file(box_name, id, rev):
    couch_box = get_couch_box_db(box_name)
    couch = CouchFileBox('http://127.0.0.1:%s' % current_app.config.geobox_state.config.get('couchdb', 'port'), couch_box)
    couch.delete(id, rev)
    flash(_("file deleted"), 'success')
    return redirect(url_for("boxes.files", box_name=box_name))


import os
import shutil
import cv2 as cv
from skimage.measure import compare_ssim
from tqdm import tqdm

def compareKeyFrame(frame1, frame2):
    return compare_ssim(frame1, frame2, multichannel=True)

    pass

def compareVideoFrame(video_path1, video_path2):
    cap1 = cv.VideoCapture(video_path1)

    VIDEO1_FPS = cap1.get(cv.CAP_PROP_FPS)
    VIDEO1_WIDTH = cap1.get(cv.CAP_PROP_FRAME_WIDTH)
    VIDEO1_HEIGHT = cap1.get(cv.CAP_PROP_FRAME_HEIGHT)
    VIDEO1_FRAME_COUNT = cap1.get(cv.CAP_PROP_FRAME_COUNT)

    VIDEO1_TOTAL_TIME = VIDEO1_FRAME_COUNT / VIDEO1_FPS

    cap2 = cv.VideoCapture(video_path2)
    VIDEO2_FPS = cap2.get(cv.CAP_PROP_FPS)
    VIDEO2_WIDTH = cap2.get(cv.CAP_PROP_FRAME_WIDTH)
    VIDEO2_HEIGHT = cap2.get(cv.CAP_PROP_FRAME_HEIGHT)
    VIDEO2_FRAME_COUNT = cap2.get(cv.CAP_PROP_FRAME_COUNT)

    VIDEO2_TOTAL_TIME = VIDEO2_FRAME_COUNT / VIDEO2_FPS

    if VIDEO1_WIDTH != VIDEO2_WIDTH or VIDEO1_HEIGHT != VIDEO2_HEIGHT:
        return False

    if abs(VIDEO1_TOTAL_TIME - VIDEO2_TOTAL_TIME) > 10:
        return False

    frame_count = 0
    key_frames = []
    for index in range(10):
        if index * (int(VIDEO1_FPS / 2)) < VIDEO1_FRAME_COUNT or index * (int(VIDEO2_FPS / 2)) < VIDEO2_FRAME_COUNT:
            key_frames.append(index * (int(VIDEO1_FPS / 2)))
        else:
            break
    score = 0
    while cap1.isOpened() or cap2.isOpened():
        suc1, frame1 = cap1.read()
        suc2, frame2 = cap2.read()
        if frame_count in key_frames:
            single_score = compareKeyFrame(frame1, frame2)
            score += single_score
        if frame_count > key_frames[len(key_frames) - 1]:
            break

        frame_count += 1

    score_avg = score / len(key_frames)
    cap1.release()
    cap2.release()
    print('\nscore_avg: ', score_avg)
    if score_avg > 0.5:
        return True
    else:
        return False

VIDEO_EXTENSIONS = [
    'mpg', 'mp4'
]

def is_video_file(filename):
    return any(filename.endswith(extension) for extension in VIDEO_EXTENSIONS)

def make_dataset(dir):
    videos = []
    assert os.path.isdir(dir), '%s is not a valid directory' % dir
    for root, _, fnames in sorted(os.walk(dir)):
        for fname in fnames:
            if is_video_file(fname):
                path = os.path.join(root, fname)
                videos.append(path)
    return videos

def findSourceVideo(Q_path, K_paths):
    Q_video_list = []
    K_video_list = []

    if isinstance(Q_path, list):
        for item in Q_path:
            Q_video_list.extend(make_dataset(item))
    else:
        Q_video_list.extend(make_dataset(Q_path))

    if isinstance(K_paths, list):
        for item in K_paths:
            K_video_list.extend(make_dataset(item))

    with open("q_to_k.txt", "w+") as f:
        for q_item in tqdm(Q_video_list):
            for k_item in K_video_list:
                if compareVideoFrame(q_item, k_item):
                    f.write(q_item)
                    f.write(":")
                    f.write(k_item)
                    f.write("\n")
                    print(" find source video:\n" + "q:" + q_item + "\n" + "k:" + k_item)
                    break
    pass

def copyTargetVideoFile():
    q_and_k_dict = {}
    with open("q_to_k.txt", "r") as f:
        while True:
            line = f.readline()
            if line:
                line = line.replace("\n", "")
                q_and_k = line.split(":")
                if len(q_and_k) == 2:
                    q_video = q_and_k[0]
                    k_video = q_and_k[1]
                    q_and_k_dict[q_video] = k_video
            else:
                break

    print(q_and_k_dict)
    pass

if __name__ == '__main__':
    Q_path = ['/home/letmesleep/data/test/q_folder']

    K_paths = ['/home/letmesleep/data/test/k_folder/k1',
               '/home/letmesleep/data/test/k_folder/k2',
               '/home/letmesleep/data/test/k_folder/k3'
               ]

    findSourceVideo(Q_path, K_paths)

    copyTargetVideoFile()


#!/usr/bin/env python

# WS client example

import asyncio
from common import const
import websockets
from tornado.options import options, define, parse_command_line

define("uid", 0, int, "uid start")

parse_command_line()

one_reader = False

async def worker(i):
    uid = options.uid + i
    await asyncio.sleep(0.01 * i)
    async with websockets.connect(
            f'ws://tx:3389/ws?token=pass&uid={uid}', ping_interval=const.PING_INTERVAL) as websocket:  # type: websockets.WebSocketClientProtocol
        resp = await websocket.recv()  # login resp
 #       await websocket.send('join')
        print(f"+++{resp} {uid}")
        ws.append((websocket, uid))
        while True:
            r = await websocket.recv()
            if not r:
                print(f'---exit {i}')
                break
            if i == 1:
                print(r)

ws = []
async def sender():
    from random import choice
    print('sending')
    while True:
        if ws:
            s, uid = choice(ws)
            await s.send(f'i am {uid}')
        await asyncio.sleep(0.1)
    print('exiting')

fs = []
for i in range(1000):
    f = asyncio.ensure_future(worker(i))
    fs.append(f)

# asyncio.ensure_future(sender())
asyncio.get_event_loop().run_until_complete(asyncio.wait(fs))


import json
import os
import unittest
from datetime import datetime

from src.steps.jsonserializer import JsonSerializer

class JsonSerializerTestCase(unittest.TestCase):
    _test_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data/test.json')

    _test_speeches = [
        {'speaker': 'HIŠ', 'timestamp': datetime.min, 'speech': 'HELLO'},
        {'speaker': 'BYEČ', 'timestamp': datetime.max, 'speech': 'GOODBYE'},
    ]

    def test_serialization(self):
        serializer = JsonSerializer(iter(self._test_speeches), self._test_file)

        for _ in serializer:
            pass

        with open(self._test_file) as speeches_file:
            speeches = json.load(speeches_file)
            self.assertEqual(len(speeches), 2)
            self.assertIsInstance(speeches, list)
            self.assertEqual(speeches[0]['speaker'], 'HIŠ')
            self.assertEqual(speeches[0]['timestamp'], datetime.min.isoformat())
            self.assertEqual(speeches[1]['speech'], 'GOODBYE')
            self.assertEqual(speeches[1]['timestamp'], datetime.max.isoformat())


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

# create the 5x5 mean filter
meanFilter = np.ones((5,5))/25

# create a 5x5 guassian filter
x = cv2.getGaussianKernel(5,1)
gaussian = x*x.T

# create a Laplacian filter
laplacian=np.array([[0, 1, 0],
                    [1,-4, 1],
                    [0, 1, 0]])

filters = [meanFilter, gaussian, laplacian]

# zero pad the filter (requirement of the convolution theorem)
# compute the Fourier transforms of the filters and plot the magnitude spectrum
padSize = 100
filters = [np.pad(m, ((padSize, ), (padSize, )), 'constant') for m in filters]
fft_filters = [np.fft.fft2(x) for x in filters]
fft_shift = [np.fft.fftshift(y) for y in fft_filters]
mag_spectrum = [np.log(np.abs(z)+1) for z in fft_shift]

# plotting
filter_name = ['Mean', 'Gaussian','Laplacian']
for i in range(3):
    plt.subplot(1,3,i+1),plt.imshow(mag_spectrum[i],cmap = 'gray')
    plt.title(filter_name[i]), plt.xticks([]), plt.yticks([])

plt.show()


__author__ = 'Murphy'
import unittest
import datetime, time
from Methods.LoginTools import LoginTools
from Methods.MemcacheTools import MemcacheTools
from Methods.WebDriverTools import WebDriverTools
from Methods.OtherTools import OtherTools
from config import app
from time import sleep

class Case087(unittest.TestCase):
    testCaseID = "Case087"
    projectName = "上海世贸皇家艾美"
    buzName = "能耗值查询"
    now = 'None'
    url = "http://%s" % app.config['SERVERIP']
    project = (395, 'shsmhjam', ['能源管理'], '#indexMain')

    def setUp(self):
        self.start = datetime.datetime.now()
        self.startTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()).split(" ")[-1]
        MemcacheTools.setMemTime(self.testCaseID,{"startTime":self.startTime})
        lg = LoginTools()
        self.driver = lg.InitialChrome(self.url,self.testCaseID)
        self.driver = lg.login(self.driver)
        self.tools = WebDriverTools()

    def tearDown(self):
        text=str([x[1] for x in self._outcome.errors if x[1]!=None])
        if "Exception" in text or "AssertionError" in text or self.errors!=[]:
            WebDriverTools.get_pic(self.driver, self.testCaseID)
        self.start = str((datetime.datetime.now() - self.start).seconds)
        self.start = self.start + "s"
        self.now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()).split(" ")[-1]
        self.driver.quit()
        MemcacheTools.setMemTime(self.testCaseID,{'start':self.startTime,'end':self.now})

    def Test(self):
        driver = self.driver
        self.errors = []
        self.tools.enterProject(driver, self.project[0], self.project[1], self.errors)
        sleep(3)
        self.tools.enterPage(driver, self.project[2], self.project[3], self.project[1], timeout=180)
        self.GetEnergyValue(driver)

        OtherTools.raiseError(self.errors)
        print('上海世贸皇家艾美酒店，检查负值，测试完成！')

    def GetEnergyValue(self, driver):
        strTodayTotalEnergy = driver.find_element_by_xpath("//div[@id='threeItem1']/div/div/p[1]/span").text
        strEnergy0 = driver.find_element_by_xpath("//div[@id='legendData00']/div[2]/div[3]/span").text
        strEnergy1 = driver.find_element_by_xpath("//div[@id='legendData01']/div[2]/div[3]/span").text
        strEnergy2 = driver.find_element_by_xpath("//div[@id='legendData02']/div[2]/div[3]/span").text
        strEnergy3 = driver.find_element_by_xpath("//div[@id='legendData03']/div[2]/div[3]/span").text
        strEnergy4 = driver.find_element_by_xpath("//div[@id='legendData04']/div[2]/div[3]/span").text
        strEnergy5 = driver.find_element_by_xpath("//div[@id='legendData05']/div[2]/div[3]/span").text
        strEnergy6 = driver.find_element_by_xpath("//div[@id='legendData06']/div[2]/div[3]/span").text
        strEnergy7 = driver.find_element_by_xpath("//div[@id='legendData07']/div[2]/div[3]/span").text
        strEnergy8 = driver.find_element_by_xpath("//div[@id='legendData08']/div[2]/div[3]/span").text
        strEnergy9 = driver.find_element_by_xpath("//div[@id='legendData09']/div[2]/div[3]/span").text
        strEnergy10 = driver.find_element_by_xpath("//div[@id='legendData10']/div[2]/div[3]/span").text
        strEnergy11 = driver.find_element_by_xpath("//div[@id='legendData11']/div[2]/div[3]/span").text
        strEnergy12 = driver.find_element_by_xpath("//div[@id='legendData12']/div[2]/div[3]/span").text
        strEnergy13 = driver.find_element_by_xpath("//div[@id='legendData13']/div[2]/div[3]/span").text
        strEnergy14 = driver.find_element_by_xpath("//div[@id='legendData14']/div[2]/div[3]/span").text
        strLastDayEnergy = driver.find_element_by_id('lastDayEnergyValue').text

        todayTotalEnergy = self.ParseEnergyValue(strTodayTotalEnergy)
        energy0 = self.ParseEnergyValue(strEnergy0)
        energy1 = self.ParseEnergyValue(strEnergy1)
        energy2 = self.ParseEnergyValue(strEnergy2)
        energy3 = self.ParseEnergyValue(strEnergy3)
        energy4 = self.ParseEnergyValue(strEnergy4)
        energy5 = self.ParseEnergyValue(strEnergy5)
        energy6 = self.ParseEnergyValue(strEnergy6)
        energy7 = self.ParseEnergyValue(strEnergy7)
        energy8 = self.ParseEnergyValue(strEnergy8)
        energy9 = self.ParseEnergyValue(strEnergy9)
        energy10 = self.ParseEnergyValue(strEnergy10)
        energy11 = self.ParseEnergyValue(strEnergy11)
        energy12 = self.ParseEnergyValue(strEnergy12)
        energy13 = self.ParseEnergyValue(strEnergy13)
        energy14 = self.ParseEnergyValue(strEnergy14)
        lastDayEnergy = self.ParseEnergyValue(strLastDayEnergy)

        self.CheckValue(todayTotalEnergy)
        self.CheckValue(energy0)
        self.CheckValue(energy1)
        self.CheckValue(energy2)
        self.CheckValue(energy3)
        self.CheckValue(energy4)
        self.CheckValue(energy5)
        self.CheckValue(energy6)
        self.CheckValue(energy7)
        self.CheckValue(energy8)
        self.CheckValue(energy9)
        self.CheckValue(energy10)
        self.CheckValue(energy11)
        self.CheckValue(energy12)
        self.CheckValue(energy13)
        self.CheckValue(energy14)
        self.CheckValue(lastDayEnergy)

        sleep(3)

    def ParseEnergyValue(self, value):
        if 'NaN'in value or "None" in value or "Null" in value:
            return False
        else:
            value = str(value)
            value = value.replace(',', '')
            value = value.replace(' ', '')
            value = value.replace('kWh', '')
            if value=="0.0":
                return 0
            else:
                return int(value)

    def CheckValue(self, value):
        if isinstance(value,int):
            if value < 0:
                self.errors.append('数值：' + str(value) + ' 小于0！')
        else:
            self.errors.append('数值：' + str(value) + ' 返回数据values为空！')

if __name__ == "__main__":
    suit = unittest.TestSuite()
    suit.addTest(Case087('Test'))
    runner = unittest.TextTestRunner()
    runner.run(suit)


import asyncio
import logging

import pytest

import lightbus
from lightbus import BusNode

logger = logging.getLogger(__name__)

@pytest.fixture
def redis_rpc_transport(new_redis_pool, server, loop):
    """Get a redis transport backed by a running redis server."""
    return lightbus.RedisRpcTransport(redis_pool=new_redis_pool(maxsize=10000))

@pytest.fixture
def redis_result_transport(new_redis_pool, server, loop):
    """Get a redis transport backed by a running redis server."""
    return lightbus.RedisResultTransport(redis_pool=new_redis_pool(maxsize=10000))

@pytest.fixture
def redis_event_transport(new_redis_pool, server, loop):
    """Get a redis transport backed by a running redis server."""
    return lightbus.RedisEventTransport(redis_pool=new_redis_pool(maxsize=10000),
                                        consumer_group_prefix='test_cg', consumer_name='test_consumer')

@pytest.fixture
def redis_schema_transport(new_redis_pool, server, loop):
    """Get a redis transport backed by a running redis server."""
    logger.debug('Loop: {}'.format(id(loop)))
    return lightbus.RedisSchemaTransport(redis_pool=new_redis_pool(maxsize=10000))

@pytest.fixture
def bus(loop, redis_rpc_transport, redis_result_transport, redis_event_transport, redis_schema_transport):
    """Get a redis transport backed by a running redis server."""
    return lightbus.create(
        rpc_transport=redis_rpc_transport,
        result_transport=redis_result_transport,
        event_transport=redis_event_transport,
        schema_transport=redis_schema_transport,
        loop=loop,
    )

@pytest.fixture(name='fire_dummy_events')
def fire_dummy_events_fixture(bus):
    async def fire_dummy_events(total, initial_delay=0.1):
        await asyncio.sleep(initial_delay)
        for x in range(0, total):
            await bus.my.dummy.my_event.fire_async(field=x)
        logger.warning('TEST: fire_dummy_events() completed')
    return fire_dummy_events


from BurstCube.NoahSim import burstutils
from BurstCube.NoahSim import NoahCube
#this obeys the correct format, but my path is off I think for it to work on my local system.
import numpy as np
from astropy.tests.helper import pytest

@pytest.fixture(scope='module')
def create_sky(request):
        testsim = NoahCube.Sky(1, 500)

        return testsim

@pytest.fixture(scope='module')
def create_BurstCube(request):

        testcube = NoahCube.BurstCube(1000, 45)

        return testcube

def test_det():

        tc = NoahCube.BurstCube(1000,45)

        result = [[0.78539816339744828, 0],
                  [0.78539816339744828, 1.5707963267948966],
                  [0.78539816339744828, 3.141592653589793],
                  [0.78539816339744828, 4.71238898038469]]

        dets = [getattr(tc, 'det{}'.format(letter))
                for letter in ['A', 'B', 'C', 'D']]

        np.testing.assert_allclose(dets, result, 1e-16)

# def test_fastcube():
#        testsim = GRBgenerator.Sky(1, 500)
#        testcube = fastcube.FastCube(1000, 45)
#        testresponse = testcube.response2GRB(testsim, samples=10,
#                                             test=True, talk=False)

        # leaving this a little more room for error
        # since I'm messing up one detector.
#        np.testing.assert_allclose(testresponse[0], 6.0, 1.0)


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 16:50:39 2018

@author: Main Desktop
"""
try:
    import ChangingBattleship
    import BattleshipShooter
    import tkinter
    from PIL import Image, ImageTk
    import socket
    from threading import Thread
    from pickle import dumps, loads
    from time import sleep
except Exception as ex:
    print(ex)
    input('Import error. Press enter to exit')
    raise 'Do not continue with this'

class myApp(tkinter.Tk):
    def __init__(self, totalBoats, boardSize):
        tkinter.Tk.__init__(self)
        self.totalBoats = totalBoats
        self.boardSize = boardSize
        # object variables
        self.player2= None
        self.player1 = ChangingBattleship.BattleShip(totalBoats,boardSize)

        ## NETWORKING STUFF ##
        networking = True
        if networking:
            hoster = input('Press enter if you are not John\n')
            if hoster == 'true':
                self.submitValid = True
                self.playerNum, self.otherPlayerNum = 1 , 2
                self.host = '0.0.0.0'
                self.startConnectionHost()
                self.recvBoard()
                self.sendBoard()
            else:
                self.submitValid = False
                self.playerNum, self.otherPlayerNum = 2, 1
                print("CLIENT NETWORKING OPTION SELECTED\n\n")
                self.host = input("Enter IP Provided by John: ")
                self.startConnectionClient()
                self.sendBoard()
                self.recvBoard()
            print('Initalizing thread...')
            Thread(target=self.recvChat, name='recv').start()

        # basic things about the tkinter window
        self.title('Battleship!')
        # Geometry does (y, x), so y value is first
        self.geometry("800x600")
        self.playerLabel = tkinter.Label(self, text=("You are player %s!" % self.playerNum))
        self.playerLabel.pack()
        self.entryBox = tkinter.Entry(self)

        self.label = tkinter.Label(self, text="Hit submit to fire!")
        self.label.place(x=0,y=145)
        self.entryBox2 = tkinter.Entry(self)
        self.entryBox2.place(x=0, y=170)
        self.entryBox.place(x=0,y=125)
        self.l2 = tkinter.Label(self, text="The status of your \nshot will apear here")
        self.l2.place(x=130,y=180)
        self.chatEntryBox = tkinter.Entry(self, width=80)

        self.xChatBase = 105
        self.chatBase = 300
        self.chatEntryBox.place(x=self.xChatBase-5,y=self.chatBase + 210)
        self.chatBackground = tkinter.Label(self, width=68, height=8, background='white')
        self.chatBackground.place(x=self.xChatBase-5,y=self.chatBase+75)

        #print(self.otherPlayersBoard, self.otherPersonsBoard)
        self.otherPlayersBoard = self.player2.getBoard()
        self.filledShip = self.player2.shipFilled
        self.currentPlayerShots = BattleshipShooter.shootAt(self.player2)

        self.shotHistory = self.currentPlayerShots.shotHistory
        self.showBoardOnGUI(280, 50, self.shotHistory)

        self.prevMessages = []

        self.bind("<Return>", self.sendChat)
        self.createLabels()
        self.createButtons()
        self.showMeMyBoard()

    def updateShootingBoard(self):
        # runs when the other player rerolls their board.
        # just updates the shot board
        self.otherPlayersBoard = self.player2.getBoard()
        self.filledShip = self.player2.shipFilled
        self.currentPlayerShots = BattleshipShooter.shootAt(self.player2)
        self.shotHistory = self.currentPlayerShots.shotHistory
        ## TODO: self.shotHistory is what needs to be sent. Find out how to
        # have recv board or whatever accept a placement for it. ty.
        self.showBoardOnGUI(280, 50, self.shotHistory)

    def twoSubmitFuncs(self):
        rowOFshot, columnOFshot = int(self.entryBox.get())-1, int(self.entryBox2.get())-1
        y =self.currentPlayerShots.shotHistory[rowOFshot][columnOFshot]
        self.maybeShowUpdatedButton(y)
        #self.currentPlayerShots.displayPrevShots()
        # determines if player can take a shot, and if so, whether they hit or miss
        if self.submitValid:
            if self.otherPlayersBoard[rowOFshot][columnOFshot] == '.':
                self.submitValid = False
                self.currentPlayerShots.attack(int(self.entryBox.get()), int(self.entryBox2.get()))
                self.maybeShowUpdatedButton('You\'ve missed! Other person\'s turn')
                self.c.send(bytes('pass code 546451222', encoding='ascii'))
                self.currentTurnLabelUpdater()
            elif self.otherPlayersBoard[rowOFshot][columnOFshot] == 'X':
                self.currentPlayerShots.attack(int(self.entryBox.get()), int(self.entryBox2.get()))
                self.maybeShowUpdatedButton('You hit them!\nGo again!')
            else:
                        #self.currentPlayerShots.attack(int(self.entryBox.get()), int(self.entryBox2.get()))
                self.maybeShowUpdatedButton('You\'ve already shot here!\nStill your turn!')
            self.showBoardOnGUI(280, 50, self.shotHistory)
            pickledHistory = dumps(self.shotHistory)
            self.c.send(pickledHistory)
        else:
            self.maybeShowUpdatedButton('It\'s not your turn yet')

    def currentTurnLabelUpdater(self):
        if self.submitValid == False:
            player = self.otherPlayerNum
        else: player = self.playerNum
        self.currentTurnDisplayer.destroy()
        self.currentTurnDisplayer = tkinter.Label(self, text='Player %s\'s turn' % player)
        self.currentTurnDisplayer.place(x=20, y=15)

    def sendBoard(self):
        print('Sending board')
        data=dumps(self.player1)
        self.c.send(data)
        print('Successfully sent')

    def recvBoard(self):
        print('Attempting to load other players board')
        x = self.c.recv(1024)
        hi = self.player2=loads(x)
        #print(hi, 'revied')
        self.showBoardOnGUI(800, 50, hi.getBoard())
        print('Board recieved')

    def getActiveEntryBox(self):
        # TODO I don't know if this is possible or not.
        # when the enter key is pressed, get what entryBox is active
        # and submit the relavent function to the entry field
        pass

    ## NETWORKING ##
    def startConnectionHost(self):
        print('ATTEMPTING TO CONNECT TO CLIENT...')
        self.s = socket.socket()
        host = self.host # IP of host machine
        port = 7002
        self.s.bind((host,port))
        self.s.listen(1) # allows for only 1 active connection
        self.c, addr = self.s.accept()
        print('Got connection from', addr)

    def submitBoard(self):
        # destorys tutoritals and enables user to fire
        self.rerollBoard.destroy()
        self.sendBoardButton.destroy()
        self.shotHistoryBoard.destroy()
        self.finalTutorial.destroy()
        self.OwnBoardTutorial.destroy()
        button = tkinter.Button(self, text='Submit', command=self.twoSubmitFuncs)
        button.place(x=130,y=140)

    def startConnectionClient(self):
        self.s = socket.socket()
        host = self.host
        port = 7002
        while True:
            try:
                self.s.connect((host, port))
                break
            except Exception:
                print('Connection failed to host: %s \nFrom port: %s'% (host, port))
                sleep(3)
        # makes it so I don't have to change any variable names between host and client
        self.c = self.s

    def recvChat(self):
        while True:
            x = self.c.recv(1024)
            try:
                # pickle rickkkk
                self.player2=loads(x)
                if type(self.player2) == ChangingBattleship.BattleShip:
                    # means that the other player has rerolled their board
                    # so current player has to receive and update their
                    # existing board.
                    self.showBoardOnGUI(800, 50, self.player2.getBoard())
                    self.updateShootingBoard()
                else:
                    # should mean this is a shothistory board
                    # I know this is weird, but in this case
                    # player 2 will = their SHOTHISTORY
                    self.showBoardOnGUI(self.chatBase+90, 200, self.player2)
            except:
                x = x.decode('utf-8')
                if x == 'pass code 546451222':
                    self.submitValid = True
                    self.currentTurnLabelUpdater()
                #self.prevMessages.append(tkinter.Label(self,text=('Them: %s' % self.c.recv(1024).decode('utf-8')), background='white'))
                else:
                    self.prevMessages.append(tkinter.Label(self,text=('Them: %s' % x), background='white'))
                    self.updateChat('do nothing with this')

    def sendToOtherPerson(self):
        self.c.send(bytes(self.chatEntryBox.get(), encoding='ascii'))

    # the bind function sends some info with it to this function automatically.
    # i don't know what to do with it so i don't think it's important
    def sendChat(self, doNothingWithThis):
        # first we set where the top of the chat appears
        # 225-18
        self.prevMessages.append(tkinter.Label(self,text=('You: %s' % self.chatEntryBox.get()), background='white')) # adds a label to the list for easy looping
        # reset and focus on the chat Entry box so content within are deleted, and you can continue to type
        try:self.sendToOtherPerson()
        except AttributeError: print("No active connection. Chat function disabled")
        self.updateChat(self.chatEntryBox.get())
        self.chatEntryBox.destroy()
        self.chatEntryBox = tkinter.Entry(self, width=80)
        self.chatEntryBox.place(x=self.xChatBase-5,y=self.chatBase + 210)
        self.chatEntryBox.focus()

    def updateChat(self, doNothingWithThis):
        self.y = self.chatBase + 75
        if len(self.prevMessages) >= 7: # chat box only comfortables displays 7 lines, so destory old labels and delete them from list
            self.prevMessages[0].destroy()
            del self.prevMessages[0]
        for eachMessage in range(len(self.prevMessages)): # print the suckers
            self.prevMessages[eachMessage].place(x=self.xChatBase, y=self.y)
            self.y += 18 # drops the next label down some so there's no overlap between messages

    ## LABELS AND BUTTON ON START ##

    def createLabels(self):
        self.shotHistoryBoard = tkinter.Label(self, text='Shows the areas you\'ve shot --->')
        self.shotHistoryBoard.place(x=100,y=100)
        self.OwnBoardTutorial = tkinter.Label(self,text='<-- This is your own board.\nClick the button up top to reroll it')
        self.OwnBoardTutorial.place(x=610,y=100)
        self.finalTutorial = tkinter.Label(self, text='Click here once you\'ve read all stuff and are satisfied with your board-->')
        self.finalTutorial.place(x=250, y=195)
        self.currentTurnDisplayer = tkinter.Label(self, text='Player 1\'s turn')
        self.currentTurnDisplayer.place(x=20, y=15)
        self.otherPersonShotTutorial = tkinter.Label(self, text='Places enemy has shot -->')
        self.otherPersonShotTutorial.place(x=self.chatBase-90, y=260)
        # func to create a bunch of buttons
    def createButtons(self):
        self.rerollBoard = tkinter.Button(self, text='Reroll own board', command=self.rerollPlayersBoard)
        self.rerollBoard.place(x=510, y=30)
        # fire submit button moved to sendBoard function to prevent firing before
        # board is finalized
        self.sendBoardButton = tkinter.Button(self, text='Finalize Board', background ='red', command=self.submitBoard)
        self.sendBoardButton.place(x=635,y=190)

    # works in tandem with the getInputBoxField method
    def maybeShowUpdatedButton(self,message):
        try: self.l2.destroy() # removes old label so there's no ugly overlap
        except AttributeError: pass
        self.l2 = tkinter.Label(self, text=message)
        self.l2.place(x=130,y=190)

    # When a the submit button is pressed, it will activate this function which grabs the entered fields
    # and sends a message to the update label function, which will update the user about their shot.
    def getInputBoxField(self):
        try:
            if self.otherPlayersBoard[int(self.entryBox.get()) -1][int(self.entryBox2.get())-1] == self.filledShip:
                self.currentPlayerShots.attack(int(self.entryBox.get()), int(self.entryBox2.get()))
                self.maybeShowUpdatedButton('Hit!')
            else:
                self.currentPlayerShots.attack(int(self.entryBox.get()), int(self.entryBox2.get()))
                self.maybeShowUpdatedButton('Miss')
        except ValueError:
            self.maybeShowUpdatedButton('A field is blank.\nShot not sent.')

    def showMeMyBoard(self):
        # shows player their own board so they can decide if they
        # reroll it if they desire
        player1Board = self.player1.getBoard()
        self.showBoardOnGUI(500, 50, player1Board)

    def rerollPlayersBoard(self):
        # creates a new board and displays it
        self.player1 = ChangingBattleship.BattleShip(self.totalBoats,self.boardSize)
        self.showMeMyBoard()
        self.sendBoard()

    def showBoardOnGUI(self, xPoint, yPoint, whatBoard):
        #  Simply creates the board on screen with the relavant imagery
        i, j = xPoint, yPoint
        for eachList in whatBoard:
            j +=20
            i= xPoint
            ## WARNING ##
            # if the labels aren't updated in the for loops, it won't update the display
            # of the list for some reasons. they have to be there.
            for eachValue in eachList:
                if eachValue == ".":
                    image = Image.open("sea.png")
                    photo = ImageTk.PhotoImage(image)
                    label2 = tkinter.Label(image=photo)
                    label2.image = photo # keep a reference!
                    label2.place(x=i,y=j)
                elif eachValue == "|" or eachValue == "X":
                    hitImage = Image.open("hit.png")
                    photoOFhit = ImageTk.PhotoImage(hitImage)
                    labelOFhit = tkinter.Label(image=photoOFhit)
                    labelOFhit.image = photoOFhit # keep a reference!
                    labelOFhit.place(x=i,y=j)
                elif eachValue == "*":
                    imageOFmiss = Image.open("miss.png")
                    photoOFmiss = ImageTk.PhotoImage(imageOFmiss)
                    labelOFmiss = tkinter.Label(image=photoOFmiss)
                    labelOFmiss.image = photoOFmiss # keep a reference!
                    labelOFmiss.place(x=i,y=j)
                else:
                    print('Mystery value found: %s' % eachValue)
                i += 20
try:
    app = myApp(5,6)
    app.mainloop()
except Exception as ex:
    print(ex)
    input('\n\n\nError in main loop. Show this to John!')

# TODO Label row and column of shot  Entry box
# todo label row and column of grids

# TODO flash screen when turn


from flask import jsonify, views, request

from app import db
from models import Department, Location, Country

class DepartmentApi(views.MethodView):

    def get(self, country_id=None):
        if not country_id:
            return jsonify([a.serialize for a in Department.query.all()])
        else:
            departmentsCountry = db.session.query(Department,Location,Country)\
                .filter(Country.country_id == Location.country_id)\
                .filter(Department.location_id == Location.location_id)\
                .filter(Country.country_id == country_id)\
                .all()

            json = []
            for department, location, country in departmentsCountry:
                dict = {}
                dict.update(department.serialize)
                dict.update(location.serialize)
                dict.update(country.serialize)
                json.append(dict)

            return jsonify(json)

    def post(self):
        if request.json:
            data = request.json
        else:
            data = request.form

        if(len(str(data.get('department_id'))) == 0
          or int(data.get('department_id')) == 0
          or len(data.get('department_name')) == 0):

            return jsonify({'message': 'Informe o Dpt ID e Dpt Name.'}), 409

        departmentID = Department.query.filter_by(department_id=data.get('department_id')).first()
        managerID = None

        if data.get('manager_id') != None:
            managerID = Department.query.filter_by(manager_id=data.get('manager_id')).first()

        if departmentID:
            return jsonify({'message': 'Dpt ID já cadastrado.'}), 409

        if managerID:
            return jsonify({'message': 'Manager ID já cadastrado.'}), 409

        department = Department().department_form_data(data)

        db.session.add(department)

        try:
            db.session.commit()
            return jsonify(
                {'message': 'Department inserido.'})
        except Exception as e:
            return jsonify({'message': 'Não foi possivel executar a operação.'}), 500

    def put(self):
        if request.json:
            data = request.json
        else:
            data = request.form

        if (len(str(data.get('department_id'))) == 0
                or int(data.get('department_id')) == 0
                or len(data.get('department_name')) == 0):
            return jsonify({'message': 'Informe o Dpt ID e Dpt Name.'}), 409

        editedDepartment = Department.query.filter_by(department_id=data.get('department_id')).first()
        editedDepartment.department_name = data.get('department_name')
        editedDepartment.manager_id = data.get('manager_id')
        editedDepartment.location_id = data.get('location_id')

        db.session.add(editedDepartment)

        try:
            db.session.commit()
            return jsonify(
                {'message': 'Department atualizado.'})
        except Exception as e:
            return jsonify({'message': 'Não foi possivel executar a operação.'}), 500

    def delete(self, id):
        Department.query.filter_by(department_id=id).delete()

        try:
            db.session.commit()
            return jsonify(
                {'message': 'Department removido.'})
        except Exception as e:
            return jsonify({'message': 'Não foi possivel executar a operação.'}), 500


#邮件发送测试.py
import sendEmail
count=1
for i in range(count):
	email=sendEmail.sendEmail("smtp.163.com","pengshiyuyx@163.com","","彭世瑜")
	ret=email.send("pengsy@byzxt.com.cn","dear","测试邮件名称","测试邮件内容")

	if ret==0:
		print("发送成功",i+1)
	else:
		print("发送失败",i+1)


# Evan Sauers
# Collaborated with Dr. Neumann, Marissa Gross, and Rebekah Orth
# File Header-piggetty.py
#
# Add your name to this:
# Evan Sauers

# Define a function called piggy(string) that returns a string
#
# File Header
#
# Define vowels

vowels = "aeiouAEIOU"

# Loop through word, one letter at a time
def piggy(word):
	n = 0
	endword = ""
	for letter in word:
		# Check if letter is a vowel
		if n == 0:
			# True?  We are done
			pig = word + "yay"
			return pig
		else:
			# False? Consonant
			pig = word[n:] + endword + "ay"
			return pig
	else:
		endword = endword + word[n]
		n = n + 1

#Ask for word

word = input("Please enter a word: ")
print (piggy(word))

def piggy(word):

	# Magic Happens Here
	pig = word
	# Ignore previous line

	return pig

# Open the file *getty.txt* for reading.
gettyFile = open("getty.txt", "r")

# Open a new file *piggy.txt* for writing.
piggyFile = open("piggy.txt", "w")

# Read the getty.txt file into a string.
gettyString = gettyFile.read()

# Strip out bad characters (, - .).
gettyString = gettyString.replace(",", "")
gettyString = gettyString.replace(".", "")
gettyString = gettyString.replace("-", "")

# Split the string into a list of words.
gettylist = gettyString.split()

# Create a new empty string.
pigstring = ""

# Loop through the list of words, pigifying each one.
for word in gettylist:

# Add the pigified word (and a space) to the new string.
	if len(word) > 0:
			pigstring = pigstring + piggy(word) + " "

# Write the new string to piggy.txt.
print (pigstring, file = piggyFile)

# close the files.
gettyFile.close()
piggyFile.close()


import sympy as sym
import numpy as np

# returns True if number in an integer
def is_integer(num):
    num = 2 * num
    if num % 2 == 0:
        return True
    else:
        return False

# finds all unique prime factors of a number
def prime_factors(x):
    p_factors = []
    for i in range(1, (x//2) + 1):
        if sym.isprime(i) and x % i == 0:
            p_factors.append(i)
    return p_factors

# expresses a number as its prime factors
def p_factn(x):
    factorisation = []
    p_factors = prime_factors(x)
    for i in p_factors:
        stop = False
        while not stop:
            if is_integer(x/i):
                factorisation.append(int(i))
                x = x/i
            else:
                stop = True
    return factorisation

# calculates the lowest common multiple of any number of given integers
def LCM(*args):
    primes = []
    non_primes = []

    # splits input sequence into primes and non-primes
    for i in args:
        if sym.isprime(i):
            primes.append(i)
        elif not sym.isprime(i) and i != 1:
            non_primes.append(i)

    # expresses non-primes as a product of prime factors
    factorised_non_primes = []
    for i in non_primes:
        x = p_factn(i)
        factorised_non_primes.append(x)

    # Removes unique primes from factorised_non_primes output from original primes list
    unique_primes = set()
    for i in factorised_non_primes:
        for j in i:
            unique_primes.add(j)
    unique_primes = list(unique_primes)
    for i in unique_primes:
        primes.remove(i)

    # creates dictionary with unique prime keys and values equal to its largest exponent from the factorised_non_primes output
    exponents = []
    for i in unique_primes:
        x = 0
        for j in factorised_non_primes:
            y = j.count(i)
            if y > x:
                x = y
        exponents.append(x)
    exponents = dict(zip(unique_primes,exponents))

    # calculates lowest common multiple
    lcm = 1
    for i in unique_primes:
        lcm = lcm * i ** (int(exponents[i]))
    lcm = lcm * np.prod(primes)
    return lcm

seq = list(range(1,21))
print(LCM(*seq))


#!/usr/bin/python3

from gpiozero import Button

button = Button(2)

try:
    while True:
        if button.is_pressed:
            print("Button is pressed")
        else:
            print("Button is not pressed")
except KeyboardInterrupt:
    print("interrupted!")
    button.close()


class Solution(object):
    def isMatching(self, s, p):
        #if not s or not p:
            #return False
        s_len = len(s)
        p_len = len(p)
        dp = [[False] * (p_len + 1) for _ in range(s_len + 1)]
        print(dp)
        dp[0][0] = True
        for i in range(p_len):
            if p[i] == "*" and dp[0][i - 1]:
                dp[0][i + 1] = True
        print(dp)
        for i in range(s_len):
            for j in range(p_len):
                if p[j] == s[i] or p[j] == ".":
                    dp[i + 1][j + 1] = dp[i][j]
                elif p[j] == "*":
                    if p[j - 1] != s[i]:
                        dp[i + 1][j + 1] = dp[i + 1][j - 1]
                    if p[j-1] == s[i] or p[j-1] == ".":
                        dp[i+1][j+1] = (dp[i][j+1] or dp[i+1][j]   or  dp[i+1][j-1])
        print(dp)
        return dp[-1][-1]

if __name__ == "__main__":
    solve = Solution()
    print(solve.isMatching('aa', 'a'))


import time
import gym
import numpy as np
import decimal

env = gym.make('CartPole-v0')
q_table = [] #Where each line of this Q-table is state, action 1, action 2, Q-value 1, Q-value 2
#Learning parameters
learning_rate = 0.1
gamma = 0.99
r_init = 20

t = 0
i_episode = 0
benchmark = 75

while i_episode < 1000:
    if i_episode % 500 == 0:
        print(q_table)
        print(len(q_table))
    observation = env.reset()
    observation = [round(observation[i],3) for i in range(len(observation))]
    observation = [observation[2],observation[3]]
    for t in range(2000): #For each timestep t in episode i_episode...
        found = False
        env.render()
        #Search for state in Q-table and choose action based on action there
        for i in range(len(q_table)):
            if np.array_equal(q_table[i][0],observation):
                found = True
                if q_table[i][3] == q_table[i][4]:
                    action = env.action_space.sample()
                else:
                    #action = (np.argmax([q_table[i][3],q_table[i][4]]) - 3) #Action is either 0 or 1
                    action = 1
                    q_t = q_table[i][action+3] #Q-value of the action at state s_t
                s_t = i
        else: #If not in Q-table, sample random action
            if found == False:
                action = env.action_space.sample()
                q_table.append([observation,0,1,r_init,r_init])
                #print("Added %s to the Q-table" % action)
                s_t = len(q_table)-1
                a_t = q_table[s_t][action+3]
        found = False
        observation, reward, done, info = env.step(action) #Take action and observe reward
        observation = [round(observation[i],3) for i in range(len(observation))]
        observation = [observation[2],observation[3]]
        #Find location of new state s_t+1 (s_tt) in Q-table
        for j in range(len(q_table)):
            if np.array_equal(q_table[j][0],observation):
                found = True
                s_tt = j
                #Q-value updated towards landing state's argmax Q-value
                q_table[s_t][action+3] += learning_rate * ((reward + (gamma * max(q_table[s_tt][3],q_table[s_tt][4]))) - q_table[s_t][action+1])
        else: #If this new state has not been visited before
            if found == False:
                q_table[s_t][action+3] += learning_rate * ((reward + (gamma * r_init)) - q_table[s_t][action+1])
        if done:
            t += t
            print("Episode {} finished after {} timesteps".format(i_episode,t))
            i_episode += 1
            break


#-- Python imports --#
from __future__ import division
import threading, pygame, math, sys, datetime

import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS

#-- Local file imports --#
import SampleFramework as sf
from ShrewFrameListener import ShrewFrameListener

from MeshMaker import MeshMaker
from PlaneMaker import PlaneMaker

#-- Path imports --#
sys.path.append("../dataObjects")
from ExperimentData import States, ExperimentData

class Shrewenstein3D(sf.Application):
    def init(self):
        #__init__ is defined in sf.Application, so we do our actual init'ing here.
        self.planeMaker = PlaneMaker(self.sceneManager)
        self.meshMaker = MeshMaker(self.sceneManager)

        #get instance of ExperimentData, we need its info to set up the scene
        self.exData = ExperimentData()

        #start events engine
        pygame.init()

    def _createScene(self):
        self.init()

        exData = self.exData

        #lights!
        self.sceneManager.ambientLight = (0.5,0.5,0.5) #using *mostly* ambient light, with minor lighting for contours.
        light = self.sceneManager.createLight('goal1Light')
        light.type = ogre.Light.LT_POINT
        lightPos = list(self.exData.goal1Pos)
        lightPos[0] = lightPos[0] - 100
        light.position = lightPos
        light.diffuseColour = 1, 1, 1
        light.specularColour = 1, 1, 1

        light = self.sceneManager.createLight('goal2Light')
        light.type = ogre.Light.LT_POINT
        lightPos = list(self.exData.goal2Pos)
        lightPos[0] = lightPos[0] + 100
        light.position = lightPos
        light.diffuseColour = 1, 1, 1
        light.specularColour = 1, 1, 1

        light = self.sceneManager.createLight('sampleLight')
        light.type = ogre.Light.LT_POINT
        lightPos = list(self.exData.samplePos)
        lightPos[2] = lightPos[2] - 100
        light.position = lightPos
        light.diffuseColour = 1, 1, 1
        light.specularColour = 1, 1, 1

        #room
        cubeTextures=[
            'Tupaia3D/Gray',#floor
            'Tupaia3D/Gray',#ceiling
            'Tupaia3D/WallPaint',#left
            'Tupaia3D/WallPaint',#right
            'Tupaia3D/WallPaint',#front wall
            'Tupaia3D/WallPaint',#back wall
            ]

        cube1Size = (exData.roomSizeX,exData.roomSizeY,exData.roomSizeZ)
        cube1Center = (0,exData.roomSizeY/2,exData.roomSizeZ/2)
        self.planeMaker.makeCube(objName='room', textureNames=cubeTextures, centerPoint=cube1Center, size=cube1Size, normalsPointOut=False)

        #cylinders
        self.meshMaker.makeCylinderMesh(name='goalMarkerMesh', radius=10, height=100, sides=12)

        ent = self.sceneManager.createEntity('goalCylinder1', 'goalMarkerMesh')
        ent.setMaterialName('Tupaia3D/Blue')
        node = self.sceneManager.getRootSceneNode().createChildSceneNode('goalCylinder1', self.exData.goal1Pos)
        node.attachObject(ent);

        ent = self.sceneManager.createEntity('goalCylinder2', 'goalMarkerMesh')
        ent.setMaterialName('Tupaia3D/Blue')
        node = self.sceneManager.getRootSceneNode().createChildSceneNode('goalCylinder2', self.exData.goal2Pos)
        node.attachObject(ent)

        #goal textures on wall. Horizontal or vertical will be visible based on trial.
        goalTextureSizeX = 200
        goalTextureSizeY = 200

        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture0', objName='GoalTexture1H', size=(goalTextureSizeX,goalTextureSizeY),
            meshName = 'GoalMesh1H', centerPoint=exData.goal1TexPos, normalVector=(0,0,-1), upVector=(0,1,0))
        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture90', objName='GoalTexture1V', size=(goalTextureSizeX,goalTextureSizeY),
            meshName = 'GoalMesh1V', centerPoint=exData.goal1TexPos, normalVector=(0,0,-1), upVector=(0,1,0))

        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture0', objName='GoalTexture2H', size=(goalTextureSizeX,goalTextureSizeY),
            meshName = 'GoalMesh2H', centerPoint=exData.goal2TexPos, normalVector=(0,0,-1), upVector=(0,1,0))
        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture90', objName='GoalTexture2V', size=(goalTextureSizeX,goalTextureSizeY),
            meshName = 'GoalMesh2V', centerPoint=exData.goal2TexPos, normalVector=(0,0,-1), upVector=(0,1,0))

        #fixation texture
        fixationTextureSizeX = 1
        fixationTextureSizeY = 1
        fixationPos = exData.fixationPos

        self.planeMaker.makePlane(textureName='Tupaia3D/Blue', objName='FixationTexture', meshName='fixationMesh',
            size=(fixationTextureSizeX,fixationTextureSizeY), centerPoint=fixationPos, normalVector=(0,0,-1), upVector=(0,1,0))

        #sample texture. Horizontal or vertical will be displayed based on trial.
        sampleTextureSizeX = 25
        sampleTextureSizeY = 25

        samplePos = exData.samplePos

        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture0', objName='SampleTextureH', meshName='sampleMeshH',
            size=(sampleTextureSizeX,sampleTextureSizeY), centerPoint=samplePos, normalVector=(0,0,-1), upVector=(0,1,0))
        self.planeMaker.makePlane(textureName='Tupaia3D/GoalTexture90', objName='SampleTextureV', meshName='sampleMeshV',
            size=(sampleTextureSizeX,sampleTextureSizeY), centerPoint=samplePos, normalVector=(0,0,-1), upVector=(0,1,0))

        #Make things invisible that should be invisible at trial start
        self.sceneManager.getEntity('SampleTextureH').setVisible(False)
        self.sceneManager.getEntity('SampleTextureV').setVisible(False)

        self.sceneManager.getEntity('GoalTexture2H').setVisible(False)
        self.sceneManager.getEntity('GoalTexture2V').setVisible(False)
        self.sceneManager.getEntity('GoalTexture1H').setVisible(False)
        self.sceneManager.getEntity('GoalTexture1V').setVisible(False)

        self.sceneManager.getEntity('goalCylinder1').setVisible(False)
        self.sceneManager.getEntity('goalCylinder2').setVisible(False)

    def _createCamera(self):
        self.camera =  self.sceneManager.createCamera ('PlayerCam')
        self.camera.nearClipDistance = 5
        self.camera.farClipDistance = 10000

    def _createViewports(self):
        viewport = self.renderWindow.addViewport(self.camera)
        viewport.backGroundColor = (0, 0, 0)
        self.camera.aspectRatio = float(viewport.actualWidth) / float (viewport.actualHeight)

    def _createFrameListener(self):
        self.frameListener = ShrewFrameListener(self.renderWindow, self.camera, self.sceneManager)
        self.root.addFrameListener(self.frameListener)
        self.frameListener.showDebugOverlay(False)

        #Start the experiment
        self.frameListener.startFixation()

if __name__ == '__main__':
    ta = Shrewenstein3D()
    ta.go()


from tequila import TequilaException
from tequila.hamiltonian import paulis
from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, ExpectationValue
from tequila.circuit.circuit import QCircuit
from tequila.simulators.simulator_api import compile_objective
from tequila.circuit.gradient import __grad_inner
from tequila.autograd_imports import jax
from tequila.circuit.compiler import compile_controlled_rotation,compile_h_power,compile_power_gate, \
    compile_trotterized_gate,compile_controlled_phase, compile_multitarget

import numpy
import copy

class QngMatrix:

    @property
    def dim(self):
        d=0
        for block in self.blocks:
            d+=len(block)
        return (d,d)

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

    def __call__(self, variables,samples=None):
        output= numpy.zeros(self.dim)
        d_v = 0
        for block in self.blocks:
            d_v_temp = 0
            for i, row in enumerate(block):
                for j, term in enumerate(row):
                    if i <= j:
                        try:
                            output[i + d_v][j + d_v] = term(variables=variables,samples=samples)
                        except:
                            output[i + d_v][j + d_v] = term
                    else:
                        output[i + d_v][j + d_v] = output[j + d_v][i + d_v]
                d_v_temp += 1
            d_v += d_v_temp

        back = numpy.linalg.pinv(output)
        return back

class CallableVector:
    @property
    def dim(self):
        return (len(self._vector))

    def __init__(self,vector):
        self._vector=vector

    def __call__(self, variables,samples=None):
        output = numpy.empty(self.dim)
        for i,entry in enumerate(self._vector):
            if hasattr(entry, '__call__'):
                output[i] = entry(variables,samples=samples)
            else:
                output[i] = entry
        return output

def get_generator(gate):
    if gate.name.lower() == 'rx':
        gen=paulis.X(gate.target[0])
    elif gate.name.lower() == 'ry':
        gen=paulis.Y(gate.target[0])
    elif gate.name.lower()  == 'rz':
        gen=paulis.Z(gate.target[0])
    elif gate.name.lower() == 'phase':
        gen=paulis.Qm(gate.target[0])
    else:
        print(gate.name.lower())
        raise TequilaException('cant get the generator of a non Gaussian gate, you fool!')
    return gen

def qng_metric_tensor_blocks(expectation,initial_values=None,samples=None,
                             backend=None,backend_options=None,noise=None):

    U=expectation.U
    moments=U.canonical_moments
    sub=[QCircuit.from_moments(moments[:i]) for i in range(1,len(moments),2)]
    parametric_moms=[moments[i] for i in range(1,len(moments)+1,2)]
    generators =[]
    for pm in parametric_moms:
        set=[]
        if len(pm.gates) !=0:
            for gate in pm.gates:
                gen=get_generator(gate)
                set.append(gen)
        if len(set) !=0:
            generators.append(set)
        else:
            generators.append(None)
    blocks=[]
    for i,set in enumerate(generators):
        if set is None:
            pass
        else:
            block=[[0 for _ in range(len(set))] for _ in range(len(set))]
            for k,gen1 in enumerate(set):
                for q,gen2 in enumerate(set):
                    if k == q:
                        arg= (ExpectationValue(U=sub[i], H=gen1 * gen1) - ExpectationValue(U=sub[i],H=gen1)**2)/4
                    else:
                        arg = (ExpectationValue(U=sub[i], H=gen1 * gen2) - ExpectationValue(U=sub[i], H=gen1)*ExpectationValue(U=sub[i],H=gen2) ) / 4
                    block[k][q] = compile_objective(arg, variables=initial_values, samples=samples, backend=backend,
                                                    noise=noise,backend_options=backend_options)
            blocks.append(block)
    return blocks

def qng_circuit_grad(E: ExpectationValueImpl):
    '''
    implements the analytic partial derivatives of a unitary as it would appear in an expectation value, taking
    all parameters as final (only useful for qng, invalid method otherwise!)
    :param E: the Excpectation whose gradient should be obtained
    :return: vector (as dict) of dU/dpi as Objectives.
    '''
    hamiltonian = E.H
    unitary = E.U

    # fast return if possible
    out=[]
    for i, g in enumerate(unitary.gates):
        if g.is_parametrized():
            if g.is_controlled():
                raise TequilaException("controlled gate in qng circuit gradient: Compiler was not called")
            if hasattr(g, "shift"):
                if hasattr(g._parameter,'extract_variables'):
                    shifter = qng_grad_gaussian(unitary, g, i, hamiltonian)
                    out.append(shifter)
            else:
                print(g, type(g))
                raise TequilaException('No shift found for gate {}'.format(g))
    if out is None:
        raise TequilaException("caught a dead circuit in qng gradient")
    return out

def qng_grad_gaussian(unitary, g, i, hamiltonian):
    '''
    qng function for getting the gradients of gaussian gates.
    THIS variant of the function does not seek out underlying gate parameters; it treats each variable 'as is'.
    This treatment is necessary for the QNG but is incorrect elsewhere.
    :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated
    :param g: a parametrized: the gate being differentiated
    :param i: Int: the position in unitary at which g appears
    :param variable: Variable or String: the variable with respect to which gate g is being differentiated
    :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary
        is contained within an ExpectationValue
    :return: a list of objectives; the gradient of the Exp. with respect to each of its (internal) parameters
    '''

    if not hasattr(g, "shift"):
        raise TequilaException("No shift found for gate {}".format(g))

    # neo_a and neo_b are the shifted versions of gate g needed to evaluate its gradient
    shift_a = g._parameter + numpy.pi / (4 * g.shift)
    shift_b = g._parameter - numpy.pi / (4 * g.shift)
    neo_a = copy.deepcopy(g)
    neo_a._parameter = shift_a
    neo_b = copy.deepcopy(g)
    neo_b._parameter = shift_b

    U1 = unitary.replace_gates(positions=[i], circuits=[neo_a])
    w1 = g.shift

    U2 = unitary.replace_gates(positions=[i], circuits=[neo_b])
    w2 = -g.shift

    Oplus = ExpectationValueImpl(U=U1, H=hamiltonian)
    Ominus = ExpectationValueImpl(U=U2, H=hamiltonian)
    dOinc = w1 * Objective(args=[Oplus]) + w2 * Objective(args=[Ominus])
    return dOinc

def subvector_procedure(eval,initial_values=None,samples=None,
                        backend=None,backend_options=None,noise=None,):
    vect=qng_circuit_grad(eval)
    out=[]
    for entry in vect:
        out.append(compile_objective(entry, variables=initial_values, samples=samples,
                                     backend=backend,backend_options=backend_options,
                                     noise=noise))
    return CallableVector(out)

def get_self_pars(U):
    out=[]
    for g in U.gates:
        if g.is_parametrized():
            if hasattr(g._parameter,'extract_variables'):
                out.append(g._parameter)
    return out

def qng_dict(argument,matrix,subvector,mapping,positional):
    return {'arg':argument,'matrix':matrix,'vector':subvector,'mapping':mapping,'positional':positional}

def get_qng_combos(objective,initial_values=None,samples=None,backend=None,
                   backend_options=None,noise=None):
    combos=[]
    vars=objective.extract_variables()
    compiled = compile_multitarget(gate=objective)
    compiled = compile_trotterized_gate(gate=compiled)
    compiled = compile_h_power(gate=compiled)
    compiled = compile_power_gate(gate=compiled)
    compiled = compile_controlled_phase(gate=compiled)
    compiled = compile_controlled_rotation(gate=compiled)
    for i,arg in enumerate(compiled.args):
        if not isinstance(arg,ExpectationValueImpl):
            ### this is a variable, no QNG involved
            mat=QngMatrix([[[1]]])
            vec=CallableVector([__grad_inner(arg, arg)])
            mapping={0:{v:__grad_inner(arg,v) for v in vars}}
        else:
            ### if the arg is an expectationvalue, we need to build some qngs and mappings!
            blocks=qng_metric_tensor_blocks(arg,initial_values=initial_values,samples=samples,
                                            backend=backend,noise=noise,backend_options=backend_options)
            mat=QngMatrix(blocks)

            vec=subvector_procedure(arg,initial_values=initial_values,samples=samples,
                                    backend=backend,noise=noise,backend_options=backend_options)

            mapping={}
            self_pars=get_self_pars(arg.U)
            for j,p in enumerate(self_pars):
                indict={}
                for v in p.extract_variables():
                    gi=__grad_inner(p,v)
                    if isinstance(gi,Objective):
                        g=compile_objective(gi, variables=initial_values, samples=samples,
                                            backend=backend, noise=noise,backend_options=backend_options)
                    else:
                        g=gi
                    indict[v]=g
                mapping[j]=indict

        posarg = jax.grad(compiled.transformation, argnums=i)
        p = Objective(compiled.args, transformation=posarg)

        pos = compile_objective(p, variables=initial_values, samples=samples,
                                backend=backend, noise=noise,backend_options=backend_options)
        combos.append(qng_dict(arg, mat, vec, mapping, pos))
    return combos

def evaluate_qng(combos,variables,samples=None):
    gd={v:0 for v in variables.keys()}
    for c in combos:
        qgt=c['matrix']
        vec=c['vector']
        m=c['mapping']
        pos=c['positional']
        marco=qgt(variables,samples=samples)
        polo=vec(variables,samples=samples)
        ev=numpy.dot(marco,polo)
        for i,val in enumerate(ev):
            maps=m[i]
            for k in maps.keys():
                gd[k] += val*maps[k]*pos(variables=variables,samples=samples)

    out=[v for v in gd.values()]
    return out

class QNGVector():

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

    def __call__(self, variables,samples=None):
        return numpy.asarray(evaluate_qng(self.combos,variables=variables,samples=samples))


# coding=utf-8
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse
from django.views.generic.edit import UpdateView

from modules.contract_manage.intern.intern_forms import ContractInternForm
from modules.contract_manage.models import *
from modules.share_module.formater import *
from modules.share_module.permissionMixin import class_view_decorator

@class_view_decorator(login_required)
@class_view_decorator(permission_required('contract_manage.change_contractintern', raise_exception=True))
class ContractInternUpdate(SuccessMessageMixin, UpdateView):
	model = ContractIntern
	form_class = ContractInternForm
	template_name = "contract_edit.html"
	success_message = u"%(name)s 成功修改"

	def get_context_data(self, **kwargs):
		context = super(ContractInternUpdate, self).get_context_data(**kwargs)
		context["form_content"] = u"合同签订-实习生"
		referrer = self.request.META.get('HTTP_REFERER', "")
		context["referrer"] = referrer
		return context

	def get_success_url(self):
		self.url = reverse('contract:list_intern', args=())
		referrer = self.request.POST.get("referrer", "")
		if referrer:
			self.url = referrer
		_addanother = self.request.POST.get("_addanother", "")
		if _addanother:
			self.url = reverse('contract:add_intern')
		return self.url

	def form_valid(self, form):
		receive_address = self.request.POST.get("receive_address", "")  # 指定通知接收地址
		address = self.request.POST.get("address", "")  # 住址
		deadline = self.request.POST.get("deadline", "")  # 合同期限
		start_date = self.request.POST.get("start_date", "")  # 合同开始时间
		end_date = self.request.POST.get("end_date", "")  # 合同结束时间

		# 计算-指定通知接收地址
		if not receive_address:
			if address:
				form.instance.receive_address = address

		# 计算-试用期
		form.instance.probation = deadline

		# 计算-合同结束时间
		if not end_date:
			if deadline and start_date:
				start_date_datetime = datetime.datetime.strptime(start_date, "%Y/%m/%d")

				if deadline == "1":  # 24个月
					end_date = add_months(start_date_datetime, 24)
				if deadline == "2":  # 36个月
					end_date = add_months(start_date_datetime, 36)
				form.instance.end_date = end_date
		return super(ContractInternUpdate, self).form_valid(form)


#!/usr/bin/env python3

# --- Modules --- #
import drawBot as dB
from pathlib import Path
from collections import defaultdict

# --- Constants --- #
DICT_FOLDER = Path('dictionaries')
PRECISION = 2

# --- Objects & Methods --- #
def calcWordsWidth(words, fontName):
    dB.font(fontName, 1)
    width_2_words = defaultdict(set)
    for eachWord in words:
        txtWdt, txtHgt = dB.textSize(eachWord)
        width_2_words[round(txtWdt, PRECISION)].add(eachWord)
    return width_2_words

# --- Variables --- #
fontName = 'Skia'
language = 'italian'

# --- Instructions --- #
if __name__ == '__main__':
    from loadWords_v4 import loadWords
    words = loadWords(DICT_FOLDER / f'{language}.txt')
    width_2_words = calcWordsWidth(words, fontName)
    print(f'words: {len(words)}')
    # words: 16458
    print(f'groups: {len(width_2_words)}')
    # groups: 573
    print(f'words/groups ratio: {len(words)/len(width_2_words):.3f}')
    # words/groups ratio: 28.723


"""
F Faça um algoritmo em que o usuário informe uma medida em metros. Em seguida, converta
 essa medida para centímetros e envie para a saída padrão:
"""
num1 = float(input("Informe a metragem: "))

centimetro = num1*100
metro = "metros"

print("%.2f %s = %.2f centimentros" %(num1, metro, centimetro))

aulas/01 - Conceitos deprogramacao python/atividades 01/questão 09.py


import asyncio
import time

import pytest
import dask
from dask_gateway.auth import get_auth, BasicAuth, KerberosAuth, JupyterHubAuth
from dask_gateway.client import Gateway, GatewayCluster, cleanup_lingering_clusters
from dask_gateway_server.compat import get_running_loop
from dask_gateway_server.managers.inprocess import InProcessClusterManager
from dask_gateway_server.utils import random_port
from tornado import web
from tornado.httpclient import HTTPRequest

from .utils import temp_gateway

def test_get_auth():
    # Pass through existing auth objects
    auth = BasicAuth()
    assert get_auth(auth) is auth

    # Auth by keyword name
    auth = get_auth("basic")
    assert isinstance(auth, BasicAuth)

    auth = get_auth("kerberos")
    assert isinstance(auth, KerberosAuth)

    # Auth from config
    config = {"gateway": {"auth": {"type": "basic", "kwargs": {}}}}
    with dask.config.set(config):
        auth = get_auth()
        assert isinstance(auth, BasicAuth)

    # Auth from config with import path
    config = {
        "gateway": {"auth": {"type": "dask_gateway.auth.BasicAuth", "kwargs": {}}}
    }
    with dask.config.set(config):
        auth = get_auth()
        assert isinstance(auth, BasicAuth)

    # Auth from config with kwargs
    config = {"gateway": {"auth": {"type": "basic", "kwargs": {"username": "bruce"}}}}
    with dask.config.set(config):
        auth = get_auth()
        assert isinstance(auth, BasicAuth)
        assert auth.username == "bruce"

    # Errors
    with pytest.raises(TypeError):
        get_auth(1)

    with pytest.raises(TypeError):
        get_auth(lambda: 1)

    with pytest.raises(ImportError):
        get_auth("dask_gateway.auth.Foo")

    with pytest.raises(ImportError):
        get_auth("not_a_real_module_name_foo_barrr")

def test_config_auth_kwargs_template_environment_vars(monkeypatch):
    monkeypatch.setenv("TEST_USER", "bruce")
    config = {
        "gateway": {"auth": {"type": "basic", "kwargs": {"username": "{TEST_USER}"}}}
    }
    with dask.config.set(config):
        auth = get_auth()
        assert isinstance(auth, BasicAuth)
        assert auth.username == "bruce"

def test_jupyterhub_auth(monkeypatch):
    with pytest.raises(ValueError) as exc:
        get_auth("jupyterhub")
    assert "JUPYTERHUB_API_TOKEN" in str(exc.value)

    monkeypatch.setenv("JUPYTERHUB_API_TOKEN", "abcde")
    auth = get_auth("jupyterhub")
    assert auth.api_token == "abcde"
    assert isinstance(auth, JupyterHubAuth)

    # Parameters override environment variable
    assert JupyterHubAuth(api_token="other").api_token == "other"

def test_client_init():
    config = {
        "gateway": {
            "address": "http://127.0.0.1:8888",
            "public-address": None,
            "proxy-address": 8786,
            "auth": {"type": "basic", "kwargs": {"username": "bruce"}},
        }
    }

    with dask.config.set(config):
        # Defaults
        gateway = Gateway()
        assert gateway.address == "http://127.0.0.1:8888"
        assert gateway._public_address == "http://127.0.0.1:8888"
        assert gateway.proxy_address == "gateway://127.0.0.1:8786"
        assert gateway.auth.username == "bruce"

        # Address override
        gateway = Gateway(address="http://127.0.0.1:9999")
        assert gateway.address == "http://127.0.0.1:9999"

        # Proxy address override
        gateway = Gateway(proxy_address="gateway://123.4.5.6:9999")
        assert gateway.proxy_address == "gateway://123.4.5.6:9999"

        # Auth override
        gateway = Gateway(auth="kerberos")
        assert isinstance(gateway.auth, KerberosAuth)

    config = {
        "gateway": {
            "address": None,
            "public-address": None,
            "proxy-address": 8786,
            "auth": {"type": "basic", "kwargs": {}},
        }
    }

    with dask.config.set(config):
        # No address provided
        with pytest.raises(ValueError):
            Gateway()

    config["gateway"]["address"] = "http://127.0.0.1:8888"
    config["gateway"]["proxy-address"] = None

    with dask.config.set(config):
        # No proxy-address provided
        with pytest.raises(ValueError):
            Gateway()

def test_gateway_addresses_template_environment_vars(monkeypatch):
    monkeypatch.setenv("TEST", "foobar")

    with dask.config.set(
        gateway__address="http://{TEST}:80",
        gateway__proxy_address=8785,
        gateway__public_address="/{TEST}/foo/",
    ):
        g = Gateway()
    assert g.address == "http://foobar:80"
    assert g.proxy_address == "gateway://foobar:8785"
    assert g._public_address == "/foobar/foo"

    with dask.config.set(gateway__proxy_address="gateway://{TEST}:8787"):
        g = Gateway("http://test.com")
    assert g.address == "http://test.com"
    assert g.proxy_address == "gateway://foobar:8787"

class SlowHandler(web.RequestHandler):
    async def get(self):
        self.waiter = asyncio.ensure_future(asyncio.sleep(30))
        self.settings["task_set"].add(self.waiter)
        try:
            await self.waiter
        except asyncio.CancelledError:
            return
        self.write("Hello world")

    def on_connection_close(self):
        if hasattr(self, "waiter"):
            self.waiter.cancel()

class slow_server(object):
    def __init__(self):
        self.port = random_port()
        self.address = "http://127.0.0.1:%d" % self.port
        self.tasks = set()
        self.app = web.Application([(r"/", SlowHandler)], task_set=self.tasks)

    async def __aenter__(self):
        self.server = self.app.listen(self.port)
        return self

    async def __aexit__(self, *args):
        self.server.stop()
        await asyncio.gather(*self.tasks, return_exceptions=True)

@pytest.mark.asyncio
async def test_client_fetch_timeout():
    async with slow_server() as server:
        gateway = Gateway(server.address, auth=BasicAuth("alice"))
        with pytest.raises(TimeoutError):
            await gateway._fetch(HTTPRequest(url=server.address, request_timeout=1))

@pytest.mark.asyncio
async def test_client_reprs(tmpdir):
    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:
        async with Gateway(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
            asynchronous=True,
        ) as gateway:
            cluster = await gateway.new_cluster()

            # Plain repr
            assert cluster.name in repr(cluster)

            # HTML repr with dashboard
            cluster.dashboard_link = "%s/gateway/clusters/%s/status" % (
                gateway_proc.public_url,
                cluster.name,
            )
            assert cluster.name in cluster._repr_html_()
            assert cluster.dashboard_link in cluster._repr_html_()

            # HTML repr with no dashboard
            cluster.dashboard_link = None
            assert "Not Available" in cluster._repr_html_()

@pytest.mark.asyncio
async def test_cluster_widget(tmpdir):
    pytest.importorskip("ipywidgets")

    def test():
        with GatewayCluster(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
        ) as cluster:
            # Smoke test widget
            cluster._widget()

            template = "
Workers	 %d
"
            assert (template % 0) in cluster._widget_status()

            cluster.scale(1)
            timeout = time.time() + 30
            while time.time() < timeout:
                if cluster.scheduler_info.get("workers"):
                    break
                time.sleep(0.25)
            else:
                assert False, "didn't scale up in time"

            assert (template % 1) in cluster._widget_status()

    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:
        loop = get_running_loop()
        await loop.run_in_executor(None, test)

@pytest.mark.asyncio
async def test_dashboard_link_from_public_address(tmpdir):
    pytest.importorskip("bokeh")

    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:
        with dask.config.set(
            gateway__address=gateway_proc.public_urls.connect_url,
            gateway__public_address="/services/dask-gateway/",
            gateway__proxy_address=gateway_proc.gateway_urls.connect_url,
        ):
            async with Gateway(asynchronous=True) as gateway:
                assert gateway._public_address == "/services/dask-gateway"

                cluster = await gateway.new_cluster()

                sol = "/services/dask-gateway/gateway/clusters/%s/status" % cluster.name
                assert cluster.dashboard_link == sol

                clusters = await gateway.list_clusters()
                for c in clusters:
                    assert c.dashboard_link.startswith("/services/dask-gateway")

@pytest.mark.asyncio
async def test_create_cluster_with_GatewayCluster_constructor(tmpdir):
    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:
        async with GatewayCluster(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
            asynchronous=True,
        ) as cluster:

            # Cluster is now present in list
            clusters = await cluster.gateway.list_clusters()
            assert len(clusters)
            assert clusters[0].name == cluster.name

            await cluster.scale(1)

            with cluster.get_client(set_as_default=False) as client:
                res = await client.submit(lambda x: x + 1, 1)
                assert res == 2

        assert cluster.status == "closed"

        async with Gateway(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
            asynchronous=True,
        ) as gateway:
            # No cluster running
            clusters = await gateway.list_clusters()
            assert not clusters

@pytest.mark.asyncio
async def test_GatewayCluster_shutdown_on_close(tmpdir):
    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:

        def test():
            cluster = GatewayCluster(
                address=gateway_proc.public_urls.connect_url,
                proxy_address=gateway_proc.gateway_urls.connect_url,
            )
            assert cluster.shutdown_on_close
            assert cluster in GatewayCluster._instances

        loop = get_running_loop()
        await loop.run_in_executor(None, test)

        assert len(GatewayCluster._instances) == 0

        async with Gateway(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
            asynchronous=True,
        ) as gateway:
            # No cluster running
            clusters = await gateway.list_clusters()
            assert not clusters

@pytest.mark.asyncio
async def test_GatewayCluster_cleanup_atexit(tmpdir):
    async with temp_gateway(
        cluster_manager_class=InProcessClusterManager, temp_dir=str(tmpdir)
    ) as gateway_proc:

        def test():
            return GatewayCluster(
                address=gateway_proc.public_urls.connect_url,
                proxy_address=gateway_proc.gateway_urls.connect_url,
            )

        loop = get_running_loop()
        cluster = await loop.run_in_executor(None, test)

        assert len(GatewayCluster._instances) == 1

        def test_cleanup():
            # No warnings raised by cleanup function
            with pytest.warns(None) as rec:
                cleanup_lingering_clusters()
            for r in rec:
                assert not issubclass(r.category, UserWarning)

            # Cluster is now closed
            assert cluster.status == "closed"

            # No harm in double running
            with pytest.warns(None) as rec:
                cleanup_lingering_clusters()
            for r in rec:
                assert not issubclass(r.category, UserWarning)

        await loop.run_in_executor(None, test_cleanup)

        async with Gateway(
            address=gateway_proc.public_urls.connect_url,
            proxy_address=gateway_proc.gateway_urls.connect_url,
            asynchronous=True,
        ) as gateway:
            # No cluster running
            clusters = await gateway.list_clusters()
            assert not clusters


def smaller(a, b):
	print("Definindo o menor número entre %s e %s" % (a, b))
	if a < b:
		print("O número %s é o menor" % (a))
	elif a > b:
		print("O número %s é o menor" % (b))
	else:
		print("Os números são iguais")

smaller(1, 5)
smaller(4, 2)
smaller(5, 5)


# -*- coding:utf-8 -*-

import re
import time
import traceback
import requests
from requests import Response,Request
from requests.exceptions import (InvalidSchema, InvalidURL, MissingSchema,
                                 RequestException)

absolute_http_url_regexp = re.compile(r"^https?://", re.I)

class ApiResponse(Response):

    def raise_for_status(self):
        if hasattr(self, "error") and self.error:
            raise self.error
        Response.raise_for_status(self)

class HttpSession(requests.Session):

    def __init__(self):
        super(HttpSession, self).__init__()
        self.request_meta = dict()

    def _build_url(self,path):
        if absolute_http_url_regexp.match(path):
            return path
        else:
            return "%s%s" % (self.base_url, path)

    def request(self, url, method, **kwargs):
        """
        Constructs and sends a :py:class:`requests.Request`.
        Returns :py:class:`requests.Response` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
        :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long in seconds to wait for the server to send data before giving up, as a float,
            or a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response content. Defaults to ``False``.
        :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
        :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
        """

        # set up pre_request hook for attaching meta data to the request object
        self.request_meta["method"] = method
        self.request_meta["start_time"] = time.time()

        response = self._send_request_safe_mode(method, url, **kwargs)

        # record the consumed time
        self.request_meta["end_time"] = time.time()

        # get the length of the content, but if the argument stream is set to True, we take
        # the size from the content-length header, in order to not trigger fetching of the body
        if kwargs.get("stream", False):
            self.request_meta["content_size"] = int(response.headers.get("content-length") or 0)
        else:
            self.request_meta["content_size"] = len(response.content or b"")

        self.request_meta["content_type"] = response.headers.get("Content-Type")
        self.request_meta["status_code"] = response.status_code
        try:
            response.raise_for_status()
            self.request_meta["status"] = "success"
        except RequestException as e:
            self.request_meta["status"] = "error"
            self.request_meta["message"] = traceback.format_exc()

        return response

    def _send_request_safe_mode(self, method, url, **kwargs):
        """
        Send an HTTP request, and catch any exception that might occur due to connection problems.

        Safe mode has been removed from requests 1.x.
        """
        try:
            return requests.Session.request(self, method, url, **kwargs)
        except (MissingSchema, InvalidSchema, InvalidURL):
            raise
        except RequestException as e:
            r = ApiResponse()
            r.status_code = 0
            r.error = e
            r.request = Request(method, url).prepare()
            return r


# Checks input is a number more than a given value
def num_check(question, low):
    valid = False
    while not valid:

        error = "Please enter an integer that is more than zero" "or (equal to) {}" .format(low)

        try:

            # Ask user to enter a number
            response = int(input(question))

            # Checks number is more than zero
            if response >= low:
                return response

            # Outputs error if input is invalid
            else:
                print(error)
                print()

        except ValueError:
            print(error)
            print()

# Finds # of bits for 24 bit colour
def image_bits():

    # Get width and height ...
    image_width = num_check("Image width? ", 1)
    image_height = num_check("Image height? ", 1)

    # Calculate the number of pixels
    num_pixels = image_width * image_height

    # Calculate # of bits (num pixels x 24)
    num_bits = num_pixels * 24

    # Outputs answer with working
    print()
    print("# of pixels = {} x {} = {}".format(image_height, image_width, num_pixels))
    print("# of bits is {} x 24 = {}".format(num_pixels, num_bits))
    print()

    return ""

# Main routine goes here
image_bits()


'''
Created on 06.12.2019

@author: Zoli
'''
import argparse
import datetime
from solaredge import datareadout, solaredge
from battery import batteryestimator, battery
from report import excelreporter
from energycost import energycost, energycostcalculator

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--site_token', type=str, help='Site token of the solaredge inverter')
    parser.add_argument('-i', '--site_id', type=int, help='Site ID of the solaredge inverter')
    parser.add_argument('-s', '--start_date', type=str, help='Start date of energy readout in YYYY-MM-DD format')
    parser.add_argument('-e', '--end_date', type=str, help='End date of energy readout in YYYY-MM-DD format')
    parser.add_argument('-o', '--report_file', type=str, default='energy.xlsx', help='Output Excel report file')
    parser.add_argument('-a', '--acc_report_file', type=str, default='energy_accumulated.xlsx', help='Output Excel report file with accumulated energy')
    args = parser.parse_args()

    inverter = solaredge.Solaredge(args.site_token)
    readout = datareadout.DataReadout(inverter, args.site_id)
    energy = readout.getDetailedEnergy(args.start_date, args.end_date)

    # 2019
    ENERGY_COST_HIGH = 0.2526
    ENERGY_COST_LOW = 0.1901
    highWeekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    highTarifHours = (datetime.time(hour=7, minute=0), datetime.time(hour=18, minute=59, second=59))
    validFrom = datetime.datetime(year=2019, month=1, day=1)
    validTo = datetime.datetime(year=2019, month=12, day=31, hour=23, minute=59, second=59)
    cost = energycost.EnergyCost()
    cost.setDualTariffEnergyCost(ENERGY_COST_HIGH, highWeekdays, highTarifHours[0], highTarifHours[1], ENERGY_COST_LOW, validFrom, validTo)
    REFUND = 0.093
    cost.setConstantEnergyRefundPerKWh(refund=REFUND, validFrom=validFrom, validTo=validTo)

    # 2020
    ENERGY_COST_HIGH = 0.2570
    ENERGY_COST_LOW = 0.1946
    validFrom = datetime.datetime(year=2020, month=1, day=1)
    validTo = datetime.datetime(year=2020, month=12, day=31, hour=23, minute=59, second=59)
    cost.setDualTariffEnergyCost(ENERGY_COST_HIGH, highWeekdays, highTarifHours[0], highTarifHours[1], ENERGY_COST_LOW, validFrom, validTo)
    REFUND = 0.1060
    cost.setConstantEnergyRefundPerKWh(refund=REFUND, validFrom=validFrom, validTo=validTo)

    # 2021
    ENERGY_COST_HIGH = 0.2247
    ENERGY_COST_LOW = 0.1921
    validFrom = datetime.datetime(year=2021, month=1, day=1)
    validTo = datetime.datetime(year=2021, month=12, day=31, hour=23, minute=59, second=59)
    cost.setDualTariffEnergyCost(ENERGY_COST_HIGH, highWeekdays, highTarifHours[0], highTarifHours[1], ENERGY_COST_LOW, validFrom, validTo)
    REFUND = 0.0896
    cost.setConstantEnergyRefundPerKWh(refund=REFUND, validFrom=validFrom, validTo=validTo)

    costCalculator = energycostcalculator.EnergyCostCalculator(cost)

    reporter = excelreporter.ExcelReporter(args.report_file)
    reporter.writeEnergyData(energy, readout.energyTypes(), costCalculator)

    realBattery = battery.Battery(capacity=9300, chargingLossPercent=1, dischargingLossPercent=1, maxChargingPower=5000, maxDischargingPower=7000)
    batteryEstimator = batteryestimator.BatteryEstimator(realBattery)
    accumulatedEnergy = batteryEstimator.accumulateFeedInEnergy(energy, datareadout.DataReadout.energyTypes())

    reporter = excelreporter.ExcelReporter(args.acc_report_file)
    reporter.writeEnergyData(accumulatedEnergy, readout.energyTypes(), costCalculator)


import csv
from csv import DictReader
from pprint import pprint
from imdbpie import ImdbFacade

def analizeFile(outfile):
	dic = {}

	with open('NetflixViewingHistory.csv', newline='') as csvfile:
		reader = DictReader(csvfile)
		for row in reader:
			#Es una serie?
			if row['Title'].count(":") == 2:
				title = row['Title'].split(':')[0]
				date = row['Date']
				if title in dic.keys():
					#Ya me habia aparecido en la lista?
					dic[title][1] += 1
					#dic[title][2].append(date)
				else:
					#Agregala a la lista
					dic[title] = [[], 1]#,[date]]

	imdb = ImdbFacade()

	for tvseries in list(dic.keys()):
		#Por cada serie, me fijo en IMDB cuantas series hay con nombre parecido
		titles = imdb.search_for_title(tvseries)
		#titles es una lista con la cantidad de matches
		if (len(titles)) > 0:
			#Si la lista tiene mas de 0 registros entonces existen registros de esa serie
			for i in range(len(titles)):
				if tvseries.lower() == titles[i].title.lower():
					#Si alguno de los resultados se llama igual que la que esta en mi archivo de netflix
					#Lo guardo en la variable title
					title = imdb.get_title(imdb_id=titles[0].imdb_id)
					#title contiene ahora toda la informacion sobre esta serie
				else:
					if i == len(titles):
						#Si ninguno se llama igual (capaz esta en otro idioma)
						print(tvseries + ' not found. Choose:')
						#Muestro todas las opciones
						pprint([show.title for show in titles])
						#Y pregunto por consola a ver cual es
						index = input('Number:')
						if index == '*':
							#Si tipeo el caracter '*' el titulo el codigo entiende que el titulo no se encontro y pasamos al siguiente
							break
						#Si figura el titulo, lo guardamos en la variable title
						title = imdb.get_title(imdb_id=titles[int(index)].imdb_id)
				break
			#Agregamos a nuestra lista las caracteristicas del titulo que nos interesen
			#imdb_id, title, year, rating, type, release_date, releases, plot_outline, rating_count, writers, directors, creators, genres, credits, certification, image, stars
			dic[tvseries][0] = [title.certification, title.genres, title.year]
			print(tvseries)
			pprint(dic[tvseries])

	rows = [[key, dic[key][1], dic[key][0][0], dic[key][0][2]]+list(dic[key][0][1]) for key in dic.keys() if len(dic[key][0]) > 1]
	max_genres = max(map(len, rows))
	first_row = ['Title', 'Ammount', 'Certification', 'Year']+ ['Genre_' + str(i+1) for i in range(max_genres-4)]
	rows.insert(0, first_row)

	import csv

	with open(outfile+".csv", "w", newline="") as f:
	    writer = csv.writer(f)
	    writer.writerows(rows)


from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
	article_title = models.CharField(max_length=200)
	article_text  = models.TextField()
	article_date  = models.DateTimeField()
	article_likes = models.IntegerField(default=0)
	article_author = models.ForeignKey(User)

	def __str__(self):
		return self.article_title

	class Meta():
		db_table = 'article'
		ordering = ["article_date"]

class Comments(models.Model):
	comments_text 	 = models.TextField(verbose_name='')
	comments_article = models.ForeignKey(Article)
	comments_author = models.ForeignKey(User)

	class Meta():
		db_table = 'comments'


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('comite', '0002_resguardo_activo'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='producto',
            options={'ordering': ['clave']},
        ),
        migrations.AlterModelOptions(
            name='resguardo',
            options={'ordering': ['recibe']},
        ),
        migrations.RemoveField(
            model_name='producto',
            name='estado',
        ),
        migrations.AddField(
            model_name='producto',
            name='usado',
            field=models.IntegerField(default=0, verbose_name=b'Usado', blank=True),
            preserve_default=False,
        ),
    ]


# @team 35
# @author Jiacheng Ye   904973      Shanghai, China
# @author Shiyi Xu      780801      Melbourne, Australia
# @author Yuyao Ma      1111182     Yinchuan, China
# @author Yujing Guan   1011792     Fuzhou, China
# @author Zexin Yu      10328021    Dalian, China
# Search Twitters in 6 States:
# TAS, WA

# Use tweept library, link: https://github.com/tweepy/tweepy
# APIs reference: https://docs.tweepy.org/en/latest/api.html#api-reference
# https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets

import tweepy, couchdb, json, sys, itertools

from os.path import dirname, abspath
parent_dir = dirname(dirname(abspath(__file__)))
sys.path.append(parent_dir)
grandparent_dir = dirname(dirname(dirname(abspath(__file__))))
sys.path.append(grandparent_dir)
grandgrandparent_dir = dirname(dirname(dirname(dirname(abspath(__file__)))))
sys.path.append(grandgrandparent_dir)

from twitter_api_config import twitter_api
from couchdb_config import Config

# Define the geo restriction for states
state_geo = {'TAS': '-41.454521,145.970673,150km', 'WA': '-27.672817,121.628311,900km'}

# Search all twitters with keyword in a certain State
def count_keyword_in_different_states(keyword, state, api, db):

    count = 0
    # Define max_id in order to achieve getting non-repetitive data
    max_id = 0
    prev_id = 0

    # Because of twitter API limits the maximum number of returns to 100 at a time,
    # so use max_id field restricts the content returned to be different each time.
    for i in itertools.count():
        # For the first time, there is no max_id field, so call api.search() without max_id
        if (i == 0):
            search_results = api.search(q = keyword, geocode = state_geo[state], count = 100)
        # After the first time, through max_id to return non duplicate query results
        else:
            search_results = api.search(q = keyword, geocode = state_geo[state], max_id = max_id, count = 100)

        # If the query result is empty, the loop ends
        if (len(search_results) == 0):
            return count

        # Update max_id --- max_id is '_id' filed of the last query result
        max_id = search_results[-1]._json['id'] - 1

        # process Tweet content
        for tweet in search_results:
            # If the id of this result is the same as that of the previous one,
            # it can be proved that all tweets have been found, then just return
            if (tweet._json['id'] == prev_id):
                print(state, count)
                return count

            # tweet is an object, and the relevant information of Twitter is in tweet._json
            # To detect whether a message contains a 'text' key.
            # Not all objects returned by twitter are messages. The difference is whether a message object contains a 'text' key
            if 'text' in tweet._json:
                count += 1
                # Conduct the dictionary for result
                dict_search = {'id': tweet._json['id_str'], 'created': tweet._json['created_at'], 'text': tweet._json['text'], 'state': state}
                # Save the result dictionary to CouchDB
                db.save(dict_search)
                # Update prev_id
                prev_id = tweet._json['id']

    return count

def main():
    # Get Twitter API handle
    api = twitter_api()

    # The keyword we would like to search
    search_keyword = ''

    # Define the name of CouchDB Database
    COUCHDB_DATABASE = "twitter_raw_data"
    # Get the server handle
    server = couchdb.Server(Config.COUCHDB_SERVER)
    # If the Database is not existent, create it
    if (not server.__contains__(COUCHDB_DATABASE)):
        db = server.create(COUCHDB_DATABASE)
    # Get the Database handle
    db = server[COUCHDB_DATABASE]

    count = 0

    for state in state_geo:
        count += count_keyword_in_different_states(search_keyword, state, api, db)

    print ('Total Count:', count)

if __name__ == '__main__':
    main()