# Copyright 2009-2013 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
#   Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
#
#   Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import argparse
import base64
import datetime
import hashlib
import os.path
from requestbuilder import Arg
from requestbuilder.auth import BaseAuth
from requestbuilder.exceptions import ArgumentError
import subprocess
import urlparse
import urllib

class EucaRsaV2Auth(BaseAuth):
    """Provides authentication for inter-component requests"""

    ARGS = [Arg('--cert', metavar='FILE', help='''file containing the X.509
                certificate to use when signing requests'''),
            Arg('--privatekey', metavar='FILE',
                help='file containing the private key to sign requests with'),
            Arg('--spoof-key-id', metavar='KEY_ID',
                help='run this command as if signed by a specific access key'),
            Arg('--euca-auth', action='store_true', help=argparse.SUPPRESS)]

    # noinspection PyExceptionInherit
    def configure(self):
        BaseAuth.configure(self)
        if not self.args.get('spoof_key_id'):
            self.args['spoof_key_id'] = os.getenv('EC2_ACCESS_KEY')

        cert = self.args.get('cert') or os.getenv('EUCA_CERT')
        privkey = self.args.get('privatekey') or os.getenv('EUCA_PRIVATE_KEY')
        if not cert:
            raise ArgumentError('argument --cert or environment variable '
                                'EUCA_CERT is required')
        if not privkey:
            raise ArgumentError('argument --privatekey or environment '
                                'variable EUCA_PRIVATE_KEY is required')
        cert = os.path.expanduser(os.path.expandvars(cert))
        privkey = os.path.expanduser(os.path.expandvars(privkey))
        if not os.path.exists(cert):
            raise ArgumentError("certificate file '{0}' does not exist"
                                .format(cert))
        if not os.path.isfile(cert):
            raise ArgumentError("certificate file '{0}' is not a file"
                                .format(cert))
        if not os.path.exists(privkey):
            raise ArgumentError("private key file '{0}' does not exist"
                                .format(privkey))
        if not os.path.isfile(privkey):
            raise ArgumentError("private key file '{0}' is not a file"
                                .format(privkey))
        self.args['cert'] = cert
        self.args['privatekey'] = privkey

    def __call__(self, request):
        if request.headers is None:
            request.headers = {}
        now = datetime.datetime.utcnow()
        request.headers['Date'] = now.strftime('%Y%m%dT%H%M%SZ')
        if 'Authorization' in request.headers:
            del request.headers['Authorization']
        if self.args.get('spoof_key_id'):
            request.headers['AWSAccessKeyId'] = self.args['spoof_key_id']
        elif 'AWSAccessKeyId' in request.headers:
            del request.headers['AWSAccessKeyId']

        cert_fp = self._get_fingerprint()
        self.log.debug('certificate fingerprint: %s', cert_fp)

        headers_to_sign = self._get_headers_to_sign(request)
        signed_headers = self._get_signed_headers(headers_to_sign)
        self.log.debug('SignedHeaders:%s', signed_headers)

        canonical_request = self._get_canonical_request(request)
        self.log.debug('CanonicalRequest:\n%s', canonical_request)
        signature = self._sign(canonical_request)
        self.log.debug('Signature:%s', signature)

        auth_header = ' '.join(('EUCA2-RSA-SHA256', cert_fp, signed_headers,
                                signature))
        request.headers['Authorization'] = auth_header

    def _get_fingerprint(self):
        cmd = ['openssl', 'x509', '-noout', '-in', self.args['cert'],
               '-fingerprint', '-md5']
        openssl = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        (stdout, __) = openssl.communicate()
        if openssl.returncode != 0:
            raise subprocess.CalledProcessError(openssl.returncode, cmd)
        return stdout.strip().rsplit('=', 1)[-1].replace(':', '').lower()

    def _sign(self, canonical_request):
        digest = hashlib.sha256(canonical_request).digest()
        cmd = ['openssl', 'pkeyutl', '-sign', '-inkey',
               self.args['privatekey'], '-pkeyopt', 'digest:sha256']
        openssl = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE)
        (stdout, __) = openssl.communicate(digest)
        if openssl.returncode != 0:
            raise subprocess.CalledProcessError(openssl.returncode, cmd)
        return base64.b64encode(stdout)

    def _get_canonical_request(self, request):
        # 1.  request method
        method = request.method.upper()
        # 2.  CanonicalURI
        c_uri = self._get_canonical_uri(request)
        # 3.  CanonicalQueryString
        c_querystr = self._get_canonical_querystr(request)
        # 4.  CanonicalHeaders
        headers_to_sign = self._get_headers_to_sign(request)
        c_headers = self._get_canonical_headers(headers_to_sign)
        # 5.  SignedHeaders
        s_headers = self._get_signed_headers(headers_to_sign)

        return '\n'.join((method, c_uri, c_querystr, c_headers, s_headers))

    def _get_canonical_uri(self, request):
        return urlparse.urlparse(request.url).path or '/'

    def _get_canonical_querystr(self, request):
        params = []
        for key, val in request.params.iteritems():
            params.append('='.join((urllib.quote(key, safe='/~'),
                                    urllib.quote(str(val), safe='~'))))
        return '&'.join(sorted(params))

    def _get_headers_to_sign(self, request):
        headers = {'Host': urlparse.urlparse(request.url).netloc}
        for key, val in request.headers.iteritems():
            if key.lower() != 'authorization':
                headers[key] = val
        return headers

    def _get_canonical_headers(self, headers):
        header_strs = [str(key).lower().strip() + ':' + str(val).strip()
                       for key, val in headers.iteritems()]
        return '\n'.join(sorted(header_strs))

    def _get_signed_headers(self, headers):
        return ';'.join(sorted(header.lower().strip() for header in headers))


from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from gtts import gTTS
from pygame import mixer
import speech_recognition as sr
import os

r = sr.Recognizer()
mixer.init()

bot = ChatBot('Bot')
bot.set_trainer(ListTrainer)

while True:
    message = input('You: ')
    if message.strip() != 'Bye':
        reply = bot.get_response(message)

        tts = gTTS('' +str(reply), lang = 'en')
        tts.save('kasule.mp3')
        mixer.music.load('kasule.mp3')
        mixer.music.play()

        print('ChatBot :', reply)
    if message.strip() == 'Bye':
        print('ChatBot : Bye')
        break


## All the necessary middleware are configured here
from fastapi.middleware.cors import CORSMiddleware

def setup_CORS(app):
    '''
    Helps to setup the CORS middleware

    Args:
    app -- FastAPI object to add the middleware for the CORS setup
    '''
    origins = [
        "http://localhost",
        "http://localhost:3000",
        ]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )


# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Test IOTensor"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import math
import numpy
import pandas
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

import tensorflow as tf
if not (hasattr(tf, "version") and tf.version.VERSION.startswith("2.")):
  tf.compat.v1.enable_eager_execution()
from tensorflow.keras.models import Sequential # pylint: disable=wrong-import-position
from tensorflow.keras.layers import Dense # pylint: disable=wrong-import-position
from tensorflow.keras.layers import LSTM # pylint: disable=wrong-import-position

import tensorflow_io as tfio # pylint: disable=wrong-import-position

def test_window():
  """test_window"""
  value = [[e] for e in range(100)]
  value = tfio.IOTensor.from_tensor(tf.constant(value))
  value = value.window(3)
  expected_value = [[e, e+1, e+2] for e in range(98)]
  assert numpy.all(value.to_tensor().numpy() == expected_value)

  v = tfio.IOTensor.from_tensor(tf.constant([1, 2, 3, 4, 5]))
  v = v.window(3)
  assert numpy.all(v.to_tensor().numpy() == [[1, 2, 3], [2, 3, 4], [3, 4, 5]])

def test_window_to_dataset():
  """test_window_to_dataset"""
  value = [[e] for e in range(100)]
  value = tfio.IOTensor.from_tensor(tf.constant(value))
  value = value.window(3)
  expected_value = [[e, e+1, e+2] for e in range(98)]
  dataset = value.to_dataset()
  dataset_value = [d.numpy().tolist() for d in dataset]
  assert numpy.all(dataset_value == expected_value)

def test_io_tensor_from_tensor_with_sklearn():
  """test_io_tensor_from_tensor_with_sklearn"""

  # The test example is based on:
  # https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/
  #
  # Both IOTensor and pandas/sklearn are used, to show the usage of IOTensor.
  airline_passengers_csv = os.path.join(
      os.path.dirname(os.path.abspath(__file__)),
      "test_csv", "airline-passengers.csv")

  dataframe = pandas.read_csv(
      airline_passengers_csv, usecols=[1], engine='python')

  numpy.random.seed(7)

  dataset = dataframe.values
  dataset = dataset.astype('float32')

  scaler = MinMaxScaler(feature_range=(0, 1))
  dataset = scaler.fit_transform(dataset)

  # split into train and test sets
  train_size = int(len(dataset) * 0.67)
  # test_size = len(dataset) - train_size
  train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
  print(len(train), len(test))

  # convert an array of values into a dataset matrix
  def create_dataset(dataset, look_back=1):
    data_x, data_y = [], []
    for i in range(len(dataset)-look_back-1):
      a = dataset[i:(i+look_back), 0]
      data_x.append(a)
      data_y.append(dataset[i + look_back, 0])
    return numpy.array(data_x), numpy.array(data_y)

  # reshape into X=t and Y=t+1
  look_back = 1
  train_x, train_y = create_dataset(train, look_back)
  test_x, test_y = create_dataset(test, look_back)

  # reshape input to be [samples, time steps, features]
  train_x = numpy.reshape(train_x, (train_x.shape[0], 1, train_x.shape[1]))
  test_x = numpy.reshape(test_x, (test_x.shape[0], 1, test_x.shape[1]))

  # create and fit the LSTM network
  model = Sequential()
  model.add(LSTM(4, input_shape=(1, look_back)))
  model.add(Dense(1))
  model.compile(loss='mean_squared_error', optimizer='adam')

  #model.fit(train_x, train_y, epochs=100, batch_size=1, verbose=2)

  #########################################
  ############ IOTensor Match: ############
  train_size = int(len(dataset) * 0.67)
  #test_size = len(dataset) - train_size
  dataset = dataframe.values
  dataset = dataset.astype('float32')

  scaler = MinMaxScaler(feature_range=(0, 1))
  scaler.fit(tfio.IOTensor.from_tensor(dataset))

  train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]

  train_dataset = tfio.IOTensor.from_tensor(train)

  train_dataset = tfio.IOTensor.from_tensor(scaler.transform(train_dataset))

  train_dataset = train_dataset.window(look_back + 1)
  train_dataset = train_dataset.to_dataset()
  train_dataset = train_dataset.map(lambda e: tf.split(e, [look_back, 1]))
  train_dataset = train_dataset.map(lambda x, y: (tf.reshape(x, [1, look_back]), y))
  print("train_dataset: ", train_dataset)

  test_dataset = tfio.IOTensor.from_tensor(test)

  test_dataset = tfio.IOTensor.from_tensor(scaler.transform(test_dataset))

  test_dataset = test_dataset.window(look_back + 1)
  test_dataset = test_dataset.to_dataset()
  test_dataset = test_dataset.map(lambda e: tf.split(e, [look_back, 1]))
  test_dataset = test_dataset.map(lambda x, y: (tf.reshape(x, [1, look_back]), y))

  model.fit(train_dataset.batch(1), epochs=100, verbose=2)
  #########################################

  # make predictions
  train_predict = model.predict(train_x)
  test_predict = model.predict(test_x)

  #########################################
  ############ IOTensor Match: ############
  train_x_dataset = train_dataset.map(lambda x, y: x)
  test_x_dataset = test_dataset.map(lambda x, y: x)

  train_x_dataset = train_x_dataset.batch(1)
  test_x_dataset = test_x_dataset.batch(1)

  train_predict_dataset = model.predict(train_x_dataset)
  test_predict_dataset = model.predict(test_x_dataset)

  train_predict_dataset_value = [d.tolist() for d in train_predict_dataset]
  test_predict_dataset_value = [d.tolist() for d in test_predict_dataset]

  # Note: train_predict_dataset_value and test_predict_dataset_value
  # have one extra compared with original implementation.
  train_predict_dataset_value = train_predict_dataset_value[:-1]
  test_predict_dataset_value = test_predict_dataset_value[:-1]
  assert numpy.allclose(train_predict_dataset_value, train_predict.tolist())
  assert numpy.allclose(test_predict_dataset_value, test_predict.tolist())
  #########################################

  # invert predictions
  train_predict = scaler.inverse_transform(train_predict)
  train_y = scaler.inverse_transform([train_y])
  test_predict = scaler.inverse_transform(test_predict)
  test_y = scaler.inverse_transform([test_y])
  # calculate root mean squared error
  train_score = math.sqrt(mean_squared_error(train_y[0], train_predict[:, 0]))
  print('Train Score: %.2f RMSE' % (train_score))
  test_score = math.sqrt(mean_squared_error(test_y[0], test_predict[:, 0]))
  print('Test Score: %.2f RMSE' % (test_score))

  # shift train predictions for plotting
  train_predict_plot = numpy.empty_like(dataset)
  train_predict_plot[:, :] = numpy.nan
  train_predict_plot[look_back:len(train_predict)+look_back, :] = train_predict
  # shift test predictions for plotting
  test_predict_plot = numpy.empty_like(dataset)
  test_predict_plot[:, :] = numpy.nan
  test_predict_plot[
      len(train_predict)+(look_back*2)+1:len(dataset)-1, :] = test_predict

  # plot baseline and predictions
  #plt.plot(scaler.inverse_transform(dataset))
  #plt.plot(train_predict_plot)
  #plt.plot(test_predict_plot)
  #plt.show()


import machine
import time
from registers import *

class ILI9341(object):
    # Pinout, change within or outside class for your use case
    PINS = [32,33,25,26,27,14,12,13,16,17,4,19,22]
    # Pin names, don't change
    PIN_NAMES = ['RST','CS','RS','WR','RD','D0','D1','D2','D3','D4','D5','D6','D7']

    # Dict of pins
    pins = {}

    # Pin mode, push-pull control
    PIN_MODE = machine.Pin.OUT

    TFTWIDTH  = 240
    TFTHEIGHT = 320

    # Designation of T/F for command data and command modes
    LCD_CDT = True
    LCD_CMD = False

    # Timing constants
    E_PULSE = 50
    E_DELAY = 50

    def init(self):
        # Initialise pins
        for pin, pin_name in zip(self.PINS, self.PIN_NAMES):
            # setattr(self, 'LCD_'+pin_name,   # Unsupported
            #     machine.Pin(pin, self.PIN_MODE))
            self.pins['LCD_'+pin_name] = machine.Pin(pin, self.PIN_MODE)

        self.pin_action('LCD_CS', False)

        # Initialise display
        self.WriteRegister8(ILI9341_SOFTRESET, 0)
        self.udelay(50)
        self.WriteRegister8(ILI9341_DISPLAYOFF, 0)

        self.WriteRegister8(ILI9341_POWERCONTROL1, 0x23)
        self.WriteRegister8(ILI9341_POWERCONTROL2, 0x10)
        self.WriteRegister16(ILI9341_VCOMCONTROL1, 0x2B2B)
        self.WriteRegister8(ILI9341_VCOMCONTROL2, 0xC0)
        self.WriteRegister8(ILI9341_MEMCONTROL, ILI9341_MADCTL_MY | ILI9341_MADCTL_BGR)
        self.WriteRegister8(ILI9341_PIXELFORMAT, 0x55)
        self.WriteRegister16(ILI9341_FRAMECONTROL, 0x001B)

        self.WriteRegister8(ILI9341_ENTRYMODE, 0x07)

        self.WriteRegister8(ILI9341_SLEEPOUT, 0)
        self.udelay(150)
        self.WriteRegister8(ILI9341_DISPLAYON, 0)
        self.udelay(500)

        self.setAddrWindow(0, 0, self.TFTWIDTH-1, self.TFTHEIGHT-1)

        self.pin_action('LCD_CS', True)

    def setAddrWindow(self, x1, x2, y1, y2):

        self.pin_action('LCD_CS', False)

        t = x1;
        t <<= 16;
        t |= x2;
        self.WriteRegister32(ILI9341_COLADDRSET, t)
        t = y1;
        t <<= 16;
        t |= y2;
        self.WriteRegister32(ILI9341_PAGEADDRSET, t)

        self.pin_action('LCD_CS', True)

    def drawPixel(self, x, y, color):

        self.pin_action('LCD_CS', False)

        self.setAddrWindow(x, y, self.TFTWIDTH-1, self.TFTHEIGHT-1)

        self.lcd_byte(0x2C,self.LCD_CMD)
        self.lcd_byte(color >> 8,self.LCD_CDT)
        self.lcd_byte(color,self.LCD_CDT)

        self.pin_action('LCD_CS', True)

    def flood(self, color, lent):

        self.pin_action('LCD_CS', False)

        self.lcd_byte(0x2C,self.LCD_CMD)
        self.lcd_byte(color >> 8,self.LCD_CDT)
        self.lcd_byte(color,self.LCD_CDT)

        blocks = lent/64

        while blocks:
            blocks -= 1
            i = 17
            while i:
                self.lcd_byte(color >> 8,self.LCD_CDT)
                self.lcd_byte(color,self.LCD_CDT)
                self.lcd_byte(color >> 8,self.LCD_CDT)
                self.lcd_byte(color,self.LCD_CDT)
                self.lcd_byte(color >> 8,self.LCD_CDT)
                self.lcd_byte(color,self.LCD_CDT)
                self.lcd_byte(color >> 8,self.LCD_CDT)
                self.lcd_byte(color,self.LCD_CDT)
                i = i - 1

        self.pin_action('LCD_CS', True)

    def fillScreen(self,color):

        self.setAddrWindow(0, 0, self.TFTWIDTH-1, self.TFTHEIGHT-1)
        self.flood(color, self.TFTHEIGHT * self.TFTWIDTH)

    def lcd_byte(self, bits, mode):
        # Send byte to data pins
        # bits = data
        # mode = True  for character
        #        False for command

        self.pin_action('LCD_RS', mode) # RS

        # High bits
        self.pin_action('LCD_D0', False)
        self.pin_action('LCD_D1', False)
        self.pin_action('LCD_D2', False)
        self.pin_action('LCD_D3', False)
        self.pin_action('LCD_D4', False)
        self.pin_action('LCD_D5', False)
        self.pin_action('LCD_D6', False)
        self.pin_action('LCD_D7', False)
        if bits&0x01==0x01:
            self.pin_action('LCD_D0', True)
        if bits&0x02==0x02:
            self.pin_action('LCD_D1', True)
        if bits&0x04==0x04:
            self.pin_action('LCD_D2', True)
        if bits&0x08==0x08:
            self.pin_action('LCD_D3', True)
        if bits&0x10==0x10:
            self.pin_action('LCD_D4', True)
        if bits&0x20==0x20:
            self.pin_action('LCD_D5', True)
        if bits&0x40==0x40:
            self.pin_action('LCD_D6', True)
        if bits&0x80==0x80:
            self.pin_action('LCD_D7', True)

        # Toggle 'Enable' pin
        self.udelay(self.E_DELAY)
        self.pin_action('LCD_WR', False)
        self.udelay(self.E_PULSE)
        self.pin_action('LCD_WR', True)
        self.udelay(self.E_DELAY)

    def WriteRegister8(self, register, cdata):
        self.lcd_byte(register,self.LCD_CMD)
        self.lcd_byte(cdata,self.LCD_CDT)

    def WriteRegister16(self, register, cdata):
        self.lcd_byte(register,self.LCD_CMD)
        self.lcd_byte(cdata & 0xFF,self.LCD_CDT)
        self.lcd_byte((cdata & 0xFF00) >> 8,self.LCD_CDT)

    def WriteRegister32(self, register, cdata):
        self.lcd_byte(register,self.LCD_CMD)
        self.lcd_byte(cdata & 0xFF,self.LCD_CDT)
        self.lcd_byte((cdata & 0xFF00) >> 8,self.LCD_CDT)
        self.lcd_byte((cdata & 0xFF0000) >> 16,self.LCD_CDT)

    def udelay(self, us):
        # Delay by us microseconds, set as function for portability
        time.sleep_us(us)

    def pin_action(self, pin, high):
        # Pin high/low functions, set as function for portability
        if high:
            self.pins[pin].value(1)
        else:
            self.pins[pin].value(0)


# coding: utf-8
'''
Created on 2016年6月19日

@author: tack
'''
import datetime
import logging
import os
from logging.handlers import RotatingFileHandler

def __getlog(name='mylog'):
    '''
        get a logging instance by name
    '''
    LOGGING_FORMAT = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s'
    DATE_FORMAT = '%y%m%d %H:%M:%S'
    formatter = logging.Formatter(LOGGING_FORMAT, DATE_FORMAT)
    # formatter = logging.Formatter('%(asctime)s:%(message)s')
    log = logging.getLogger(name)
    handler = RotatingFileHandler('logs/' + name + '.log', maxBytes=50 * 1024 * 1024, backupCount=10)
    # handler = logging.FileHandler('logs/' + name + '.log')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    log.setLevel(logging.INFO)
    return log

def __state_log(name='state'):
    '''
    create a logger instance
    :param name:
    :return:
    '''
    # LOGGING_FORMAT = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s'
    log = logging.getLogger('.')
    handler = logging.FileHandler(name)
    log.addHandler(handler)
    log.setLevel(logging.INFO)
    return log

def read_last_state(name='state'):
    stat = {}
    if os.path.exists('state'):
        for line in open('state', 'r'):
            arr = line.strip().split(',')
            code = arr[0]
            # dt = arr[1].replace('-', '')
            dt = arr[1]
            if code in stat:
                if dt > stat[code]:
                    stat[code] = dt
            else:
                stat[code] = dt
    return stat

mylog = __getlog()
__state = read_last_state()
statelog = __state_log()

def get_laste_update_dt(code):
    return __state.get(code, None)

def mkdirs(path):
    '''
    make dirs
    '''
    if not os.path.exists(path):
        os.makedirs(path)

def today_last_year(years=1):
    lasty = datetime.datetime.today().date() + datetime.timedelta(-365 * years)
    return str(lasty)

def day_befor(days=1):
    lasty = datetime.datetime.today().date() - datetime.timedelta(days=days)
    return str(lasty)

if __name__ == '__main__':
    print(day_befor(10))


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        nodes = []
        while head is not None:
            nodes.append(head)
            head = head.next
        if n is len(nodes):
            return nodes[0].next
        else:
            nodes[-n-1].next = nodes[-n].next
            return nodes[0]
#Runtime:45ms
#This function use extra space O(n),try using O(1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        fast = slow = head
        for _ in range(n):
            fast = fast.next
        if fast is None:return head.next
        while fast.next is not None:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return head
#Runtime:52ms
#But this is better.


#!/usr/bin/env python

import rospy
import std_msgs.msg

from servo import Servo

COMPUTER = rospy.get_param('/computer')

PWM_FREQUENCY = rospy.get_param('/tilt_servo/pwm/frequency')
SERVO_PWM_PIN = rospy.get_param('/tilt_servo/pwm/pin')
DUTY_CYCLE_MIN = rospy.get_param('/tilt_servo/duty_cycle_min')
DUTY_CYCLE_MAX = rospy.get_param('/tilt_servo/duty_cycle_max')
SCALE_RANGE = rospy.get_param('/tilt_servo/scale_range')

def healthy_message(msg):
    if abs(msg.data) > 1:
        rospy.logwarn_throttle(
            1, 'Camera servo position out of range. Ignoring message...')
        return False
    return True

class ServoInterface(object):
    def __init__(self):
        self.is_initialized = False
        rospy.init_node('servo_interface', anonymous=False)
        self.sub = rospy.Subscriber(
            'camera_position', std_msgs.msg.Float64, self.callback)

        rospy.on_shutdown(self.shutdown)

        try:
            self.tilt_servo = Servo(SERVO_PWM_PIN,
                                    PWM_FREQUENCY,
                                    DUTY_CYCLE_MIN,
                                    DUTY_CYCLE_MAX,
                                    SCALE_RANGE,
                                    COMPUTER)
            self.tilt_position = 0
        except NameError:
            rospy.logfatal('Could not initialize servo.py. Is /computer parameter set correctly? '
                           'Shutting down node...')
            rospy.signal_shutdown('')
        except:
            rospy.logfatal("Unexpected error:", sys.exc_info()[0])
            raise

        self.tilt_servo.set_position(self.tilt_position)
        rospy.loginfo('Initialized camera tilt servo in neutral position.')
        self.is_initialized = True
        self.spin()

    def spin(self):
        rate = rospy.Rate(PWM_FREQUENCY)

        while not rospy.is_shutdown():
#            tilt_position = tilt_position + \
#                tilt_servo_resolution * tilt_servo_direction
            # Move servo if nonzero direction
#            if abs(self.tilt_servo_direction) == 1:
#                self.tilt_servo.set_position(tilt_position)

            rate.sleep()

    def shutdown(self):
        self.tilt_servo.shutdown()

    def callback(self, msg):
        if not self.is_initialized:
            rospy.logwarn('Callback before node initialized, ignoring...')
            return

        if not healthy_message(msg):
            return

        self.tilt_position = msg.data
        self.tilt_servo.set_position(msg.data)

if __name__ == '__main__':
    try:
        servo_interface = ServoInterface()
        rospy.spin()
    except rospy.ROSInterruptException:
        pass


# coding=utf-8

"""Minimum Number of Arrows to Burst Balloons.

>>> solve = _solve
>>> solve([[10, 16], [2, 8], [1, 6], [7, 12]])
2
>>> solve([[9, 12], [1, 10], [4, 11], [8, 12], [3, 9], [6, 9], [6, 7]])
2
"""

def _solve(points):
    res, border = 0, -float('inf')
    for left, right in sorted(points, key=lambda point: point[1]):
        if left > border:
            res += 1
            border = right
    return res


import argparse
from datetime import datetime
import os
import re

class NotesManager:
    """
    Note file format: YYYY-MM-DD_TYPE_detail_seq.txt
    e.g. 2018-01-01-meeting-generic.txt
        2018-01-02_one-on-one_rohit.txt
        2018-01-02_interview_shiva-sundaram.txt
    """
    def __init__(self):
        self.BASEDIR='./data/'

    def create_file(self, filename):
        f=open("./data/" + filename,"a+")
        f.close()

    def list(self, category=None):
        if category is None:
            category = ''
        for filename in os.listdir(self.BASEDIR):
            if category in filename:
                print(filename)

    def create(self, category, detail):
        if category is None:
            category='meeting'
        if detail is None:
            detail='self'
        now = datetime.now()
        date_string= datetime.today().strftime('%Y-%m-%d')
        self.create_file('_'.join([date_string, category, detail]) + '.txt')

if __name__ =='__main__':
    nm = NotesManager()
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--new", action="store_true", help="create a new note\n usage: notes.py -c category detail")
    parser.add_argument("-l", "--list", action="store_true", help="list most recent notes")
    parser.add_argument("-o", "--overwrite", action="store_true", help="overwrite previous note")
    parser.add_argument("-c", "--category", help="category of the notes, e.g. meeting, todo, oneonone")
    parser.add_argument("-d", "--detail", help="additional details for the notes e.g. meeting subject, 1_1 person")
    args = parser.parse_args()
    if args.list:
        nm.list(args.category)
    elif args.new:
        nm.create(args.category, args.detail)
        nm.list(args.category)
    else:
        nm.list(args.category)


# -*- coding: utf-8 -*-
"""
Created on Sat Feb  1 14:04:55 2020
創建104爬蟲
@author: 軒亭
"""

import requests
from bs4 import BeautifulSoup

xx="高薪" #搜尋工作類型

for i in range(1,10):
    url=f"https://www.104.com.tw/jobs/search/?ro=0&kwop=7&keyword={xx}&area=6001008000&order=11&asc=0&page={i}&mode=s"
    aa=requests.get(url)
    bs=BeautifulSoup(aa.text, 'html.parser')
    ww=bs.find_all(class_="b-block--top-bord job-list-item b-clearfix js-job-item")
    for dd in ww:
        cc=dd.find(class_="b-tit")
        ee=dd.find(class_="b-block__left")
        print(cc.a.text.strip())
        print(cc.a["href"])
        try:

            print(ee.p.text.strip())

        except BaseException as k:
            print(k)
        print("---------------------------------------------------")


import random
import time
import json
import discord

class character():
    # Parameterized constructor for character class object
    def __init__(self, name, level, battleclass):
        self.name = name
        self.level = level
        self.battleclass = battleclass
        self.stats = [] # Possible dict conversion with format: {"Health" : "" , "Attack" : "" , "Defense" : "" , "Speed" : "" , "Critical" : ""}
        self.health = 100

        #  Assigns character object stats variable based on characterClass
        if battleclass == "warrior":
            self.attack = random.randint(1, 20)
            self.defense = random.randint(20, 20)
            self.speed = random.randint(1, 20)
            self.critical = random.randint(1, 20)
            self.stats.insert(0, self.health)
            self.stats.insert(1, self.attack)
            self.stats.insert(2, self.defense)
            self.stats.insert(3, self.speed)
            self.stats.insert(4, self.critical)

        elif battleclass == "ranger":
            self.attack = random.randint(1, 20)
            self.defense = random.randint(1, 20)
            self.speed = random.randint(20, 20)
            self.critical = random.randint(1, 20)
            self.stats.insert(0, self.health)
            self.stats.insert(1, self.attack)
            self.stats.insert(2, self.defense)
            self.stats.insert(3, self.speed)
            self.stats.insert(4, self.critical)

        elif battleclass == "castor":
            self.attack = random.randint(20, 20)
            self.defense = random.randint(1, 20)
            self.speed = random.randint(1, 20)
            self.critical = random.randint(1, 20)
            self.stats.insert(0, self.health)
            self.stats.insert(1, self.attack)
            self.stats.insert(2, self.defense)
            self.stats.insert(3, self.speed)
            self.stats.insert(4, self.critical)

    # Prints the details of the character object
    def printDetails(self):
        embed = discord.Embed(title="Character Stats:", color=0x00ff00)
        embed.set_thumbnail(url="https://orig00.deviantart.net/f025/f/2017/277/f/2/ffbe___cloud_strife_gif_2_by_zerolympiustrife-dbpjw5t.gif")
        embed.add_field(name="Attack", value=str(self.attack), inline=True)
        embed.add_field(name="Defense", value=str(self.defense), inline=True)
        embed.add_field(name="Speed", value=str(self.speed), inline=True)
        embed.add_field(name="Luck", value=str(self.critical), inline=True)
        embed.add_field(name="Level", value=str(self.level), inline=True)
        return embed

    # Series of accessors and mutators for character objects
    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def setLevel(self, level):
        self.level = level

    def getLevel(self):
        return self.level

    def setBattleclass(self, battleclass):
        self.battleclass = battleclass

    def getBattleclass(self):
        return self.battleclass

    # Returns a specific stat based on index ({0 - 4} / {Health - Critical})
    def getStats(self, value):
        return self.stats[value:value + 1]

# Begin user adventure with character object creation
# characterName = input("\nEnter character name:\n")
#
#
# tempLevel = int(input("\nEnter character level:\n"))
# if tempLevel != 1:
#     boolLevelFlag = False
# else:
#     characterLevel = tempLevel
#     boolLevelFlag = True
#
# # Validate whether user has access to override character default level
# while not boolLevelFlag:
#     print("Input Alert: You are trying to create a character level higher than 1.")
#     passwordToken = input("\nEnter your admin password:\n")
#
#     if passwordToken == "admin":
#         print("Access Granted!")
#         characterLevel = tempLevel
#         boolLevelFlag = True
#
#     else:
#         print("Access Denied!")
#         tempLevel = 1
#         characterLevel = tempLevel
#         boolLevelFlag = True
#
#
# print("\nValid battle classes:"
#       "\nWarrior: Specializes in defense."
#       "\nRanger: Specializes in speed."
#       "\nCastor: Specializes in attack.")
#
# tempBattleClass = input("\nEnter your battle class:\n")
#
# # Validate user input for battle class
# while not (tempBattleClass.lower() == "warrior" or tempBattleClass.lower() == "ranger"
#            or tempBattleClass.lower() == "castor"):
#     print("You must select a valid battle class.")
#     tempBattleClass = input("\nEnter your battle class:\n")
#
# characterClass = tempBattleClass.lower()

# Function to create one of 3 random enemies using RNG
def randomEnemy(level):
    rng = random.randint(1, 3)
    if rng == 1:
        characterName = "Goblin"
        characterLevel = level
        characterClass = "warrior"

    elif rng == 2:
        characterName = "Skeleton"
        characterLevel = level
        characterClass = "ranger"

    else:
        characterName = "Witch"
        characterLevel = level
        characterClass = "castor"

    return character(characterName, characterLevel, characterClass)

# ------------------ #
# UNDER CONSTRUCTION #
# ------------------ #

# Begin user battle sequence
# def battleSequence(character, enemy):
#     print("\n" + enemy.name + " appears and challenges " + character.name + " to battle!")
#     enemy.printDetails()
#
#     while character.health > 0 and enemy.health > 0:
#         if character.health > 100:
#             character.health = 100
#
#         if enemy.health > 100:
#             enemy.health = 100
#
#         print("\n" + character.name + "'s Health: " + str(character.health))
#         print(enemy.name + "'s Health: " + str(enemy.health))
#
#         print("\nNext move:\n1. Attack\n2. Defend\n3. Flee\n")
#         choice = int(input("\nEnter the number of your choice:\n"))
#
#         # Validate user choice
#         while not (choice == 1 or choice == 2 or choice == 3):
#             print("\nPlease enter a valid choice!\n")
#             choice = int(input("\nEnter the number of your choice:\n"))
#
#         # Determine enemy turn
#         rng = random.randint(1, 2)
#
#         # Situation 1: character -> ATTACK and enemy -> ATTACK
#         if choice == 1 and rng == 1:
#
#             # Situation 1a: character attacks first
#             if character.speed > enemy.speed:
#                 print(character.name + " attacks first with Speed: " + str(character.speed) + "!")
#                 enemyDmgTaken = character.attack
#                 critRoll = random.randint(1, 100)
#
#                 if critRoll <= character.critical:
#                     print("It's super effective!")
#                     enemyDmgTaken += (character.attack / 2)
#
#                 print(character.name + " strikes " + enemy.name + " for " + str(enemyDmgTaken) + " points of damage!")
#                 enemy.health -= enemyDmgTaken
#                 print(enemy.name + "'s Health: " + str(enemy.health) + "\n")
#
#                 # enemy attacks second
#                 print(enemy.name + " attacks second with Speed: " + str(enemy.speed) + "!")
#                 characterDmgTaken = enemy.attack
#                 critRoll = random.randint(1, 100)
#
#                 if critRoll <= enemy.critical:
#                     print("It's super effective!")
#                     characterDmgTaken += (enemy.attack / 2)
#
#                 print(enemy.name + " strikes " + character.name + " for " + str(characterDmgTaken) + " points of damage!")
#                 character.health -= characterDmgTaken
#                 print(character.name + "'s Health: " + str(character.health) + "\n")
#
#             # Situation 1b: enemy attacks first
#             else:
#                 print(enemy.name + " attacks first with Speed: " + str(enemy.speed) + "!")
#                 characterDmgTaken = enemy.attack
#                 critRoll = random.randint(1, 100)
#
#                 if critRoll <= enemy.critical:
#                     print("It's super effective!")
#                     characterDmgTaken += (enemy.attack / 2)
#
#                 print(enemy.name + " strikes " + character.name + " for " + str(characterDmgTaken) + " points of damage!")
#                 character.health -= characterDmgTaken
#                 print(character.name + "'s Health: " + str(character.health) + "\n")
#
#                 # character attacks second
#                 print(character.name + " attacks second with Speed: " + str(character.speed) + "!")
#                 enemyDmgTaken = character.attack
#                 critRoll = random.randint(1, 100)
#
#                 if critRoll <= character.critical:
#                     print("It's super effective!")
#                     enemyDmgTaken += (character.attack / 2)
#
#                 print(character.name + " strikes " + enemy.name + " for " + str(enemyDmgTaken) + " points of damage!")
#                 enemy.health -= enemyDmgTaken
#                 print(enemy.name + "'s Health: " + str(enemy.health) + "\n")
#
#         # Situation 2: character -> ATTACK and enemy -> DEFEND
#         if choice == 1 and rng == 2:
#
#             # character damages enemy after factoring in enemy's defense
#             print(character.name + " attacks " + enemy.name + "!")
#             enemyDmgTaken = character.attack
#             critRoll = random.randint(1, 100)
#             if critRoll <= character.critical:
#                 print("It's super effective!")
#                 enemyDmgTaken += (character.attack / 2)
#
#             print(enemy.name + " defends against " + character.name + "'s attack!")
#             enemyDmgTaken -= enemy.defense
#             critRoll = random.randint(1, 100)
#             if critRoll <= enemy.critical:
#                 print("It's super effective!")
#                 enemyDmgTaken -= (enemy.defense / 2)
#
#             if enemyDmgTaken > 0:
#                 print(character.name + " strikes " + enemy.name + " for " + str(enemyDmgTaken) + " points of damage!")
#                 enemy.health -= enemyDmgTaken
#
#             elif enemyDmgTaken < 0:
#                 print(enemy.name + " blocks all damage from " + character.name + "!")
#                 print("+5 Health to " + enemy.name)
#                 enemy.health += 5
#
#             else:
#                 print(enemy.name + " blocks all damage from " + character.name + "!")
#
#         # Situation 3: character -> DEFEND and enemy -> ATTACK
#         if choice == 2 and rng == 1:
#
#             # enemy damages character after factoring in character's defense
#             print(enemy.name + " attacks " + character.name + "!")
#             characterDmgTaken = enemy.attack
#             critRoll = random.randint(1, 100)
#             if critRoll <= enemy.critical:
#                 print("It's super effective!")
#                 characterDmgTaken += (enemy.attack / 2)
#
#             print(character.name + " defends against " + enemy.name + "'s attack!")
#             characterDmgTaken -= character.defense
#             critRoll = random.randint(1, 100)
#             if critRoll <= character.critical:
#                 print("It's super effective!")
#                 characterDmgTaken -= (character.defense / 2)
#
#             if characterDmgTaken > 0:
#                 print(enemy.name + " strikes " + character.name + " for " + str(characterDmgTaken) + " points of damage!")
#                 character.health -= characterDmgTaken
#
#             elif characterDmgTaken < 0:
#                 print(character.name + " blocks all damage from " + enemy.name + "!")
#                 print("+5 Health to " + character.name)
#                 character.health += 5
#
#             else:
#                 print(character.name + " blocks all damage from " + enemy.name + "!")
#
#             print(character.name + "'s Health: " + str(character.health))
#
#         # Situation 4: character -> DEFEND and character -> DEFEND
#         if choice == 2 and rng == 2:
#
#             print(character.name + " and " + enemy.name +" both defend against nothing?!\n")
#             print("Both adversaries begin to taunt each other from a distance!")
#             print("The adrenaline from taunting causes both entities to heal a small amount of health!")
#             print("\n+5 Health to both " + character.name + " and " + enemy.name + "!")
#             character.health += 5
#             enemy.health += 5
#
#         # Situation 5: character -> FLEE and enemy -> ATTACK
#         if choice == 3 and rng == 1:
#
#             print(character.name + " attempts to flee from the battle!\n")
#             time.sleep(2)
#
#             # Roll to determine outcome of attempted FLEE
#             fleeRoll = random.randint(1, 100)
#             if fleeRoll <= character.speed:
#                 print("Success!\n")
#                 print(character.name + " flees from the battle to live another day!")
#                 enemy.health = 0
#
#             else:
#                 print("Fail!\n")
#                 print(character.name + " tries to flee but trips and lands on their face...")
#                 print("-5 Health to " + character.name + "\n")
#                 character.health -= 5
#
#                 # enemy attacks character
#                 print(enemy.name + " attacks " + character.name + "!")
#                 characterDmgTaken = enemy.attack
#                 critRoll = random.randint(1, 100)
#
#                 if critRoll <= enemy.critical:
#                     print("It's super effective!")
#                     characterDmgTaken += (enemy.attack / 2)
#
#                 print(enemy.name + " strikes " + character.name + " for " + str(characterDmgTaken) + " points of damage!")
#                 character.health -= characterDmgTaken
#                 print(character.name + "'s Health: " + str(character.health) + "\n")
#
#         # Situation 6: character -> FLEE and enemy -> DEFEND
#         if choice == 3 and rng == 2:
#
#             print(character.name + " attempts to flee from the battle!\n")
#             time.sleep(2)
#
#             # Roll to determine outcome of attempted FLEE
#             fleeRoll = random.randint(1, 100)
#             if fleeRoll <= character.speed:
#                 print("Success!\n")
#                 print(character.name + " flees from the battle to live another day!")
#                 enemy.health = 0
#
#             else:
#                 print("Fail!\n")
#                 print(character.name + " tries to flee but trips and lands on their face...")
#                 print(enemy.name + " laughs at " + character.name + "'s failure!\n")
#                 print("The shame causes " + character.name + " to lose additional health...")
#                 print("-10 Health to " + character.name)
#                 character.health -= 10
#                 print(character.name + "'s Health: " + str(character.health) + "\n")
#
#
#     print("\nEND OF BATTLE!\n")
#
#
#     if character.health > 0:
#         print(character.name + " wins the battle against " + enemy.name + "!\n")
#
#     else:
#         print(character.name + " loses the battle against " + enemy.name + "!\n")

# Reading from JSON file
#  with open("data.txt") as json_file:
#      data = json.load(json_file)
#      for x in data['character']:
#          print("Character Name: " + x["name"])
#          print("Character Level: " + x["level"])
#          print("Character Class: ") + x["battleclass"]
#          print("Character Stats: " + x["stats"] + "\n")

# Saving to JSON file
#  data = {}
#  data['character'] = []
#  data['character'].append({
#      'name': characterName,
#      'level': characterLevel,
#      'battleclass': characterClass,
#      'stats': character.stats
#  })
#
#  with open("data.txt", "w") as outfile:
#      json.dump(data, outfile)

# char1 = character(characterName, characterLevel, characterClass)
# char1.printDetails()
#
# time.sleep(2) # Pause between displaying character details
#
# enemy1 = randomEnemy()
#
# time.sleep(2) # Pause before first battle sequence
#
# battleSequence(char1, enemy1)


"""
YouTube API For POTATO BOT.
Made By stshrewsburyDev (AKA: Steven Shrewsbury)
"""

import argparse
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def search(DEV_KEY, options):
    youtube = build("youtube", "v3", developerKey=DEV_KEY)

    search_response = youtube.search().list(q=options.q,
                                            part="id,snippet",
                                            maxResults=options.max_results
                                            ).execute()

    results = {}

    videos = []
    channels = []
    playlists = []

    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            videos.append(search_result)
        elif search_result["id"]["kind"] == "youtube#channel":
            channels.append(search_result)
        elif search_result["id"]["kind"] == "youtube#playlist":
            playlists.append(search_result)

    results["videos"] = videos
    results["channels"] = channels
    results["playlists"] = playlists

    return results

def get_videos(DEV_KEY, search_query, max_results):
    parser = argparse.ArgumentParser()
    parser.add_argument("--q", help="Serch term", default=search_query)
    parser.add_argument("--max-results", help="Max results", default=max_results)
    options = parser.parse_args()

    return search(DEV_KEY=DEV_KEY,
                  options=options)["videos"]


from sqlalchemy import create_engine, MetaData, Table
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

def get_data(db_url, table_name='exp_table', data_column_name='datastring', statuses=[3,4,5,7], exclude = []):
    # boilerplace sqlalchemy setup
    engine = create_engine(db_url)
    metadata = MetaData()
    metadata.bind = engine
    table = Table(table_name, metadata, autoload=True)
    # make a query and loop through
    s = table.select()
    rows = s.execute()

    data = []

    for row in rows:
        # only use subjects who completed experiment and aren't excluded
        if row['status'] in statuses and row['uniqueid'] not in exclude:
            data.append(row[data_column_name])

    # Now we have all participant datastrings in a list.
    # Let's make it a bit easier to work with:

    # parse each participant's datastring as json object
    # and take the 'data' sub-object
    data = [json.loads(part)['data'] for part in data]

    # insert uniqueid field into trialdata in case it wasn't added
    # in experiment:
    for part in data:
        for record in part:
            record['trialdata']['uniqueid'] = record['uniqueid']

    # flatten nested list so we just have a list of the trialdata recorded
    # each time psiturk.recordTrialData(trialdata) was called.
    data = [record['trialdata'] for part in data for record in part]

    # Put all subjects' trial data into a dataframe object from the
    # 'pandas' python library: one option among many for analysis
    data_frame = pd.DataFrame(data)

    return data_frame

def get_learning_curve(data, block_size=30, plot=True):
    data_len = len(data)
    n_blocks = data_len/block_size
    block_indices = np.linspace(0, data_len, num=n_blocks+1, dtype=int)
    p_correct = np.zeros(n_blocks)
    for block in range(n_blocks):
        p_correct[block] = np.mean(data['hit'][block_indices[block]:block_indices[block+1]])
    if plot:
        pc, = plt.plot(range(1, n_blocks+1), p_correct)
        plt.xlabel("block", fontsize=30)
        plt.ylabel("% correct", fontsize=30)
        plt.ylim(0, 1)
        plt.xticks(range(1, n_blocks+1))
    return p_correct

def get_avg_samps(data, block_size=30, plot=True, att_feature='locSamps'):
    data_len = len(data)
    n_blocks = data_len/block_size
    block_indices = np.linspace(0, data_len, num=n_blocks+1, dtype=int)
    att_p = np.zeros(n_blocks)
    for block in range(n_blocks):
        att_p[block] = np.mean(data[att_feature][block_indices[block]:block_indices[block+1]])
    if plot:
        pc, = plt.plot(range(1, n_blocks+1), att_p)
        plt.xlabel("block", fontsize=30)
        plt.ylabel("Avg. # of samples", fontsize=30)
        plt.ylim(0, 10)
        plt.xticks(range(1, n_blocks+1))
    return att_p

def get_noise_estimates(data, plot=True):
	color_noise = data[data['colorNoise'].notnull()]['colorNoise']
	color_noise = color_noise[color_noise.keys()[0]]
	loc_noise = data[data['colorNoise'].notnull()]['locNoise']
	loc_noise = loc_noise[loc_noise.keys()[0]]
	if plot:
		color, = plt.plot(color_noise, label="Color")
		loc, = plt.plot(loc_noise, label="Location")
		plt.xlabel("# samples", fontsize=30)
		plt.ylabel("$\sigma$", fontsize=30)
		plt.ylim(0, 1)
		plt.legend(handles=[loc, color], loc=2, bbox_to_anchor=(1.05, 1))
	return loc_noise, color_noise


#!/usr/bin/python3
"""
Test for the City class
"""

from datetime import datetime
import inspect
from models import city
from models.base_model import BaseModel
import pep8
import unittest
City = city.City

c = "created_at"
u = "updated_at"

class TestStateDocStyle(unittest.TestCase):
    """test for documentation and pep8 style"""
    def setUp(cls):
        """set up for methods"""
        cls.city_func = inspect.getmembers(City, inspect.isfunction)

    def test_pep8(self):
        """test pep8 in City class"""
        pep8s = pep8.StyleGuide(quiet=True)
        result = pep8s.check_files(['models/city.py'])
        self.assertEqual(result.total_errors, 0,
                         "Found code style errors and warnings.")

    def test_pep8_test(self):
        """test pep8 for test to City class"""
        pep8s = pep8.StyleGuide(quiet=True)
        result = pep8s.check_files(['tests/test_models/test_city.py'])
        self.assertEqual(result.total_errors, 0,
                         "Found code style errors and warnings.")

    def test_module_doc(self):
        """test for the doc in module"""
        self.assertIsNot(city.__doc__, None,
                         "city.py without a docstring")
        self.assertTrue(len(city.__doc__) >= 1,
                        "city.py without a docstring")

    def test_class_doc(self):
        """test for class documentation"""
        self.assertIsNot(City.__doc__, None,
                         "City class without docstring")
        self.assertTrue(len(City.__doc__) >= 1,
                        "City class without docstring")

    def test_func_doc(self):
        """test for doc in methods"""
        for func in self.city_func:
            self.assertIsNot(func[1].__doc__, None,
                             "{:s} docstring needed in method".format(func[0]))
            self.assertTrue(len(func[1].__doc__) >= 1,
                            "{:s} docstring needed in method".format(func[0]))

class TestCityClass(unittest.TestCase):
    """test for class"""
    def test_is_subclass(self):
        """test for a subclass of BaseModel"""
        city = City()
        self.assertIsInstance(city, BaseModel)
        self.assertTrue(hasattr(city, "id"))
        self.assertTrue(hasattr(city, "created_at"))
        self.assertTrue(hasattr(city, "updated_at"))

    def test_state_id(self):
        """thest for for attribute state id for City class"""
        city = City()
        self.assertTrue(hasattr(city, "state_id"))
        self.assertEqual(city.state_id, "")

    def test_name(self):
        """test for the state_id attr"""
        city = City()
        self.assertTrue(hasattr(city, "name"))
        self.assertEqual(city.name, "")

    def test_to_dict_values(self):
        """test the values in dict"""
        time = "%Y-%m-%dT%H:%M:%S.%f"
        city = City()
        new_dict = city.to_dict()
        self.assertEqual(new_dict["__class__"], "City")
        self.assertEqual(type(new_dict[c]), str)
        self.assertEqual(type(new_dict[u]), str)
        self.assertEqual(new_dict[c], city.created_at.strftime(time))
        self.assertEqual(new_dict[u], city.updated_at.strftime(time))

    def test_str(self):
        """test for output str method"""
        city = City()
        string = "[City] ({}) {}".format(city.id, city.__dict__)
        self.assertEqual(string, str(city))


'''
Created on 14 de ago de 2016

@author: anderson
'''
from django.conf.urls import patterns, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('web_critic.core.views',
                       url(r'^$', 'home', name='home'),
                       url(r'^contact/$', 'contact', name="contact"),
                       )


# -*- coding: utf-8 -*-
import random
import math
import time
import KBEngine
from KBEDebug import *
import SCDefine
from interfaces.GameObject import GameObject

#Trap基础上可以扩展出有战斗属性的比如：图腾
class Trap(KBEngine.Entity, GameObject):
	def __init__(self):
		KBEngine.Entity.__init__(self)
		GameObject.__init__(self)

		self.init = False

		self.castID = 0#释放者ID
		self.life = 3#trap生命
		self.inv = 1#间隔时间
		self.invTimes = 1#间隔次数
		self.effectInv = []#过程中的效果
		self.effectEnd = []#结束时的效果

		self.territoryControllerID = 0#trap监测ID
		self.trapEntity = []#trap范围内entity

		if self.life == 0 and self.invTimes == 0:
			ERROR_MSG("trap life == 0 && invTimes == 0")
			#有问题，需要删除trap
			self.destroy()
			return
		self.timerID = self.addTimer(0.1, 0.1, SCDefine.TIMER_TYPE_HEARDBEAT)

		#临时变量存储trapID没有赋值之前得到的entity信息,主要是为了应对kbe的机制
		self.tmpB = False
		self.tmpTrapID = 0
		self.tmpTrap = []
		#一旦trapID正常，以上就失去作用

		ERROR_MSG("trap init")

	def onDestroy(self):
		ERROR_MSG("trap detroy")

	def isEnemy(self, entityC):
		sname = entityC.getScriptName()
		if sname == "Avatar" or sname == "NPC" or sname == "Monster":
			if entityC.isDead():
				return False
			return True
		return False

	def onTimer(self, tid, userArg):
		if not self.init:
			self.init = True
			#增加范围监测
			self.territoryControllerID = self.addProximity(10, 0, 0)
		result = False
		self.life = self.life - 0.1
		ERROR_MSG("trap life:%f"%(self.life))
		if self.life <= 0:
			result = True
		if self.tmpB and self.territoryControllerID > 0:
			#用bool值做简化判定，是否有数据需要处理，如果有，遍历增加到标准数组内
			self.tmpB = False
			for e in self.tmpTrap:
				self.trapEntity.append(e)
			self.tmpTrap = None
		if result == True:
			#生命周期结束或者次数满足后去除范围监控
			ERROR_MSG("trap nums:%i"%(len(self.trapEntity)))
			self.trapEntity = None
			if self.territoryControllerID > 0:
				self.cancelController(self.territoryControllerID)
				self.territoryControllerID = 0
			if self.timerID > 0:
				self.delTimer(self.timerID)
				self.timerID = 0
			#删除自己
			self.destroy()
			return
		GameObject.onTimer(self, tid, userArg)

	#暂时还是默认使用系统的方形算法来确认敌人是否在范围内
	def onEnterTrap(self, entityEntering, range_xz, range_y, controllerID, userarg):
		"""
		KBEngine method.
		有entity进入trap
		"""
		#暂时没有判定是什么类型的entity，到时候需要增加判定
		#放到最上方判定，为了处理临时数据方便
		if entityEntering.isDestroyed or not self.isEnemy(entityEntering):
			return
		#or entityEntering.getScriptName() != "Avatar"
		if self.territoryControllerID == 0 and controllerID != 0:
			ERROR_MSG("on enter trap:%i, %i, %s"%(controllerID, self.territoryControllerID, entityEntering.getScriptName()))
			self.tmpB = True
			self.tmpTrap.append(entityEntering)
		if controllerID != self.territoryControllerID:
			return

		ERROR_MSG("%s::onEnterTrap: %i entityEntering=(%s)%i, range_xz=%s, range_y=%s, controllerID=%i, userarg=%i" % \
						(self.getScriptName(), self.id, entityEntering.getScriptName(), entityEntering.id, \
						range_xz, range_y, controllerID, userarg))
		self.trapEntity.append(entityEntering)

	def onLeaveTrap(self, entityLeaving, range_xz, range_y, controllerID, userarg):
		"""
		KBEngine method.
		有entity离开trap
		"""
		if entityLeaving.isDestroyed or not self.isEnemy(entityEntering):
			return
		if self.territoryControllerID == 0 and controllerID != 0:
			ERROR_MSG("on leave trap:%i, %i"%(controllerID, self.territoryControllerID))
			self.tmpB = True
			self.tmpTrap.remove(entityLeaving)
		if controllerID != self.territoryControllerID:
			return
		ERROR_MSG("%s::onLeaveTrap: %i entityLeaving=(%s)%i." % (self.getScriptName(), self.id, \
				entityLeaving.getScriptName(), entityLeaving.id))
		self.trapEntity.remove(entityEntering)


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

from django.contrib import admin
from app import models

# Register your models here.
def register_admin(model):
    """Turn admin.site.register into a decorator."""
    def wrapper(klass):
        admin.site.register(model, klass)
        return klass
    return wrapper

@admin.register(models.journal_submission)
class JournalSubmissionAdmin(admin.ModelAdmin):
    list_display = ('user','created')
    list_filter = ('created',)
    search_fields = ['user']

@admin.register(models.embed)
class EmbedAdmin(admin.ModelAdmin):
    list_display = ('summary','url','source','message')
    list_filter = ('source',)
    search_fields = ['summary']

@admin.register(models.question)
class QuestionAdmin(admin.ModelAdmin):
    list_display = ('question','category')
    list_filter = ('category',)
    search_fields = ['question']


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

from flask import Blueprint, redirect, url_for, render_template, request
from auth import admin_required
from apps.tenancy.admin.forms import TenancyInfoForm, TenancyForm
from apps.tenancy.models import TenancyInfo, Tenancy
from google.appengine.ext import blobstore
from apps.utils.blobstore import get_uploads
import os
from apps.file.models import File

mod = Blueprint(
    'tenancy.admin',
    __name__,
    template_folder='templates',
    url_prefix='/admin/services/tenancy'
)

@mod.route('/', methods=['GET', 'POST'], endpoint='index')
@admin_required
def index():
    tenancy_info = TenancyInfo.get_master_db()
    form = TenancyInfoForm(obj=tenancy_info)
    if request.method == 'POST' and form.validate_on_submit():
        form.populate_obj(tenancy_info)
        tenancy_info.put()
        return redirect(url_for('tenancy.admin.index'))
    return render_template(
        'tenancy/admin/index.html',
        index_active='active',
        form=form
    )

@mod.route('/tenancy/', methods=['GET'])
@admin_required
def tenancy():
    tenancies = Tenancy.query()
    return render_template(
        'tenancy/admin/tenancy.html',
        tenancy_active='active',
        tenancies=tenancies
    )

@mod.route('/tenancy/add/', methods=['GET', 'POST'], endpoint='add')
@admin_required
def tenancy_add():
    form = TenancyForm()
    url = blobstore.create_upload_url(
        url_for('tenancy.admin.add')
    )
    if request.method == 'POST':
        upload_files = get_uploads(request, 'attach_file')
        file_ = None
        if len(upload_files):
            blob_info = upload_files[0]
        else:
            blob_info = None

        if form.validate_on_submit():
            if blob_info:
                blob_info = blobstore.BlobInfo.get(blob_info.key())
                if blob_info.size:
                    file_ = File.create(
                        blob_key=blob_info.key(),
                        title=form.name.data,
                        description=form.description.data,
                        is_public=form.is_public.data,
                        filename=os.path.basename(blob_info.filename.replace('\\', '/')),
                        size=blob_info.size,
                        content_type=blob_info.content_type)
                    file_.put()
                else:
                    blob_info.delete()

        tenancy = Tenancy()
        form.populate_obj(tenancy)
        if file_:
            tenancy.file = file_.key
        tenancy.put()
        return redirect(url_for('tenancy.admin.tenancy'))

    tenancies = Tenancy.query()
    return render_template(
        'tenancy/admin/add.html',
        add_active='active',
        form=form,
        tenancies=tenancies,
        url=url
    )

@mod.route('/tenancy/<int:key_id>/', methods=['GET', 'POST'], endpoint='edit')
@admin_required
def tenancy_edit(key_id):
    tenancy = Tenancy.retrieve_by_id(key_id)
    if not tenancy:
        return redirect(url_for('tenancy.admin.tenancy'))
    if request.method == 'POST' and 'delete_tenancy' in request.form:
        tenancy.key.delete()
        return redirect(url_for('tenancy.admin.tenancy'))
    url = blobstore.create_upload_url(
        url_for('tenancy.admin.edit', key_id=key_id)
    )
    form = TenancyForm(obj=tenancy)
    if request.method == 'POST':
        upload_files = get_uploads(request, 'attach_file')
        file_ = None
        if len(upload_files):
            blob_info = upload_files[0]
        else:
            blob_info = None

        if form.validate_on_submit():
            if blob_info:
                blob_info = blobstore.BlobInfo.get(blob_info.key())
                if blob_info.size:
                    file_ = File.create(
                        blob_key=blob_info.key(),
                        title=form.name.data,
                        description=form.description.data,
                        is_public=form.is_public.data,
                        filename=os.path.basename(blob_info.filename.replace('\\', '/')),
                        size=blob_info.size,
                        content_type=blob_info.content_type)
                    file_.put()
                else:
                    blob_info.delete()

        form.populate_obj(tenancy)
        if file_:
            if tenancy.file:
                tenancy.file.delete()
            tenancy.file = file_.key
        tenancy.put()
        return redirect(url_for('tenancy.admin.tenancy'))

    return render_template(
        'tenancy/admin/tenancy_edit.html',
        tenancy=tenancy,
        form=form,
        url=url
    )


#第 0004 题： 任一个英文的纯文本文件，统计其中的单词出现的个数
# Author : weijiansun
# -*-coding:utf-8-*-

import collections
import re
import sys

def count(filename = 'test.txt'):
    file=open(filename,'r')
    data=file.read()
    dic=collections.defaultdict(lambda:0)
    data =re.sub(r'[\W\d]',' ',data)
    datalist=data.split(' ')
    for item in datalist:
        dic[item]+=1
    del dic['']
    return dic

if __name__ =="__main__":
    print(sorted(count().items()))


import argparse
import os

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils as vutils
from torch.autograd import Variable
from tensorboardX import SummaryWriter
from tqdm import tqdm

from model import CapsulesNet
from data import Data

def one_hot_encode(target, length):
    batch_size = target.size(0)
    one_hot_vec = torch.zeros((batch_size, length))
    for i in range(batch_size):
        one_hot_vec[i, target[i]] = 1.0

    return one_hot_vec

def main(args):
    # Set logger
    writer = SummaryWriter(log_dir=args.log_dir)

    # DATA
    data = Data(args)
    # Embed and visualize
    data.embed(writer)
    # Load data loader
    train_loader, test_loader = data.load()
    n_train_batches = len(train_loader)
    n_test_batches = len(test_loader)

    # MODEL
    model = CapsulesNet(args.n_conv_in_channel, args.n_conv_out_channel,
                        args.n_primary_unit, args.primary_unit_size,
                        args.n_classes, args.output_unit_size,
                        args.n_routing, args.regularization_scale,
                        args.input_width, args.input_height,
                        args.use_cuda)

    if args.use_cuda:
        print('[INFO] Using {} GPU(s)'.format(torch.cuda.device_count()))
        model.cuda()

    # Info
    print(model)

    # Optimizer
    optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)

    # TRAINING
    # Train helper
    def train(epoch, model):
        # Switch model to train mode
        model.train()

        for i, (data, target) in enumerate(tqdm(train_loader, unit='batch')):
            # One-hot encode for labels
            target_one_hot = one_hot_encode(target, args.n_classes)

            # Wrap inputs into Variable
            data, target = Variable(data), Variable(target_one_hot)
            if args.use_cuda:
                data = data.cuda()
                target = target.cuda()

            # Forward
            optimizer.zero_grad()
            output = model(data)

            # Calculate loss
            loss, margin_loss, recon_loss = model.loss(data, output, target)

            # Backward
            loss.backward()
            optimizer.step()

            # Tensorboard log
            global_step = (epoch-1) * n_train_batches + i
            writer.add_scalar('train/total_loss', loss.data[0], global_step)
            writer.add_scalar('train/margin_loss' , margin_loss.data[0], global_step)
            writer.add_scalar('train/reconstruction_loss', recon_loss.data[0], global_step)

            # STDOUT log
            if (i+1) % args.log_interval == 0:
                template = "[Epoch {}/{}] " \
                           "[Batch {}/{}] " \
                           "Total loss: {:.6f}, Margin loss: {:.6f}, Reconstruction loss: {:.6f}"
                tqdm.write(template.format(epoch, args.epochs,
                                           i+1, n_train_batches,
                                           loss.data[0], margin_loss.data[0], recon_loss.data[0]))

    # Test helper
    def test(epoch, model):
        # Switch model to evaluate mode
        model.eval()

        loss, margin_loss, recon_loss = 0., 0., 0.
        correct = 0.

        for data, target in tqdm(test_loader):
            target_indices = target

            # One-hot encode for labels
            target_one_hot = one_hot_encode(target, args.n_classes)

            # Wrap inputs into Variable
            data, target = Variable(data, volatile=True), Variable(target_one_hot)
            if args.use_cuda:
                data = data.cuda()
                target = target.cuda()

            # Forward
            output = model(data)

            # Calculate loss, and sum up
            t_loss, m_loss, r_loss = model.loss(data, output, target,
                                                 size_average=False)
            loss += t_loss.data[0]
            margin_loss += m_loss.data[0]
            recon_loss += r_loss.data[0]

            # Count number of correct prediction
            # v_magnitude shape: [batch_size, 10, 1, 1]
            v_magnitude = torch.sqrt((output**2).sum(dim=2, keepdim=True))
            # pred shape: [batch_size, 1, 1, 1]
            pred = v_magnitude.data.max(1, keepdim=True)[1].cpu()
            correct += pred.eq(target_indices.view_as(pred)).sum()

        # Tensorboard log
        loss /= n_test_batches
        margin_loss /= n_test_batches
        recon_loss /= n_test_batches
        accuracy = correct / len(test_loader.dataset)

        global_step = epoch * n_train_batches
        writer.add_scalar('test/total_loss', loss, global_step)
        writer.add_scalar('test/margin_loss', margin_loss, global_step)
        writer.add_scalar('test/recon_loss', recon_loss, global_step)
        writer.add_scalar('test/accuracy', accuracy, global_step)

        # IMAGES RECONSTRUCTION
        if epoch % args.recon_interval == 0:
            reconstruction = model.decoder(output, target)
            # Resize to batch of images [batch_size, C, H, W]
            recon_imgs = reconstruction.view(-1, args.n_conv_in_channel,
                                             args.input_height, args.input_width)
            # Visualize in Tensorboard
            recon_grid = vutils.make_grid(recon_imgs.data,
                                          normalize=True, scale_each=True)
            original_grid = vutils.make_grid(data.data,
                                             normalize=True, scale_each=True)
            writer.add_image('test/original_{}_{}'.format(epoch, global_step),
                             original_grid, global_step)
            writer.add_image('test/reconstruction_{}_{}'.format(epoch, global_step),
                             recon_grid, global_step)

        # STDOUT log
        template = """[Test {}]
        Total loss: {:.6f}, Margin loss: {:.6f}, Reconstruction loss: {:.6f}
        Accuracy: {:.4f}%
        """
        tqdm.write(template.format(epoch,
                                   loss, margin_loss, recon_loss,
                                   accuracy * 100))

    def checkpoint(epoch, parameters):
        """Helper for saving model's parameters
        """
        if not os.path.exists(args.model_dir):
            os.mkdir(args.model_dir)
        model_path = os.path.join(args.model_dir,
                                  'epoch_{}.pth'.format(epoch))
        torch.save(parameters, model_path)
        print('[INFO] Checkpoint {} for epoch {}'.format(model_path, epoch))

    # Start training
    for epoch in range(1, args.epochs+1):
        train(epoch, model)
        test(epoch, model)

        if epoch % args.save_interval == 0:
            checkpoint(epoch, model.state_dict())

    writer.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('--epochs', type=int, default=25)
    parser.add_argument('--learning_rate', type=float, default=0.01)
    parser.add_argument('--batch_size', type=int, default=128)

    parser.add_argument('--n_conv_in_channel', type=int, default=1)
    parser.add_argument('--n_conv_out_channel', type=int, default=256)
    parser.add_argument('--n_primary_unit', type=int, default=8)
    parser.add_argument('--primary_unit_size', type=int, default=1152)
    parser.add_argument('--n_classes', type=int, default=10)
    parser.add_argument('--output_unit_size', type=int, default=16)
    parser.add_argument('--n_routing', type=int, default=3)
    parser.add_argument('--regularization_scale', type=float, default=0.0005)
    parser.add_argument('--input_height', type=int, default=28)
    parser.add_argument('--input_width', type=int, default=28)

    parser.add_argument('--no_cuda', action='store_true', default=False)
    parser.add_argument('--log_interval', type=int, default=10)
    parser.add_argument('--save_interval', type=int, default=5)
    parser.add_argument('--recon_interval', type=int, default=5)

    parser.add_argument('--log_dir', type=str, default='logs')
    parser.add_argument('--model_dir', type=str, default='models')

    args = parser.parse_args()
    args.use_cuda = (not args.no_cuda) and torch.cuda.is_available()

    print(args)
    main(args)


#!/usr/bin/env python3

# https://codeforces.com/problemset/problem/1136/B
# 三类move: 取(=n), 仍(=n+1), 移(n-1+min(k-1,n-k))

def f(l):
    n,k = l
    return 3*n + min(k-1,n-k)

l = list(map(int,input().split()))
print(f(l))


from flask import (
    current_app as app,
    url_for,
    render_template,
    redirect,
    request
)
from .forms import CalcularForm
from .calculos import calculo_juros_compostos
from .plotly_wrapper import create_plot_calculos
import pandas as pd

@app.route("/", methods=['GET', 'POST'])
def calcular():
    calcularForm = CalcularForm()

    if calcularForm.validate_on_submit():
        montante_inicial = calcularForm.montante_inicial.data
        aportes_mensais = calcularForm.aportes_mensais.data
        taxa_mensal = calcularForm.taxa_mensal.data
        tempo_meses = calcularForm.tempo_meses.data

        return redirect(url_for('resultado', montante=montante_inicial,aportes=aportes_mensais, taxa=taxa_mensal, tempo=tempo_meses))
    return render_template(
        'index.html',
        form=calcularForm
    )

@app.route("/resultado")

def resultado():
    capital_mensal = calculo_juros_compostos(
        montante_inicial=float(request.args['montante']),
        aportes_mensais=float(request.args['aportes']),
        taxa_mensal=float(request.args['taxa']),
        tempo_meses=int(request.args['tempo'])
    )
    plot = create_plot_calculos(round(capital_mensal, 2))
    return render_template(
        "resultado.html",
        montante_inicial=round(float(request.args['montante']), 2),
        capital_final=round(capital_mensal['Capital'].iloc[-1], 2),
        juros_acumulados=round(capital_mensal['Juros Acumulados'].iloc[-1], 2),
        total_aportado=round(capital_mensal['Valor Aportado'].iloc[-1], 2),
        plot=plot
    )

@app.route("/favicon.ico")
def favicon():
    return app.send_static_file('favicon.ico')


import unittest, sys
sys.path.extend(['.','..','../..','py'])

import h2o, h2o_cmd, h2o_import as h2i, h2o_browse as h2b
from h2o_test import find_file, dump_json, verboseprint

class Basic(unittest.TestCase):
    def tearDown(self):
        h2o.check_sandbox_for_errors()

    @classmethod
    def setUpClass(cls):
        h2o.init()

    @classmethod
    def tearDownClass(cls):
        h2o.tear_down_cloud()

    def test_simple2(self):
        # h2o-dev doesn't take ../.. type paths? make find_file return absolute path
        a_node = h2o.nodes[0]

        # import_result = a_node.import_files(path=find_file("smalldata/logreg/prostate.csv"))
        import_result = a_node.import_files(path=find_file("smalldata/poker/poker-hand-testing.data"))
        # print dump_json(import_result)

        k = import_result['keys'][0]
        # frames_result = a_node.frames(key=k[0], len=5)

        frames_result = a_node.frames(key=k)

        frame = frames_result['frames'][0]
        byteSize = frame['byteSize']
        rows = frame['rows']
        columns = frame['columns']
        for c in columns:
            label = c['label']
            missing = c['missing']
            stype = c['type']
            zeros = c['zeros']
            domain = c['domain']

        # print dump_json(frame)

        # how do you parse multiple files
        parse_result = a_node.parse(key=k)

        frame = parse_result['frames'][0]
        hex_key = frame['key']['name']

        verboseprint(hex_key, ":", dump_json(parse_result))

if __name__ == '__main__':
    h2o.unit_main()


from PyQt5 import QtWidgets

class Settings(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.initUI()

    def initUI(self):

        vbox = QtWidgets.QVBoxLayout()

        wrap_vbox = QtWidgets.QVBoxLayout()
        lbl = QtWidgets.QLabel('test lbl for db2')
        wrap_vbox.addWidget(lbl)

        # Возвращаем в основной макет
        self.out_window = wrap_vbox


import redis

class RedisClient(object):
    """
    Redis客户端
    """
    _CLIENT = None

    @classmethod
    def get_client(cls):
        """
        获取客户端
        :return:
        """
        if cls._CLIENT:
            return cls._CLIENT

        pool = redis.ConnectionPool(host='localhost', port=6379, db=0)

        cls._CLIENT = redis.StrictRedis(connection_pool=pool)
        return cls._CLIENT


# -*- coding: utf-8 -*-
from openprocurement.api.utils.common import get_now

from datetime import timedelta
from copy import deepcopy

test_organization = {
    "name": u"Державне управління справами",
    "identifier": {
        "scheme": u"UA-EDR",
        "id": u"00037256",
        "uri": u"http://www.dus.gov.ua/"
    },
    "address": {
        "countryName": u"Україна",
        "postalCode": u"01220",
        "region": u"м. Київ",
        "locality": u"м. Київ",
        "streetAddress": u"вул. Банкова, 11, корпус 1"
    },
    "contactPoint": {
        "name": u"Державне управління справами",
        "telephone": u"0440000000"
    }
}
test_procuringEntity = test_organization.copy()
swiftsure_procuring_entity = deepcopy(test_procuringEntity)
swiftsure_procuring_entity.update({
    "additionalContactPoints": [
        {
            "name": u"Державне управління справами",
            "telephone": u"0440000000"
        }
    ]
})

contract_create_data = {
    "awardID": "376d560b2b2d452a80543865f3cab43e",
    "contractID": "a930574bf8cd405cb7f9c9ed4ca68061",
    "contractType": "ceasefire",
    "dateSigned": get_now().isoformat(),
    "merchandisingObject": "a930574bf8cd999cb7f9c9ed4ca68061",
    "period": {
        "startDate": get_now().isoformat(),
        "endDate": (get_now() + timedelta(days=30)).isoformat(),
    },
    "procuringEntity": swiftsure_procuring_entity,
    "title": "Test Contract",
    "suppliers": [test_organization],
    "value": {
     "currency": "UAH",
     "amount": 500.0,
     "valueAddedTaxIncluded": True
    },
    "items": [
        {
            "description": u"Земля для військовослужбовців",
            "classification": {
                "scheme": u"CPV",
                "id": u"66113000-5",
                "description": u"Земельні ділянки"
            },
            "unit": {
                "name": u"item",
                "code": u"44617100-9"
            },
            "quantity": 5,
            "registrationDetails": {
                "status": "unknown",
            },
            "address": {
                "countryName": u"Україна",
                "postalCode": "79000",
                "region": u"м. Київ",
                "locality": u"м. Київ",
                "streetAddress": u"вул. Банкова 1"
            }
        }
    ]
}


__author__ = 'xiangyuzhang'
__author__ = 'xiangyuzhang'
from subprocess import call
import os

# create waiting list

raw_file_vector = ["c432-vector.log", "c499-vector.log", "c880-vector.log", "c1355-vector.log", "c1908-vector.log", "c2670-vector.log", "c3540-vector.log"
                 , "c5315-.log", "c7552-vector.log"]

# create output name
out_filename = ['c432', 'c499', 'c880', 'c1355', 'c1908', 'c2670', 'c3540', 'c5315', 'c7552']
out_frame_vector = "_Corrupt_Random_incre_vector.eps"
out_frame_iteration = "_Corrupt_Random_incre_vector.eps"

content = []
k = 0
z = 2
# use loop

for i in out_filename:
    sub = "'" + raw_file_vector[k] + "'"
    line_1_vector = "set output " + "'" + i + out_frame_vector + "'" +'\n'
    line_7_vector = "plot "  + "'corrupt_vector.dat'" + " using 1:" + str(z) + " " + "title 'Corrupt' w lp pt 0 ps 1 lc -1 lw 2, "+ sub + " using 1:($2+$3)/2:($2-$3)/2 notitle w errorbars linestyle 1, " + sub + " using 1:4 title 'Random AVR' w linespoints pt 0 ps 1 lc -1 lw 2\n"

    with open("sample", 'r') as infile: # here to get sample list
        income = infile.read()
        sample_lines = income.split('\n')

    content.append(sample_lines[0] + '\n')
    content.append(line_1_vector)
    content.append(sample_lines[2] + '\n')
    content.append(sample_lines[3] + '\n')
    content.append(sample_lines[4] + '\n')
    content.append(sample_lines[5] + '\n')
    content.append("set grid y\n")
    content.append("set yrange [0.1:10000]\n")
    content.append("set xrange [0:201]\n")

    content.append(sample_lines[6] + '\n')
    content.append(line_7_vector)

    for j in content:
        with open(("plot_script_" + i),'a') as outfile:
            outfile.write(j)

    Cmmd = 'gnuplot plot_script_' + i
    Proc = call(Cmmd, shell = True)

    # os.remove('plot_script')
    k = k + 1
    z = z + 1
    content = []
# call subprocess


from room import Room
from player import Player
from items.item import Item
# Declare all the rooms

room = {
    'outside':  Room("Outside Cave Entrance",
                     """North of you, the cave mount beckons"""),

    'foyer':    Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),

    'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),

    'narrow':   Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),

    'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}

# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

#
# Main
#

# Make a new player object that is currently in the 'outside' room.

# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.

directions = ['n','e','w','s']
starting_room = room['outside']
player = Player("Trabin", room['outside'])

current_room = player.current_room

print(f"q to quit, use n,e,w,s for directions")

while True:

    print(player.current_room.name)
    print(player.current_room.description)

    user_input = input(f"{player.name} What would you like to do? ")

    if user_input == 'n':
        if player.current_room.n_to:
            player.current_room = player.current_room.n_to
        else:
            print("This isn't an exit. Please input again")
    if user_input == 'e':
        if player.current_room.e_to:
            player.current_room = player.current_room.e_to
        else:
            print("This isn't an exit. Please input again")
    if user_input == 'w':
        if player.current_room.w_to:
            player.current_room = player.current_room.w_to
        else:
            print("This isn't an exit. Please input again")
    if user_input == 's':
        if player.current_room.s_to:
            player.current_room = player.current_room.s_to
        else:
            print("This isn't an exit. Please input again")

    if user_input == 'get' or user_input == 'take':
        if len(current_room.items) > 0:
            for i in current_room.items:
                if user_input[i] == i.name:
                    player.bag.append(i)
                    print(f"{i.name} Collected. It has been safely placed in your bag!")
                else:
                    print('This item appears to be vacant. Search again, or check your bag.')

    if user_input == 'q':
        print(f"Thanks for playing, {player.name}!")
        exit(0)


"""UI Coverage for a CFME/MIQ Appliance

Usage
-----

``py.test --ui-coverage``

General Notes
-------------
simplecov can merge test results, but doesn't appear to like working in a
multi-process environment. Specifically, it clobbers its own results when running
simultaneously in multiple processes. To solve this, each process records its
output to its own directory (configured in coverage_hook). All of the
individual process' results are then manually merged (coverage_merger) into one
big json result, and handed back to simplecov which generates the compiled html
(for humans) and rcov (for jenkins) reports.

thing_toucher makes a best-effort pass at requiring all of the ruby files in
the rails root, as well as any external MIQ libs/utils outside of the rails
root (../lib and ../lib/util). This makes sure files that are never
required still show up in the coverage report.

Workflow Overview
-----------------

Pre-testing (``pytest_configure`` hook):

1. Add ``Gemfile.dev.rb`` to the rails root, then run bundler to install simplecov
   and its dependencies.
2. Install and require the coverage hook (copy ``coverage_hook`` to config/, add
   require line to the end of ``config/boot.rb``)
3. Restart EVM (Rudely) to start running coverage on the appliance processes:
   ``killall -9 ruby; service evmserverd start``
4. TOUCH ALL THE THINGS (run ``thing_toucher.rb`` with the rails runner).
   Fork this process off and come back to it later

Post-testing (``pytest_unconfigure`` hook):

1. Poll ``thing_toucher`` to make sure it completed; block if needed.
2. Stop EVM, but nicely this time so the coverage atexit hooks run:
   ``service evmserverd stop``
3. Run ``coverage_merger.rb`` with the rails runner, which compiles all the individual process
   reports and runs coverage again, additionally creating an rcov report
4. Pull the coverage dir back for parsing and archiving
5. For fun: Read the results from ``coverage/.last_run.json`` and print it to the test terminal/log

Post-testing (e.g. ci environment):
1. Use the generated rcov report with the ruby stats plugin to get a coverage graph
2. Zip up and archive the entire coverage dir for review

"""
import json
import os
from glob import glob

from py.error import ENOENT
from py.path import local

from fixtures.pytest_store import store
from utils.log import logger
from utils.path import log_path, scripts_data_path

# paths to all of the coverage-related files

# on the appliance
#: Corresponds to Rails.root in the rails env
rails_root = local('/var/www/miq/vmdb')
#: coverage root, should match what's in the coverage hook and merger scripts
appliance_coverage_root = rails_root.join('coverage')

# local
coverage_data = scripts_data_path.join('coverage')
gemfile = coverage_data.join('Gemfile.dev.rb')
coverage_hook = coverage_data.join('coverage_hook.rb')
coverage_merger = coverage_data.join('coverage_merger.rb')
thing_toucher = coverage_data.join('thing_toucher.rb')
coverage_output_dir = log_path.join('coverage')

def _thing_toucher_mp_handler(ssh_client):
    # for use in a subprocess to kick off the thing toucher
    x, out = ssh_client.run_rails_command('thing_toucher.rb')
    return x

def clean_coverage_dir():
    try:
        coverage_output_dir.remove(ignore_errors=True)
    except ENOENT:
        pass
    coverage_output_dir.ensure(dir=True)

class UiCoveragePlugin(object):
    def pytest_configure(self, config):
        if store.parallelizer_role != 'master':
            store.current_appliance.install_coverage()

        if store.parallelizer_role != 'slave':
            clean_coverage_dir()

    def pytest_sessionfinish(self, exitstatus):
        # Now master/standalone needs to move all the reports to an appliance for the source report
        if store.parallelizer_role != 'slave':
            store.terminalreporter.write_sep('-', 'collecting coverage reports')
        else:
            store.slave_manager.message('collecting coverage reports')

        if store.parallelizer_role != 'master':
            store.current_appliance.collect_coverage_reports()

        # for slaves, everything is done at this point
        if store.parallelizer_role == 'slave':
            return

        # The rest should be only happening in the master/sandalone process
        results_tgzs = glob(coverage_output_dir.join('*-coverage-results.tgz').strpath)
        if not results_tgzs:
            # Not sure if we should explode here or not.
            logger.error('No coverage results collected')
            store.terminalreporter.write_sep('=', 'No coverage results found', red=True)
            return

        # push the results to the appliance
        ssh_client = store.current_appliance.ssh_client()
        for results_tgz in results_tgzs:
            dest_file = appliance_coverage_root.join(os.path.basename(results_tgz)).strpath
            ssh_client.put_file(results_tgz, dest_file)
            ssh_client.run_command('tar xvaf {} -C /var/www/miq/vmdb/coverage'.format(dest_file))

        # run the merger on the appliance to generate the simplecov report
        store.terminalreporter.write_sep('-', 'merging coverage reports')
        ssh_client.put_file(coverage_merger.strpath, rails_root.strpath)
        ssh_client.run_rails_command(coverage_merger.basename)

        # Now bring the report back and write out the info
        # TODO: We're already using tar, might as well tar this up, too.
        ssh_client.get_file(
            appliance_coverage_root.join('merged').strpath,
            coverage_output_dir.strpath,
            recursive=True
        )

    def pytest_unconfigure(self, config):
        try:
            last_run = json.load(log_path.join('coverage', 'merged', '.last_run.json').open())
            coverage = last_run['result']['covered_percent']
            # TODO: We don't currently know what a "good" coverage number is.
            style = {'bold': True}
            if coverage > 40:
                style['green'] = True
            else:
                style['red'] = True
            store.terminalreporter.line('UI Coverage Result: {}%'.format(coverage), **style)
        except KeyboardInterrupt:
            # don't block this, so users can cancel out
            raise
        except Exception as ex:
            logger.error('Error printing coverage report to terminal')
            logger.exception(ex)

def pytest_addoption(parser):
    group = parser.getgroup('cfme')
    group.addoption('--ui-coverage', dest='ui_coverage', action='store_true', default=False,
        help="Enable setup and collection of ui coverage on an appliance")

def pytest_cmdline_main(config):
    # Only register the plugin worker if ui coverage is enabled
    if config.option.ui_coverage:
        config.pluginmanager.register(UiCoveragePlugin(), name="ui-coverage")


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import datetime
from dateutil import rrule

from django.http import JsonResponse, Http404
from django.template.defaultfilters import slugify
from django.views.generic import DetailView

from cms.views import details
from publisher.views import PublisherDetailView
from .models import Event, EventPackage
from .settings import EVENT_TYPES

BATCH_DELTA = 3  # How many batches to show before + after current batch

# Translations from dateinput formatting to Python formatting
DATEFORMAT_XLATE = [
    (re.compile(pattern), replacement) for (pattern, replacement) in (
        ('dddd', '%A'),
        ('ddd', '%a'),
        ('dd', '%d'),
        ('!%d', '%e'),  # Will include a leading space for 1-9
        ('mmmm', '%B'),
        ('mmm', '%b'),
        ('mm', '%m'),
        ('!%m', '%m'),  # Will include leading zero
        ('yyyy', '%Y'),
        ('yy', '%y'),
    )
]

def dateformat_xlate(dateformat):
    for regexp, replacement in DATEFORMAT_XLATE:
        dateformat = regexp.sub(replacement, dateformat)
    return dateformat

def calculate_occurrences(data):
    # TODO: Return error on failure
    occurrences = []

    date_format = dateformat_xlate(data['format'])
    start_date = datetime.datetime(int(data['year']),
                                   int(data['month']),
                                   int(data['day']))
    rule = rrule.rrulestr(data['rrule'], dtstart=start_date)
    iterator = iter(rule)

    if 'batch_size' in data:
        batch_size = int(data['batch_size'])
    else:
        batch_size = 10

    if 'start' in data:
        start = int(data['start'])
    else:
        start = 0

    cur_batch = start // batch_size
    start = cur_batch * batch_size  # Avoid stupid start-values

    if hasattr(rule, '_exdate'):
        exdates = sorted(rule._exdate)
    else:
        exdates = []

    # Loop through the start first dates, to skip them:
    i = 0
    occurrences = []
    while True:
        try:
            # Get a date
            date = iterator.next()
        except StopIteration:
            # No more dates
            break
        while exdates and date > exdates[0]:
            # There are exdates that appear before this date:
            if i < start:
                # Skip them
                exdates.pop(0)
                i += 1
            else:
                # include them
                exdate = exdates.pop(0)
                occurrences.append({'date': exdate.strftime('%Y%m%dT%H%M%S'),
                                    'formattedDate': exdate.strftime(date_format),
                                    'type': 'exdate', })
                i += 1

        if i >= batch_size + start:
            break  # We are done!

        i += 1
        if i <= start:
            # We are still iterating up to the first event, so skip this:
            continue

        # Add it to the results
        if date in getattr(rule, '_rdate', []):
            occurrence_type = 'rdate'
        elif date == start_date:
            occurrence_type = 'start'
        else:
            occurrence_type = 'rrule'
        occurrences.append({'date': date.strftime('%Y%m%dT%H%M%S'),
                            'formattedDate': date.strftime(date_format),
                            'type': occurrence_type, })

    while exdates:
        # There are exdates that are after the end of the recurrence.
        # Excluding the last dates make no sense, as you can change the
        # range instead, but we need to support it anyway.
        exdate = exdates.pop(0)
        occurrences.append({'date': exdate.strftime('%Y%m%dT%H%M%S'),
                            'formattedDate': exdate.strftime(date_format),
                            'type': 'exdate', })

    # Calculate no of occurrences, but only to a max of three times
    # the batch size. This will support infinite recurrence in a
    # useable way, as there will always be more batches.
    first_batch = max(0, cur_batch - BATCH_DELTA)
    last_batch = max(BATCH_DELTA * 2, cur_batch + BATCH_DELTA)
    maxcount = (batch_size * last_batch) - start

    num_occurrences = 0
    while True:
        try:
            iterator.next()
            num_occurrences += 1
        except StopIteration:
            break
        if num_occurrences >= maxcount:
            break

    # Total number of occurrences:
    num_occurrences += batch_size + start

    max_batch = (num_occurrences - 1) // batch_size
    if last_batch > max_batch:
        last_batch = max_batch
        first_batch = max(0, max_batch - (BATCH_DELTA * 2))

    batches = [((x * batch_size) + 1, (x + 1) * batch_size) for x in range(first_batch, last_batch + 1)]
    batch_data = {'start': start,
                  'end': num_occurrences,
                  'batch_size': batch_size,
                  'batches': batches,
                  'currentBatch': cur_batch - first_batch,
                  }

    return {'occurrences': occurrences, 'batch': batch_data}

def get_occurrences(request):
    """
    Adapted from the test_server.py of https://github.com/collective/jquery.recurrenceinput.js
    """
    data = {}

    for x in ('year', 'month', 'day', 'rrule', 'format', 'start',):
        data[x] = request.GET.get(x, None)

    if None in data.values():
        return JsonResponse({'error': True, 'message': "'year', 'month', 'day', 'rrule', and 'format' are required."})

    result = calculate_occurrences(data)
    return JsonResponse(result)

class EventDetailView(PublisherDetailView):
    template_name = 'happenings/detail/default.html'
    extra_context = {}
    preview = False
    model = Event
    event_types = EVENT_TYPES

    def get_queryset(self):
        qs = super(EventDetailView, self).get_queryset()
        types_filter = [x[0] for x in self.event_types]
        qs = qs.filter(event_type__in=types_filter)
        return qs

    def dispatch(self, request, *args, **kwargs):
        """
        Intercept the request and route to a CMS page if it exists, otherwise
        use the standard detail handling
        """
        try:
            return details(request, request.path.lstrip('/').rstrip('/'))
        except Http404:
            pass
        return super(EventDetailView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(EventDetailView, self).get_context_data(**kwargs)
        context.update(self.extra_context)

        if self.object.is_archived():
            self.template_name = 'happenings/404.html'
        elif self.object.event_type == 'current exhibition' and self.object.end_date() < datetime.datetime.today():
            self.template_name = 'happenings/detail/past-exhibition.html'
        elif self.object.parent is not None:
            self.template_name = 'happenings/detail/child.html'
        elif self.object.child_events.all():
            self.template_name = 'happenings/detail/parent.html'
        else:
            self.template_name = 'happenings/detail/%s.html' % slugify(self.object.event_type)

        return context

class PackageDetailView(DetailView):
    queryset = EventPackage.objects.all()
    template_name = 'happenings/detail/package.html'


from xai.brain.wordbase.verbs._soften import _SOFTEN

#calss header
class _SOFTENS(_SOFTEN, ):
	def __init__(self,):
		_SOFTEN.__init__(self)
		self.name = "SOFTENS"
		self.specie = 'verbs'
		self.basic = "soften"
		self.jsondata = {}