def learnCorrect(word, suggestion, wordCount, wordDeletes, flag=True):
    """This function acts as a reward and punishment mechanism for the program's corrective abilities"""
    if suggestion is not None:
        # If reward and punishment
        if flag:
            if word == suggestion:
                if suggestion not in wordCount:
                    # Add word to dictionary. 74 is the first quartile of the non zero counts
                    wordCount[suggestion] = 74
                    if len(suggestion) > 1:
                        # Add to Deletes Dictionary
                        for i in xrange(0, len(suggestion)):
                            suggestionDelete = suggestion[:i] + suggestion[i + 1:]
                            if suggestionDelete in wordDeletes:
                                wordDeletes[suggestionDelete].append(suggestion)
                            else:
                                wordDeletes[suggestionDelete] = [suggestion]
                # Increase count by plus 10
                wordCount[suggestion] += 10
            elif word != suggestion and word is not None:
                # This is true reward for proper correction
                if suggestion in wordCount:
                    wordCount[suggestion] += 10
                if word in wordCount:
                    # Punishment by less 20
                    wordCount[word] -= 20
        else:
            # Punish unwanted word so that it may not appear again
            if suggestion in wordCount:
                wordCount[suggestion] -= 10
            # Add to dictionary
            if word is not None and word is not "":
                if word not in wordCount:
                    # Add with count first quartile 74
                    wordCount[word] = 74
                    if len(word) > 1:
                        # Add to Deletes Dictionary
                        for i in xrange(0, len(word)):
                            wordDelete = word[:i] + word[i + 1:]
                            if wordDelete in wordDeletes:
                                wordDeletes[wordDelete].append(word)
                            else:
                                wordDeletes[wordDelete] = [word]
                # Increase count by plus 10
                wordCount[word] += 10

def learnConjecture(suggestion, ipStream, dict2gram, dict3gram, dict4gram, dict5gram, wordCount):
    """This function acts as a reward mechanism only for the program's predictive abilities"""

    word1, word2, word3, word4 = ipStream
    words = [word1, word2, word3, word4, suggestion]

    def learn2(words, dict2gram, wordCount):
        """This closure takes two words and updates the 2-gram dictionary"""
        try:
            dict2gram[words[0]][words[1]] += 10
        except:
            if words[0] in wordCount and words[1] in wordCount:
                try:
                    dict2gram[words[0]] = dict()
                    dict2gram[words[0]][words[1]] = 10
                except:
                    pass

    def learn3(words, dict3gram, wordCount):
        """This closure takes three words and updates the 3-gram dictionary"""
        try:
            dict3gram[words[0]][words[1]][words[2]] += 10
        except:
            if words[0] in wordCount and words[1] in wordCount and words[2] in wordCount:
                try:
                    dict3gram[words[0]][words[1]] = dict()
                    dict3gram[words[0]][words[1]][words[2]] = 10
                except:
                    try:
                        dict3gram[words[0]] = dict()
                        dict3gram[words[0]][words[1]] = dict()
                        dict3gram[words[0]][words[1]][words[2]] = 10
                    except:
                        pass

    def learn4(words, dict4gram, wordCount):
        """This closure takes four words and updates the 4-gram dictionary"""
        try:
            dict4gram[words[0]][words[1]][words[2]][words[3]] += 10
        except:
            if words[0] in wordCount and words[1] in wordCount and words[2] in wordCount and words[3] in wordCount:
                try:
                    dict4gram[words[0]][words[1]][words[2]] = dict()
                    dict4gram[words[0]][words[1]][words[2]][words[3]] = 10
                except:
                    try:
                        dict4gram[words[0]][words[1]] = dict()
                        dict4gram[words[0]][words[1]][words[2]] = dict()
                        dict4gram[words[0]][words[1]][words[2]][words[3]] = 10
                    except:
                        try:
                            dict4gram[words[0]] = dict()
                            dict4gram[words[0]][words[1]] = dict()
                            dict4gram[words[0]][words[1]][words[2]] = dict()
                            dict4gram[words[0]][words[1]][words[2]][words[3]] = 10
                        except:
                            pass

    def learn5(words, dict5gram, wordCount):
        """This closure takes five words and updates the 5-gram dictionary"""
        try:
            dict5gram[word1][words[1]][words[2]][words[3]][words[4]] += 10
        except:
            if words[0] in wordCount and words[1] in wordCount and words[2] in wordCount and words[3] in wordCount and \
                            words[4] in wordCount:
                try:
                    dict5gram[words[0]][words[1]][words[2]][words[3]] = dict()
                    dict5gram[words[0]][words[1]][words[2]][words[3]][words[4]] = 10
                except:
                    try:
                        dict5gram[words[0]][words[1]][words[2]] = dict()
                        dict5gram[words[0]][words[1]][words[2]][words[3]] = dict()
                        dict5gram[words[0]][words[1]][words[2]][words[3]][words[4]] = 10
                    except:
                        try:
                            dict5gram[words[0]][words[1]] = dict()
                            dict5gram[words[0]][words[1]][words[2]] = dict()
                            dict5gram[words[0]][words[1]][words[2]][words[3]] = dict()
                            dict5gram[words[0]][words[1]][words[2]][words[3]][words[4]] = 10
                        except:
                            try:
                                dict5gram[words[0]] = dict()
                                dict5gram[words[0]][words[1]] = dict()
                                dict5gram[words[0]][words[1]][words[2]] = dict()
                                dict5gram[words[0]][words[1]][words[2]][words[3]] = dict()
                                dict5gram[words[0]][words[1]][words[2]][words[3]][words[4]] = 10
                            except:
                                pass

    if suggestion is not None:
        # If all four recent words are available and valid, try to update 5gram dictionary for that word sequence.
        if word1 is not None:
            learn5(words[0:], dict5gram, wordCount)
            learn4(words[1:], dict4gram, wordCount)
            learn3(words[2:], dict3gram, wordCount)
            learn2(words[3:], dict2gram, wordCount)
        # If only one word is available, try to update 2gram dictionary for that word sequence.
        elif word3 is None:
            learn2(words[3:], dict2gram, wordCount)
        # If only two recent words are available, try to update up to 3gram dictionary for that word sequence.
        elif word2 is None:
            learn2(words[3:], dict2gram, wordCount)
            learn3(words[2:], dict3gram, wordCount)
        # If only three recent words are available, try to update 4gram dictionary for that word sequence.
        elif word1 is None:
            learn2(words[3:], dict2gram, wordCount)
            learn3(words[2:], dict3gram, wordCount)
            learn4(words[1:], dict4gram, wordCount)


from django.shortcuts import render,redirect
import importlib
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from superadmin.utils import  table_filter,table_sort,table_search
# Create your views here.
from superadmin import superadmin
from superadmin.forms import create_model_form
def index(request):
    return render(request, "superadmin/table_index.html",{'table_list':superadmin.enabled_admins})

def display_table_objs(request,app_name,table_name):

    print("-->",app_name,table_name)
    #models_module = importlib.import_module('%s.models' %(app_name))
    #model_obj = getattr(models_module,table_name)
    admin_class = superadmin.enabled_admins[app_name][table_name]

    object_list,filter_condtions = table_filter(request,admin_class) #过滤后的结果

    object_list = table_search(request,admin_class,object_list)

    object_list, orderby_key = table_sort(request, admin_class, object_list)  # 排序后的结果
    print("orderby key ", orderby_key)
    paginator = Paginator(object_list, admin_class.list_per_page)  # Show 25 contacts per page

    page = request.GET.get('page')
    try:
        query_sets = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        query_sets = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        query_sets = paginator.page(paginator.num_pages)

    return render(request, "superadmin/table_objs.html", {"admin_class": admin_class,
                                                          "query_sets": query_sets,
                                                          "filter_condtions": filter_condtions,
                                                          "orderby_key": orderby_key,
                                                          "previous_orderby": request.GET.get("o", ''),
                                                          "search_text": request.GET.get('_q', '')})

def table_obj_add(request, app_name, table_name):
    admin_class = superadmin.enabled_admins[app_name][table_name]
    model_form_class = create_model_form(request, admin_class)

    if request.method == "POST":
        form_obj = model_form_class(request.POST)  #
        if form_obj.is_valid():
            form_obj.save()
            return redirect(request.path.replace("/add/", "/"))
    else:
        form_obj = model_form_class()

    return render(request, "superadmin/table_obj_add.html", {"form_obj": form_obj})

def table_obj_change(request, app_name, table_name, obj_id):
    admin_class = superadmin.enabled_admins[app_name][table_name]
    model_form_class = create_model_form(request, admin_class)

    obj = admin_class.model.objects.get(id=obj_id)
    if request.method == "POST":
        form_obj = model_form_class(request.POST, instance=obj)  # 更新
        if form_obj.is_valid():
            form_obj.save()
    else:

        form_obj = model_form_class(instance=obj)

    return render(request, "superadmin/table_obj_change.html", {"form_obj": form_obj})


#!/usr/bin/env python3
# coding: UTF-8

import threading
import datetime
import argparse
import pathlib
import logging
import signal
import codecs
import cowsay
import zmq
import sys

from uuid import uuid4

# Configuration file management : eccoin.conf

from configure import loadConfigurationECC

# eccPacket & cryptoNode  classes

from eccpacket    import eccPacket
from cryptonode   import cryptoNode, eccoinNode, cryptoNodeException

################################################################################
## RepeatTimer class ###########################################################
################################################################################

class RepeatTimer(threading.Timer):

    def run(self):

        while not self.finished.wait(self.interval):

            self.function(*self.args, **self.kwargs)

################################################################################
## EchoApp class ###############################################################
################################################################################

class EchoApp:

	def __init__(self, protocol, name, prefix, debug=False):

		self.protocol_id	= protocol
		self.protocol_ver	= 1
		self.name			= name
		self.prefix			= prefix
		self.debug			= debug
		self.subscribers	= []
		self.coins			= []
		self.running		= True
		self.timer          = 0

	############################################################################

	def send_ecc_packet(self, dest, meth, data):

		ecc_packet = eccPacket(self.protocol_id, self.protocol_ver, dest, self.coins[0].routingTag, meth, data)

		if self.debug:

			logging.info('TX: {}'.format(ecc_packet.to_json()))

		ecc_packet.send(self.coins[0])

	############################################################################

	def process_ecc_packet(self, ecc_packet):

		# Ensure we have a route back to whoever is sending an ecchat message

		self.coins[0].setup_route(ecc_packet.get_from())

		if ecc_packet.get_meth() == eccPacket.METH_chatMsg:

			data = ecc_packet.get_data()

			# send the chatAck message

			ackData = {'uuid' : data['uuid'],
					   'cmmd' : data['cmmd'],
					   'able' : True}

			self.send_ecc_packet(ecc_packet.get_from(), eccPacket.METH_chatAck, ackData)

			reply = []

			if data['text'].startswith('#BALANCE'):

				reply.append("Balance = {:f}".format(self.coins[0].get_balance()))

			elif data['text'].startswith('#STOP!!!'):

				reply.append("ececho stopping ...")

				self.running = False

			elif data['text'].startswith('"') and data['text'].endswith('"'):

				reply = cowsay.get_output_string('cow', data['text'][1:-1]).splitlines()

			else:

				reply.append(self.prefix + data['text'])

			# echo back the reply text as a new chatMsg

			for line in reply:

				echData = {'uuid' : str(uuid4()),
						   'cmmd' : 'add',
						   'text' : line}

				self.send_ecc_packet(ecc_packet.get_from(), eccPacket.METH_chatMsg, echData)

		elif ecc_packet.get_meth() == eccPacket.METH_addrReq:

			data = ecc_packet.get_data()

			if data['coin'] == self.coins[0].symbol:

				address = self.coins[0].get_new_address()

				rData = {'uuid' : data['uuid'],
						 'coin' : data['coin'],
						 'addr' : address}

				self.send_ecc_packet(ecc_packet.get_from(), eccPacket.METH_addrRes, rData)

			else:

				rData = {'uuid' : data['uuid'],
						 'coin' : data['coin'],
						 'addr' : '0'}

				self.send_ecc_packet(ecc_packet.get_from(), eccPacket.METH_addrRes, rData)

		else:

			pass

	############################################################################

	def zmqInitialise(self):

		self.context = zmq.Context()

		for index, coin in enumerate(self.coins):

			self.subscribers.append(self.context.socket(zmq.SUB))

			if coin.zmqAddress:

				self.subscribers[index].connect(coin.zmqAddress)
				self.subscribers[index].setsockopt(zmq.SUBSCRIBE, b'')

	############################################################################

	def zmqHandler(self, index):

		[address, contents] = self.subscribers[index].recv_multipart()

		if address.decode() == 'packet':

			protocolID = contents.decode()[1:]

			eccbuffer = self.coins[0].get_buffer(int(protocolID))

			if eccbuffer:

				for packet in eccbuffer.values():

					message = codecs.decode(packet, 'hex').decode()

					if self.debug:

						logging.info('RX: {}'.format(message))

					ecc_packet = eccPacket.from_json(message)

					self.process_ecc_packet(ecc_packet)

	############################################################################

	def zmqShutdown(self):

		for subscriber in self.subscribers:

			subscriber.close()

		self.context.term()

	############################################################################

	def reset_buffer_timeout(self):

		self.coins[0].reset_buffer_timeout()

	############################################################################

	def cryptoInitialise(self):

		if loadConfigurationECC(self.coins, self.protocol_id):

			for coin in self.coins:

				try:

					coin.initialise()

				except cryptoNodeException as error:

					print(str(error))

					return False

				self.timer = RepeatTimer(10, self.reset_buffer_timeout)

				self.timer.start()

			return True

		return False

	############################################################################

	def cryptoShutdown(self):

		if self.timer:

			self.timer.cancel()

		for coin in self.coins:

			coin.shutdown()

	############################################################################

	def run(self):

		if self.cryptoInitialise():

			self.zmqInitialise()

			while self.running:

				self.zmqHandler(0)

			self.zmqShutdown()

		self.cryptoShutdown()

################################################################################

def terminate(signalNumber, frame):

	logging.info('%s received - terminating' % signal.Signals(signalNumber).name)

	sys.exit()

################################################################################
### Main program ###############################################################
################################################################################

def main():

	if sys.version_info[0] < 3:

		raise 'Use Python 3'

	pathlib.Path('log').mkdir(parents=True, exist_ok=True)

	logging.basicConfig(filename = 'log/ececho-{:%Y-%m-%d}.log'.format(datetime.datetime.now()),
						filemode = 'a',
						level    = logging.INFO,
						format   = '%(asctime)s - %(levelname)s : %(message)s',
						datefmt  = '%d/%m/%Y %H:%M:%S')

	logging.info('STARTUP')

	signal.signal(signal.SIGINT,  terminate)  # keyboard interrupt ^C
	signal.signal(signal.SIGTERM, terminate)  # kill [default -15]

	argparser = argparse.ArgumentParser(description='Echo service for ecchat')

	argparser.add_argument('-p', '--protocol', action='store'     , help='Protocol ID'      , type=int, default=1       , required=False)
	argparser.add_argument('-n', '--name'    , action='store'     , help='nickname'         , type=str, default='ececho', required=False)
	argparser.add_argument('-x', '--prefix'  , action='store'     , help='reply prefix'     , type=str, default='> '    , required=False)
	argparser.add_argument('-d', '--debug'   , action='store_true', help='debug message log',                             required=False)

	command_line_args = argparser.parse_args()

	logging.info('Arguments %s', vars(command_line_args))

	app = EchoApp(command_line_args.protocol,
	              command_line_args.name,
	              command_line_args.prefix,
	              command_line_args.debug)

	app.run()

	logging.info('SHUTDOWN')

################################################################################

if __name__ == '__main__':

	main()

################################################################################


import unittest
from LocalMinArray import *

class TestLocalMinArray(unittest.TestCase):

    def test_random1(self):
        a = [3, 4, 15, 100, 16, 8, 20, 10, 2, 6, 7, 12]
        r = findLocMin2(a, 0, len(a)-1)
        if r > 0:
            self.assertLess(a[r], a[r-1], msg="smaller than left")
        if r < len(a)-1:
            self.assertLess(a[r], a[r+1], msg="smaller than right")

    def test_increase(self):
        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        r = findLocMin2(a, 0, len(a)-1 )
        self.assertEqual(r, 0, msg="should detect at index 0")

    def test_decrease(self):
        a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        r = findLocMin2(a, 0, len(a)-1)
        self.assertEqual(r, len(a)-1, msg="should detect at index end")

if __name__ == '__main__':
    #
    # to run verbose option
    #   python3 test.py -v

    # to run each module
    #   python3 -m unittest test.TestLocalMinArray -v
    unittest.main()


#!/usr/bin/env python

"""
@package ion_functions.test.generic_functions
@file ion_functions/test/generic_functions.py
@author Christopher Mueller
@brief Unit tests for generic_functions module
"""

from nose.plugins.attrib import attr
from ion_functions.test.base_test import BaseUnitTestCase

import numpy as np
from ion_functions.data import generic_functions as gfunc

@attr('UNIT', group='func')
class TestGenericFunctionsUnit(BaseUnitTestCase):

    def test_magnetic_declination(self):
        """
        Test magnetic_declination function.

        Some values based on those defined in the WMM document,
        WMM2010testvalues.pdf which accompanies the software.  Others
        were created and checked using online calculators.

        Implemented by Stuart Pearce, April 2013
        """

        lat = np.array([45.0, 45.0, 80.0, 0.0, -80.0, 80.0, 0.0, -80.0])
        lon = np.array([-128.0, -128.0, 0.0, 120.0,
                        240.0, 0.0, 120.0, 240.0])
        z = np.array([0.0, 1000.0, 0.0, 0.0,
                      0.0, 100000.0, 100000.0, 100000.0])
        timestamp = np.array([3575053740.7382507,  # 2013-04-15 22:29:00
                              3575053740.7382507,  # UTC
                              3471292800.0,        # 2010-01-01 UTC
                              3471292800.0,
                              3471292800.0,
                              3471292800.0,
                              3471292800.0,
                              3471292800.0])
        zflag = np.array([-1, -1, -1, -1, -1, 1, 1, 1])
        output = []
        for ii in range(len(lat)):
            out_ = gfunc.magnetic_declination(lat[ii],lon[ii],
                                              timestamp[ii],z[ii],zflag[ii])
            output.append(out_)
        output = np.array(output)

        check_values = np.array([16.46093044096720,
                                 16.46376239313584,
                                 -6.13,
                                 0.97,
                                 70.21,
                                 -6.57,
                                 0.94,
                                 69.62])
        self.assertTrue(np.allclose(output, check_values,
                                    rtol=0, atol=1e-2))

    def test_ntp_to_unix_time(self):
        """
        Test ntp_to_unix_time function.

        Timestamp Values gathered from various internet sources
        including the NTP FAQ and HOWTO.

        Implemented by Stuart Pearce, April 2013
        """
        ntp_timestamps = np.array([3176736750.7358608,
                                   3359763506.2082224,
                                   3575049755.4380851])

        output = gfunc.ntp_to_unix_time(ntp_timestamps)

        check_values = np.array([967747950.735861,
                                 1150774706.2082224,
                                 1366060955.438085])
        self.assertTrue(np.allclose(output, check_values,
                                    rtol=0, atol=1e-6))

    def test_extract_parameters(self):
        """
        Test extract_parameter function.

        Array values created by author.

        Implemented by Christopher Wingard, April 2013
        """

        in_array = np.array([34, 67, 12, 15, 89, 100, 54, 36])
        self.assertTrue(np.equal(34, gfunc.extract_parameter(in_array, 0)))
        self.assertTrue(np.equal(67, gfunc.extract_parameter(in_array, 1)))
        self.assertTrue(np.equal(12, gfunc.extract_parameter(in_array, 2)))
        self.assertTrue(np.equal(15, gfunc.extract_parameter(in_array, 3)))
        self.assertTrue(np.equal(89, gfunc.extract_parameter(in_array, 4)))
        self.assertTrue(np.equal(100, gfunc.extract_parameter(in_array, 5)))
        self.assertTrue(np.equal(54, gfunc.extract_parameter(in_array, 6)))
        self.assertTrue(np.equal(36, gfunc.extract_parameter(in_array, 7)))


import pyttsx3
import  PyPDF2
book = open('oop.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(book)

pages = pdfReader.numPages
print(pages)
for num in range(8,pages):

    speaker = pyttsx3.init()
    pages = pdfReader.getPage(7)
    text = pages.extractText()
    speaker.say(text)
    speaker.runAndWait()


#!/bin/python3

import sys

n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]

number_of_swaps = 0
swapped = True

while swapped:
    swapped = False
    for i, number in enumerate(a):
        if i == len(a) - 1:
            break
        if a[i] > a[i+1]:
            a[i], a[i+1] = a[i+1], a[i]
            number_of_swaps += 1
            swapped = True

print("Array is sorted in {} swaps.".format(number_of_swaps))
print("First Element: {}".format(a[0]))
print("Last Element: {}".format(a[-1]))


# -*- coding: utf-8 -*-
"""Created on Wed Feb 13 22:39:37 2019
@author: shravan
"""
import numpy as np
import random
import math
import matplotlib.pyplot as plt
def regression(n,alpha,trainx,trainy,testx,testy,power,mod):
    minerror,bestn,bestiter=10000,0,0
    allw=list()
    trainerror=list()
    testerror=list()
    for i in range(1,n): # for n 1 to 9
        vecx=[[trainx[k]**j for j in range(i+1)] for k in range(len(trainx))] # creating power of x dependin upon n
        vectestx=[[testx[k]**j for j in range(i+1)] for k in range(len(testx))]# same as above for test data
        w=[random.uniform(0,1) for j in range(i+1)] #random weights initially
        count=len(trainx)
        tempw=[None]*(i+1)
        it,epsilon,error0,error=0,1,0,0
        while(epsilon>0.00005 and it <100):#either iteration more than 100 or epsilon value
            for j in range(i+1): #for different theta(w) value do GDescent
                if(mod==False):# whether to use absolute value cost function
                    delw=power*sum([((np.dot(w,vecx[k])-trainy[k])**(power-1))*(1 if j==0 else vecx[k][j]) for k in range(len(trainx))])/(2*float(count))
                else:# finding the derivative of mod funciton each element of summunation will be evaluated for derivation
                    delw=sum([vecx[k][j] if w[j]> ((np.dot(w,vecx[k])-w[j]*vecx[k][j]-trainy[k])/float(vecx[k][j])) else (-vecx[k][j]) for k in range(len(trainx))])
                tempw[j]=w[j]-alpha*delw
                #print("new delta w{0} :{1} ".format(j,tempw[j]))
            w=list(tempw)   #copying temporary thetas value to original weights(thetas) for another iteration
            error=sum([(np.dot(w,vecx[k])-trainy[k])**power for k in range(len(trainx))])/(2*float(count))
            epsilon=abs(error0-error)
            error0=error
            it+=1
            #print("error in n={0} iteration={1} is={2}:".format(i,it,error))
        allw.append(w)
        trainerror.append(error)
        testerror.append(sum([(np.dot(w,vectestx[k])-testy[k])**power for k in range(len(testx))])/(2*float(len(testx))))
        if(error<minerror):
            minerror=error
            bestn=i
            bestiter=it
    print("overall min Train error {0} when n ={1} and iteration={2}".format(minerror,bestn,bestiter))
    print("Min test error:",testerror[bestn-1])
    return bestn,allw,trainerror,testerror
n=10 # power of x till where we want the polynomial to be evaluated
mm=[10,100,1000,10000] #number of example
mmtrerr=[]
mmtsterr=[]
for j,m in enumerate(mm):
    random.seed(123)
    x=[random.uniform(0,1) for i in range(m)]
    y=[math.sin(x[i]) for i in range(m)]
    mu,sigma=0,0.3
    noise=np.random.normal(mu,sigma,m)
    y=y+noise
    trainx=x[0:int(.8*m)]
    testx=x[int(.8*m):m]
    trainy=y[0:int(.8*m)]
    testy=y[int(.8*m):m]
    bestn,allw,trainerror,testerror=regression(n,0.05,trainx,trainy,testx,testy,2,False)
    mmtrerr.append(trainerror[bestn-1])
    mmtsterr.append(testerror[bestn-1])

f, ax=plt.subplots()
ax.set_xlabel("Size of data")
ax.set_ylabel("error")
ax.set_title('Error for different m(10,100,1000,10000')
ax.set_title("Train(green) and Test(red) error for n=(1,...,9)")

#ax.set_xticks(mm)
#ax.set_xticklabels(mm)
ax.semilogx(mm, mmtrerr, 'go',mm,mmtsterr,'rs')
plt.subplots_adjust(hspace=0.9,wspace=0.4)
plt.savefig("figure3.png",dpi=600)


import re
import json

question_list = []

def Question_Filled(question):
    if not question["Number"]:
        return False
    if not question["Question"]:
        return False
    if not question["A"]:
        return False
    if not question["B"]:
        return False
    if not question["C"]:
        return False
    if not question["D"]:
        return False
    return True

def Blank_Question():
    question = {
        "Number": 1,
        "Question" : "",
        "A" : "",
        "B" : "",
        "C" : "",
        "D" : "",
        "Answer": ""
    }
    return question

def Add_Question(question):
    question_list.append(question)

def main():
    question_number = 1
    question_pattern = r"Question\s[\d]+\:\s([\S\s]+\?)"
    answer_pattern = r"([\w]+)\.\s+([\S\s]+)\."

    question = Blank_Question()

    with open(r"c:/Code/GTBootCampMain/04-Web-APIs/02-Homework/Assets/Questions.txt", encoding="utf8") as questions:
        while True:
            line = questions.readline()
            if not line:
                break
            if line.rstrip():
                match = re.search(question_pattern, line)
                if match:
                    question["Number"] = question_number
                    question_number += 1
                    question["Question"] = match.group(1)

                match = re.search(answer_pattern, line)
                if match:
                    question[match.group(1)]  = match.group(2)

                if Question_Filled(question):
                    Add_Question(question)
                    question = Blank_Question()

    question_number = 0
    with open(r"c:/Code/GTBootCampMain/04-Web-APIs/02-Homework/Assets/Answers.txt", encoding="utf8") as answers:
        while True:
            line = answers.readline()
            if not line:
                break
            if line.rstrip():
                match = re.search(answer_pattern, line)
                if match:
                    question_list[question_number]["Answer"] = match.group(1)
                    question_number += 1

    f = open(r"c:/Code/GTBootCampMain/04-Web-APIs/02-Homework/Assets/Questions.json", "w")
    f.write(json.dumps(question_list))
    f.close()

if(__name__) == "__main__":
    main()


"""
Create a test database (sqlite) for pytest
"""

import os
from contextlib import contextmanager

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from battleground.schema import Base

if os.name == "posix":
    TMPDIR = "/tmp"
else:
    TMPDIR = "%TMP%"

TMPDB = os.path.join(TMPDIR, "plarktest.db")

testengine = create_engine("sqlite:///{}".format(TMPDB))

Base.metadata.create_all(testengine)
Base.metadata.bind = testengine

def remove_test_db():
    """
    Remove the sqlite file for the test database
    """
    if os.path.exists(TMPDB):
        os.remove(TMPDB)

@contextmanager
def test_session_scope():
    """Provide a transactional scope around a series of operations."""
    db_session = sessionmaker(bind=testengine)
    testsession = db_session()
    try:
        yield testsession
        testsession.commit()
    except Exception:
        testsession.rollback()
        raise
    finally:
        testsession.close()


# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
import logging
import struct

from iotdb.utils.Field import Field

# for package
from iotdb.utils.IoTDBConstants import TSDataType
from iotdb.utils.IoTDBRpcDataSet import IoTDBRpcDataSet
from iotdb.utils.RowRecord import RowRecord

import pandas as pd

logger = logging.getLogger("IoTDB")

class SessionDataSet(object):
    def __init__(
        self,
        sql,
        column_name_list,
        column_type_list,
        column_name_index,
        query_id,
        client,
        statement_id,
        session_id,
        query_data_set,
        ignore_timestamp,
    ):
        self.iotdb_rpc_data_set = IoTDBRpcDataSet(
            sql,
            column_name_list,
            column_type_list,
            column_name_index,
            ignore_timestamp,
            query_id,
            client,
            statement_id,
            session_id,
            query_data_set,
            1024,
        )

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close_operation_handle()

    def get_fetch_size(self):
        return self.iotdb_rpc_data_set.get_fetch_size()

    def set_fetch_size(self, fetch_size):
        self.iotdb_rpc_data_set.set_fetch_size(fetch_size)

    def get_column_names(self):
        return self.iotdb_rpc_data_set.get_column_names()

    def get_column_types(self):
        return self.iotdb_rpc_data_set.get_column_types()

    def has_next(self):
        return self.iotdb_rpc_data_set.next()

    def next(self):
        if not self.iotdb_rpc_data_set.get_has_cached_record():
            if not self.has_next():
                return None
        self.iotdb_rpc_data_set.has_cached_record = False
        return self.construct_row_record_from_value_array()

    def construct_row_record_from_value_array(self):
        out_fields = []
        for i in range(self.iotdb_rpc_data_set.get_column_size()):
            index = i + 1
            data_set_column_index = i + IoTDBRpcDataSet.START_INDEX
            if self.iotdb_rpc_data_set.get_ignore_timestamp():
                index -= 1
                data_set_column_index -= 1
            column_name = self.iotdb_rpc_data_set.get_column_names()[index]
            location = (
                self.iotdb_rpc_data_set.get_column_ordinal_dict()[column_name]
                - IoTDBRpcDataSet.START_INDEX
            )

            if not self.iotdb_rpc_data_set.is_null_by_index(data_set_column_index):
                value_bytes = self.iotdb_rpc_data_set.get_values()[location]
                data_type = self.iotdb_rpc_data_set.get_column_type_deduplicated_list()[
                    location
                ]
                field = Field(data_type)
                if data_type == TSDataType.BOOLEAN:
                    value = struct.unpack(">?", value_bytes)[0]
                    field.set_bool_value(value)
                elif data_type == TSDataType.INT32:
                    value = struct.unpack(">i", value_bytes)[0]
                    field.set_int_value(value)
                elif data_type == TSDataType.INT64:
                    value = struct.unpack(">q", value_bytes)[0]
                    field.set_long_value(value)
                elif data_type == TSDataType.FLOAT:
                    value = struct.unpack(">f", value_bytes)[0]
                    field.set_float_value(value)
                elif data_type == TSDataType.DOUBLE:
                    value = struct.unpack(">d", value_bytes)[0]
                    field.set_double_value(value)
                elif data_type == TSDataType.TEXT:
                    field.set_binary_value(value_bytes)
                else:
                    raise RuntimeError("unsupported data type {}.".format(data_type))
            else:
                field = Field(None)
            out_fields.append(field)

        return RowRecord(
            struct.unpack(">q", self.iotdb_rpc_data_set.get_time_bytes())[0], out_fields
        )

    def close_operation_handle(self):
        self.iotdb_rpc_data_set.close()

    def todf(self):
        return resultset_to_pandas(self)

def resultset_to_pandas(result_set: SessionDataSet) -> pd.DataFrame:
    """
    Transforms a SessionDataSet from IoTDB to a Pandas Data Frame
    Each Field from IoTDB is a column in Pandas
    :param result_set:
    :return:
    """
    return result_set.iotdb_rpc_data_set.resultset_to_pandas()

def get_typed_point(field: Field, none_value=None):
    choices = {
        # In Case of Boolean, cast to 0 / 1
        TSDataType.BOOLEAN: lambda field: 1 if field.get_bool_value() else 0,
        TSDataType.TEXT: lambda field: field.get_string_value(),
        TSDataType.FLOAT: lambda field: field.get_float_value(),
        TSDataType.INT32: lambda field: field.get_int_value(),
        TSDataType.DOUBLE: lambda field: field.get_double_value(),
        TSDataType.INT64: lambda field: field.get_long_value(),
    }

    result_next_type: TSDataType = field.get_data_type()

    if result_next_type in choices.keys():
        return choices.get(result_next_type)(field)
    elif result_next_type is None:
        return none_value
    else:
        raise Exception(f"Unknown DataType {result_next_type}!")


import sys

LANGUAGE_ALIASES = [
    (u'en', u'english'),
    (u'es', u'spanish'),
    (u'de', u'german'),
]

LANGUAGE_NAMES_FROM_SHORT = dict(
    (short, (short, long_)) for (short, long_) in LANGUAGE_ALIASES
)

LANGUAGE_NAMES_FROM_LONG_ENGLISH = dict(
    (long_, (short, long_)) for (short, long_) in LANGUAGE_ALIASES
)

class LanguageAliases(object):
    """
    This class provides access to all of the aliases for a single language.
    """

    def __init__(self, short_name, long_english_name):
        self._short = short_name
        self._long_english = long_english_name

    @property
    def short_name(self):
        return self._short

    @property
    def long_english_name(self):
        return self._long_english

def new_lang_from_short_name(short_name):
    try:
        aliases = LANGUAGE_NAMES_FROM_SHORT[short_name.lower()]
    except KeyError:
        sys.stderr.write(
            "The language code '%s' is not supported." % short_name
        )
        raise KeyError

    return LanguageAliases(*aliases)

def new_lang_from_long_english_name(long_name):
    try:
        aliases = LANGUAGE_NAMES_FROM_LONG_ENGLISH[long_name.lower()]
    except KeyError:
        sys.stderr.write("The language '%s' is not supported." % long_name)
        raise KeyError

    return LanguageAliases(*aliases)


import time
from Bubot.Helpers.ExtException import ExtException, Unauthorized, AccessDenied
from Bubot.Helpers.Action import Action, async_action
from aiohttp_session import get_session
# from bubot.Helpers.Сryptography.SignedData import SignedData
from aiohttp import web
from Bubot.Core.BubotHelper import BubotHelper
from BubotObj.OcfDevice.subtype.WebServer.ApiHelper import WebResponse as Response
# from bubot.Catalog.Account.Account import Account
from BubotObj.User.User import User
import re
from bson.json_util import dumps, loads

class ApiHandler:
    clear = re.compile('[^a-zA-Z0-9._]')
    api_class_cache = {}

    def __init__(self, request):
        self.session = None
        # self.request = request
        self.storage = request.app['storage']
        self.app = request.app
        self.device = request.app['device']
        self.log = self.device.log

    async def prepare(self, request, device, obj_name, action, prefix, response_class):
        try:
            api_class = self.get_api_class(device, obj_name)(response_class)
        except Exception as err:
            raise ExtException('Handler not found', detail=f'{device}/{obj_name}', parent=err)
        api_action = f'{prefix}_{action}'
        self.session = await get_session(request)
        self.session['last_visit'] = time.time()
        try:
            task = getattr(api_class, api_action)
        except Exception as err:
            raise ExtException('Handler not found', detail=f'{device}/{obj_name}/{action}')
        return task(self)

    # async def get_json_data(self):
    #     data = await self.request.text()
    #     if not data:
    #         raise Exception('empty data')
    #     return loads(data)

    def get_api_class(self, device, obj_name):
        if obj_name:
            uid = f'{device}.{obj_name}'
        else:
            uid = device
        try:
            return self.api_class_cache[uid]
        except KeyError:
            pass
        if obj_name:
            try:
                api_class = BubotHelper.get_extension_class(obj_name, device, suffix='Api')
            except:
                api_class = BubotHelper.get_obj_class(obj_name, suffix='Api')
        else:
            api_class = BubotHelper.get_subtype_class('OcfDevice', device, suffix='Api')
        self.api_class_cache[uid] = api_class
        return api_class

    @async_action
    async def check_right(self, **kwargs):
        kwargs['account'] = kwargs['account'] if kwargs.get('account') else self.session['account']
        kwargs['user'] = self.session.get('user')
        if not kwargs['user']:
            raise Unauthorized()
        if not kwargs['account']:
            raise AccessDenied()
        kwargs['storage'] = self.storage
        return await User.check_right(**kwargs)

    @staticmethod
    async def loads_request_data(view):
        data = await view.request.text()
        return loads(data) if data else {}

    @staticmethod
    async def loads_json_request_data(view):
        if view.request.method == 'GET':
            return dict(view.request.query)
        else:
            return await view.loads_request_data(view)

class HttpHandler(web.View, ApiHandler):

    def __init__(self, request):
        web.View.__init__(self, request)
        ApiHandler.__init__(self, request)
        # self.storage = request.app['storage']
        # self.app = request.app
        # self.session = None
        # self.data = None
        self.lang = request.headers.get('accept-language')
        pass

    async def get(self):
        return await self.request_handler('api')

    async def post(self):
        async def www_form_decode():
            return dict(await self.request.post())
            pass

        async def json_decode():
            return await self.request.json()

        data_decoder = {
            'application/x-www-form-urlencoded': www_form_decode,
            'application/json': json_decode
        }
        data_type = self.request.headers.get('content-type')
        if data_type and data_type in data_decoder:
            self.data = await data_decoder[data_type]()

        return await self.request_handler('api')

    async def request_handler(self, prefix, **kwargs):
        _action = Action(name=f'{self.__class__.__name__}.request_handler')
        device = self.request.match_info.get('device')
        obj_name = self.request.match_info.get('obj_name')
        action = self.request.match_info.get('action')

        try:
            task = await self.prepare(self.request, device, obj_name, action, prefix, Response)
            response = _action.add_stat(await task)
            _action.set_end()
            response.headers['stat'] = dumps(_action.stat, ensure_ascii=True)
            return response
        except ExtException as err:
            return Response.json_response(ExtException(
                action=_action.name,
                dump={
                    "device": device,
                    "obj_name": obj_name,
                    "action": action
                },
                parent=err).to_dict(), status=err.http_code)
        except Exception as err:
            return Response.json_response(ExtException(action=_action.name, parent=err).to_dict(), status=500)

    async def notify(self, data):
        return


from django.contrib import admin
from django.urls import path
from webapp import views
urlpatterns = [
    path("", views.register, name='register'),
    path("login", views.loginuser, name='login'),
    path("logout", views.logoutuser, name='logout'),
    path("index",views.index,name='index'),
    path("uploadimg",views.uploadimg,name='uploadimg'),
    path("autosuggest",views.autosuggest,name='autosuggest'),

]


"""
Content Provider:       Thingiverse
ETL Process:            Use the API to identify all CC0 3D Models.
Output:                 TSV file containing the 3D models
                        their respective images and meta-data.
Notes:                  https://www.thingiverse.com/developers/getting-started
                        All API requests require authentication.
                        Rate limiting is 300 per 5 minute window.
"""
import argparse
import logging
import os
import json
from operator import itemgetter
from datetime import datetime, timedelta, timezone

import common.requester as requester
import common.storage.image as image_class

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

logger = logging.getLogger(__name__)

PER_PAGE_LIMIT = 30
IMAGES_LIMIT = 1000
DELAY = 1.0  # Time between each two consecutive requets
HOST = 'thingiverse.com'
ENDPOINT = f'https://api.{HOST}/newest'
PROVIDER = 'thingiverse'
LICENSE = 'cc0'
LICENSE_VERSION = '1.0'
LICENSE_TEXT = 'Creative Commons'
TOKEN = os.getenv('THINGIVERSE_API_KEY')
DEFAULT_QUERY_PARAMS = {
    'access_token': TOKEN,
}

delayed_requester = requester.DelayedRequester(DELAY)
image_store = image_class.ImageStore(provider=PROVIDER)

def main(date):
    """
    This script pulls the data for a given date from Thingiverse API
    and writes it into a .TSV file to be eventually read
    into our DB.
    Required Arguments:
    date:  Date String in the form YYYY-MM-DD.  This is the date for
           which running the script will pull data.
    """
    logger.info(f'Processing Thingiverse API for date: {date}')

    start_timestamp = _derive_timestamp_pair(date)

    cur_page = 1
    total_images = 0
    is_valid = True

    while is_valid and total_images < IMAGES_LIMIT:
        thing_batch = _get_things_batch(
            cur_page
        )
        total_images, is_valid = _process_thing_batch(
            thing_batch, total_images, start_timestamp)
        cur_page = cur_page + 1

    total_images = image_store.commit()
    logger.info(f'Total images: {total_images}')
    logging.info('Terminated!')

def _process_thing_batch(thing_batch, total_images, start_timestamp):
    is_valid = True
    if thing_batch is not None:
        thing_batch = list(thing_batch)
        batch_total_images = list(filter(None, list(map(lambda thing: _process_thing(
            str(thing), start_timestamp), thing_batch))))

        if '-1' in batch_total_images:
            is_valid = False
            batch_total_images = []

        total_images += sum(batch_total_images)

    return total_images, is_valid

def _derive_timestamp_pair(date):
    date_obj = datetime.strptime(date, '%Y-%m-%d')
    utc_date = date_obj.replace(tzinfo=timezone.utc)
    start_timestamp = str(int(utc_date.timestamp()))
    #end_timestamp = str(int((utc_date + timedelta(days=1)).timestamp()))
    return start_timestamp

def _get_things_batch(page=1, retries=5):
    query_params = _build_query_params(
        page
    )
    thing_batch = None
    response_json = _get_response_json_list(
        query_params=query_params, retries=retries)
    if response_json is not None:
        thing_batch = map(lambda thing: thing['id'], response_json)

    if 'batchcomplete' in response_json:
        logger.debug('Found batchcomplete')

    return thing_batch

def _build_query_params(
        page=1,
        default_query_params=DEFAULT_QUERY_PARAMS
):
    query_params = default_query_params.copy()
    query_params.update({'per_page': PER_PAGE_LIMIT})
    query_params.update({'page': page})

    return query_params

def _get_response_json_list(
    query_params,
    endpoint=ENDPOINT,
    retries=0
):
    response_json = None

    if retries < 0:
        logger.error('No retries remaining.  Failure.')
        raise Exception('Retries exceeded')

    response = delayed_requester.get(
        endpoint,
        params=query_params,
        timeout=60
    )
    if response is not None and response.status_code == 200:
        try:
            response_json = response.json()
        except Exception as e:
            logger.warning(f'Could not get response_json.\n{e}')
            response_json = None
    if response_json is None or (type(response_json) != list and response_json.get('error') is not None):
        logger.warning(f'Bad response_json:  {response_json}')
        logger.warning(
            'Retrying:\n_get_response_json(\n'
            f'    {endpoint},\n'
            f'    {query_params},\n'
            f'    retries={retries - 1}'
            ')'
        )
        response_json = _get_response_json_list(
            query_params,
            endpoint=endpoint,
            retries=retries - 1
        )

    return response_json

def _build_thing_query(thing, default_query_params=DEFAULT_QUERY_PARAMS):
    endpoint = f'https://api.thingiverse.com/things/{thing}'
    query_params = default_query_params.copy()
    return endpoint, query_params

def _validate_license(response_json):
    license_ = None
    license_version = None
    if not (('license' in response_json) and (
            LICENSE_TEXT.lower() in response_json['license'].lower())):
        logging.warning('license not detected')
    else:
        license_ = LICENSE
        license_version = LICENSE_VERSION

    return license_, license_version

def _create_meta_dict(
    thing_data
):
    meta_data = {
        'description': thing_data.get('description', ''),
        'title': thing_data.get('name', '')
    }

    return meta_data

def _build_foreign_landing_url(thing_data, thing):
    foreign_landing_url = None
    if 'public_url' in thing_data:
        foreign_landing_url = thing_data['public_url'].strip()
    else:
        foreign_landing_url = f'https://www.thingiverse.com/thing:{thing}'

    return foreign_landing_url

def _build_creator_data(thing_data):
    creator = None
    creator_url = None
    try:
        if ('first_name' in thing_data['creator']) and (
                'last_name' in thing_data['creator']):
            creator = f"{thing_data['creator']['first_name']} {thing_data['creator']['last_name']}"

        if (creator.strip() == '') and ('name' in thing_data['creator']):
            creator = thing_data['creator']['name']

        if 'public_url' in thing_data['creator']:
            creator_url = thing_data['creator']['public_url'].strip()

    except Exception as e:
        logger.warning(f'Could not find "creator" in "thing_data". \n {e}')

    return creator, creator_url

def _create_tags_list(thing):
    logging.info(f'Requesting tags for thing: {thing}')
    endpoint = f'https://api.thingiverse.com/things/{thing}/tags'
    tags = _get_response_json_list(DEFAULT_QUERY_PARAMS, endpoint, retries=5)
    tags_list = None
    if tags is not None:
        tags_list = list(map(lambda tag: {'name': str(
            tag['name'].strip()), 'provider': 'thingiverse'}, tags))
        tags_list.sort(key=itemgetter('name'))
    return tags_list

def _get_image_list_json(thing):
    endpoint = f'https://api.thingiverse.com/things/{thing}/files'
    image_list = _get_response_json_list(
        DEFAULT_QUERY_PARAMS, endpoint, retries=5)
    if image_list is None:
        logging.warning('Image Not Detected!')

    return image_list

def _get_image_url_thumbnail(images):
    thumbnail = None
    image_url = None
    for image_size in images:

        if str(image_size['type']).strip().lower() == 'display':

            if str(image_size['size']).lower() == 'medium':
                thumbnail = image_size['url'].strip()

            if str(image_size['size']).lower() == 'large':
                image_url = image_size['url'].strip()

            elif image_url is None:
                image_url = thumbnail

        else:
            continue

    return thumbnail, image_url

def _add_images(image_list,
                foreign_landing_url,
                license_,
                license_version,
                creator,
                creator_url,
                title,
                tags_list):
    total_images = 0
    for image in image_list:
        total_images = image_store.add_item(
            foreign_landing_url=foreign_landing_url,
            image_url=image[1],
            thumbnail_url=image[2],
            license_=license_,
            license_version=license_version,
            foreign_identifier=image[0],
            creator=creator,
            creator_url=creator_url,
            title=title,
            meta_data=image[3],
            raw_tags=tags_list,
            source='Thigniverse'
        )
    return total_images

def _process_image_list(image_list, description):
    images_data = []
    for image in image_list:
        meta_data = {}
        thumbnail = None
        image_url = None
        foreign_landing_id = None
        meta_data['description'] = description
        if ('default_image' in image) and image['default_image']:
            if 'url' in image['default_image']:
                meta_data['3d_model'] = image['default_image']['url']
                foreign_landing_id = str(image['default_image']['id'])
                images = image['default_image']['sizes']
                thumbnail, image_url = _get_image_url_thumbnail(images)
                if image_url is None:
                    logging.warning('Image Not Detected!')
                    continue

                images_data.append(
                    [
                        image_url if not foreign_landing_id else foreign_landing_id,
                        image_url,
                        thumbnail,
                        '\\N' if not meta_data else json.dumps(meta_data)
                    ]
                )
            else:
                logging.warning('3D Model Not Detected!')
                continue
        else:
            logging.warning('Image Not Detected!')

    return images_data

def _process_thing(thing, start_timestamp):
    endpoint, query_params = _build_thing_query(thing)
    license_ = None
    license_version = None
    creator = None
    creator_url = None
    foreign_landing_url = None
    total_images = 0
    total_images_list = []
    logging.info('Processing thing: {}'.format(thing))
    response_json = _get_response_json_list(query_params, endpoint, retries=5)

    if response_json is not None:
        modified_date = response_json.get('modified', '')
        if modified_date is not None:
            modified_date = modified_date.split('T')[0].strip()
            modified_date = _derive_timestamp_pair(modified_date)
            if modified_date >= start_timestamp:
                license_, license_version = _validate_license(response_json)
                meta_data = _create_meta_dict(response_json)
                foreign_landing_url = _build_foreign_landing_url(
                    response_json, thing)
                creator, creator_url = _build_creator_data(response_json)
                tags_list = _create_tags_list(str(thing))
                image_list = _get_image_list_json(thing)
                total_images_list = _process_image_list(
                    image_list, meta_data['description'])
                total_images = _add_images(total_images_list, foreign_landing_url, license_,
                                           license_version, creator, creator_url, meta_data['title'], tags_list)
            else:
                logging.warning('Modified Date Not Valid')
                total_images = '-1'
        else:
            logging.warning('Modified Date Not Found')
            total_images = '-1'
    else:
        logging.warning('Thing Not Found, response_json is None')
        total_images = '-1'

    return total_images

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Thingiverse API Job',
        add_help=True
    )
    parser.add_argument(
        '--date',
        help='Identify images uploaded on a date (format: YYYY-MM-DD).')
    args = parser.parse_args()
    if args.date:
        date = args.date
    else:
        date_obj = datetime.now() - timedelta(days=2)
        date = datetime.strftime(date_obj, '%Y-%m-%d')

    main(date)


class Item:
    """ Class for items in the game that can be interacted with """
    def __init__(self, name, location_id, description, is_moveable, is_wearable):
        self.name = name
        self.location_id = location_id
        self.description = description
        self.is_moveable = is_moveable
        self.is_wearable = is_wearable

    def to_seq(self):
        return ([
                self.name
                ,self.location_id
                ,self.description
                ,'T' if self.is_moveable else 'F'
                ,'T' if self.is_wearable else 'F'
                ])


class Solution:
    # @param A : list of list of integers
    # @return an integer
    def adjacent(self, A):
        A[0] = [max(A[0][i], A[1][i]) for i in range(len(A[0]))]
        inclusive = exclusive = 0
        for num in A[0]:
            new_inclusive = max(inclusive, exclusive + num)
            exclusive = max(exclusive, inclusive)
            inclusive = new_inclusive

        return max(inclusive, exclusive)


from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings
from lib.utilities import pymongo_query, format_query_output, get_log_window, format_query_input
from netshed.greylist.models import Greylist
import time

def index(request):
    """ GET request to mongoengine db queries """

    query = dict([(str(param), str(val).lower()) for param, val in request.GET.iteritems() if val])

    search_time = 0
    loglines = []
    db_results = ''
    if 'search' in query:
        if query['search'] == 'search':

            # generic pymongo query from utilities
            start = time.time()
            loglines = pymongo_query(query, 'greylist', settings.LOCAL)
            search_time = start - time.time()

        # greylist database search
        elif query['search'] == 'database query':
            del query['date']
            del query['search']

            start = time.time()
            db_results = Greylist.objects.filter(**format_query_input(query))
            search_time = start - time.time()

    dates = get_log_window('greylist', settings.LOCAL)
    return render_to_response('greylist/index.html', {'db_results': db_results, 'query': format_query_output(query), 'dates':dates, 'loglines':loglines, 'time':search_time})


class Solution(object):
    def isAnagram(self,s,t):
        count =0
        counter=0
        print (s,t)
        s_dict={}
        t_dict={}
        for letter in s:
            if letter in t:
                count +=1
                s_dict[letter] =s_dict.get(letter,0) +1
        for letter in t:
            if letter in s:
                t_dict[letter]=t_dict.get(letter,0)+1
        print (s_dict,t_dict)
        for each in s_dict:
            if each in t_dict:
                if t_dict[each]== s_dict[each]:
                    counter += s_dict[each]
        print (counter)

        if (len(s)==len(t)) and (count ==len(t) and counter==len(t)):
            return True
        else:
            return False

s=Solution
print(s.isAnagram( "anagram" ,"accc","caac"))


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

"""
***************************************************************************
    SagaAlgorithm213.py
    ---------------------
    Date                 : December 2014
    Copyright            : (C) 2014 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'December 2014'
__copyright__ = '(C) 2014, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os
from .SagaAlgorithm213 import SagaAlgorithm213
from processing.tools import dataobjects
from processing.tools.system import getTempFilenameInTempFolder

sessionExportedLayers = {}

class SagaAlgorithm214(SagaAlgorithm213):

    def getCopy(self):
        newone = SagaAlgorithm214(self.descriptionFile)
        newone.provider = self.provider
        return newone

    def exportRasterLayer(self, source):
        global sessionExportedLayers
        if source in sessionExportedLayers:
            exportedLayer = sessionExportedLayers[source]
            if os.path.exists(exportedLayer):
                self.exportedLayers[source] = exportedLayer
                return None
            else:
                del sessionExportedLayers[source]
        layer = dataobjects.getObjectFromUri(source, False)
        if layer:
            filename = layer.name()
        else:
            filename = os.path.basename(source)
        validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
        filename = ''.join(c for c in filename if c in validChars)
        if len(filename) == 0:
            filename = 'layer'
        destFilename = getTempFilenameInTempFolder(filename + '.sgrd')
        self.exportedLayers[source] = destFilename
        sessionExportedLayers[source] = destFilename
        return 'io_gdal 0 -TRANSFORM 1 -INTERPOL 0 -GRIDS "' + destFilename + '" -FILES "' + source + '"'


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

import os
import subprocess
from git import Repo
import json
import logging

logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('info_branchs')

def get_all_branches_info(path):
    res = []
    for lFile in os.listdir(path):
        p = os.path.join(path, lFile)
        if os.path.isdir(p) \
                and lFile not in ['.', '..'] \
                and not os.path.islink(p):
            if lFile == '.git':
                logger.debug("Found a git folder %s", p)
                info = {}
                repo = Repo(p)
                info.update({'path': path,
                    'repo_url': str(repo.remotes.origin.url),
                    'branch': str(repo.head.ref),
                    'commit': str(repo.head.reference.commit),
                    'is_dirty': repo.is_dirty()})
                res.append(info)
            else:
                r = get_all_branches_info(p)
                if r:
                    res = res + r
    return res

if __name__ == '__main__':
    b_info = get_all_branches_info('/home/truiz/working/lodigroup/instance_as_prod')
    with open('branches_info.txt', 'w') as fout:
        json.dump(b_info, fout, sort_keys=True, indent=4, ensure_ascii=False)

    #_apply_recursive('/home/truiz/working/backupws')


rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
                 columns=list(letters[:26]))
tcorr = d.corr()

#Draw matrix SNS
def sns_heatmap(input_data, graph_title):
    sns.set(style="white")
    temp = input_data
    xcorr = temp
    mask = np.zeros_like(xcorr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True
    f, ax = plt.subplots(figsize=(20, 15))
    #cmap = sns.diverging_palette(240, 10, l=25, as_cmap=True)
    sns.set(font_scale=1.5)
    #annot=True/False (Adds Values in squares)
    sns.heatmap(xcorr, vmin=-0.4, vmax=0.9, center=0, annot=False, annot_kws={"size":10}, fmt=".2f",
                mask=mask, cmap='RdBu_r', square=True, xticklabels=True,
                yticklabels=True, label='big', linewidths=0.1, cbar_kws={"shrink": 0.5}, ax=ax)
    plt.yticks(fontsize=13)
    plt.xticks(fontsize=13)
    plt.xlabel('Location', fontsize=16)
    plt.ylabel('Location', fontsize=16)
    plt.title(graph_title)


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

# In[24]:

import openpyxl
import pandas as pd
import os
import datetime
#from IPython.display import display

# In[25]:

def print_full(x):
    df = pd.DataFrame(x)
    pd.set_option('display.max_rows', 2000)
    pd.set_option('display.max_columns', 20)
    display(df)

# In[26]:

excelname= "kd"
sheetname = "kd"

wb = openpyxl.load_workbook(str(excelname)+".xlsx")
ws = wb[str(sheetname)]

dataset = []

i = 1
while(ws.cell(row=i, column=1).value!=None):
    row = []
    j = 1
    while(ws.cell(row=i, column=j).value!=None):
        row.append(ws.cell(row=i, column=j).value)
        j = j +1
    dataset.append(row)
    i = i + 1

# In[27]:

pd.DataFrame(dataset)

# In[28]:

trade=[]
for i in range(0,len(dataset)):
    row=[]
    for j in range(0,11):
        row.append(0)
    trade.append(row)
trade[0][0] = "date"
trade[0][1] = "open"
trade[0][2] = "high"
trade[0][3] = "low"
trade[0][4] = "close"
trade[0][5] = "rsv"
trade[0][6] = "k"
trade[0][7] = "d"
trade[0][8] = "buy_day"
trade[0][9] = "cum_day"
trade[0][10] = "sell_day"

# In[29]:

#抓KD數據
for i in range(1, len(trade)):
    trade[i][0] = dataset[i][0]
    trade[i][1] = float(dataset[i][1])
    trade[i][2] = float(dataset[i][2])
    trade[i][3] = float(dataset[i][3])
    trade[i][4] = float(dataset[i][4])

#rsv
#RSV(t) = (close(t) - min(low(z)| z = t, t-1, ..., t-8)/(max(high(z)) - min(low(z)| z = t, t-1, ..., t-8)*100 , t = 9, 11, ..., T
for i in range(9, len(trade)):
    rsv = 0
    high = []
    low = []
    for j in range(0, 9):
        high.append(trade[i-j][2])
        low.append(trade[i-j][3])
    rsv = (trade[i][4]-min(low))/(max(high)-min(low))*100
    trade[i][5] = rsv
    print(rsv)

# In[30]:

#k (K值 初始值 = 50, at day 9，所以 K(9) = 50)
trade[9][6] = 50

for i in range(10,len(trade)):
    K = 0
    K = (trade[i-1][6]*2/3) + (trade[i][5]*1/3)
    trade[i][6] = K
    print(K)

# In[31]:

#d (D值 初始值 = 50, at day 9，所以 D(9) = 50)
trade[9][7] = 50

for i in range(10,len(trade)):
    D = 0
    D =(trade[i-1][7]*2/3) + (trade[i][6]*1/3) #trade[i][6]不能直接寫成K，因為寫K會只抓到最後一筆K值
    trade[i][7] = D
    print(D)

# In[32]:

#KD黃金交叉
#當KD指標的K值由下往上突破D值，建議買進、做多
#K(t) > D(t)
for i in range(10, len(trade)):
    if(trade[i][6] > trade[i][7])and(trade[i-1][9]==0):
        trade[i][8] = 1
        trade[i][9] = 1
        trade[i][10] = 0
    elif(trade[i][6] < trade[i][7])and(trade[i-1][9]==1):
        trade[i][8] = 0
        trade[i][9] = 0
        trade[i][10] = 1
    elif(trade[i-1][2]>0):
        trade[i][8] = 0
        trade[i][9] = 1
        trade[i][10] = 0

# In[33]:

for i in range(1, len(trade)):
    trade[i][0] = dataset[i][0]     #把日期、股價給trade
    trade[i][7] = float(dataset[i][7])

# In[34]:

for i in range(0, len(trade)):
    for j in range(0, len(trade[1])):
        ws.cell(row=i+1, column=j+1).value= trade[i][j]
wb.save('kd3.xlsx')

# In[ ]:

# In[ ]:


#!/home/lmanrique/anaconda3/bin/python

import numpy as np
import statistics
import time

def time_stat(func, size, ntrials):

  # the time to generate the random array should not be included
  x = 0
  sum_time = 0

  while x < ntrials:
    data = np.random.rand(size)

    # modify this function to time func with ntrials times using a new random array each time
    start = time.perf_counter()
    res = func(data)
    sum_time += (time.perf_counter() - start)
    x += 1

    # return the average run time
  return sum_time / ntrials

if __name__ == '__main__':
  print('{:.6f}s for statistics.mean'.format(time_stat(statistics.mean, 10**5, 30)))
  print('{:.6f}s for np.mean'.format(time_stat(np.mean, 10**5, 30)))


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import logging as log
import numpy as np
import sys
import os

from keras.preprocessing.image import ImageDataGenerator
from keras.utils import to_categorical
from keras.datasets import mnist
from keras import optimizers
from keras import layers
from keras import models
from util import *

log.basicConfig(level=log.INFO)

## 设置KERAS根目录，所有的数据集都从这个目录加载
log.info("set ENV `KERAS_HOME` ...")
os.environ["KERAS_HOME"] = "./keras"

## 设置GPU参数
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session(tf.Session(config=config))

## 从`https://www.kaggle.com/c/dogs-vs-cats/data`数据集提取一个小型的数据集
# get_small_dataset("/Users/uc/Downloads/dogs-vs-cats/", "./dataset/dogs-vs-cats")

## 加载图片并标准化
train_datagen = ImageDataGenerator(
	rescale = 1./255,
	rotation_range = 40,
	width_shift_range = 0.2,
	height_shift_range = 0.2,
	shear_range = 0.2,
	zoom_range = 0.2,
	horizontal_flip = True,
	fill_mode = 'nearest')

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
		"./dataset/dogs-vs-cats/train",
		# All images will be resized to 150x150
		target_size=(150, 150),
		batch_size=32,
		# Since we use binary_crossentropy loss, we need binary labels
		class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
	   	"./dataset/dogs-vs-cats/validation",
		target_size=(150, 150),
		batch_size=32,
		class_mode='binary')

## 构建模型
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])

## 训练模型
history = model.fit_generator(
	train_generator,
	steps_per_epoch = 100,
	epochs = 100,
	validation_data = validation_generator,
	validation_steps = 50)

model.save('./model/cats_and_dogs_small_2.h5')

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.subplot(211)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.subplot(212)
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()


#             *** GEOMETRIC model (points, lines, surfaces) - SETS***0
FEcase= xc.FEProblem()
preprocessor=FEcase.getPreprocessor
prep=preprocessor   #short name
nodes= prep.getNodeHandler
elements= prep.getElementHandler
elements.dimElem= 3
# Problem type
modelSpace= predefined_spaces.StructuralMechanics3D(nodes) #Defines the
# dimension of the space: nodes by three coordinates (x,y,z) and
# six DOF for each node (Ux,Uy,Uz,thetaX,thetaY,thetaZ)
sty=outSty.OutputStyle()
out=outHndl.OutputHandler(modelSpace,sty)

# grid model definition (tablero)
gridTabl= gm.GridModel(prep,xListTabl,yListTabl,zListTabl)

# Grid geometric entities definition (points, lines, surfaces)
# Points' generation
gridTabl.generatePoints()

#   Surfaces generation (tablero)
#Riostra estribo 1
x=xRiostrEstr[0]
y=yRiostrEstr[0]
z=zLosa[0]
riostrEstr1=gridTabl.genSurfOneXYZRegion(xyzRange=((x[0],y[0],z),(x[-1],y[-1],z)),setName='riostrEstr1')
#Riostra estribo 2
x=xRiostrEstr[1]
y=yRiostrEstr[1]
z=zLosa[0]
riostrEstr2=gridTabl.genSurfOneXYZRegion(xyzRange=((x[0],y[0],z),(x[-1],y[-1],z)),setName='riostrEstr2')
#Losa
x=xLosa
y=yLosa
z=zLosa[0]
losa=gridTabl.genSurfOneXYZRegion(xyzRange=((x[0],y[0],z),(x[-1],y[-1],z)),setName='losa')
#Cartabones
x=xCartab
y=yLosa
z=zLosa[0]
cartabInt=gridTabl.genSurfMultiXYZRegion(lstXYZRange=[((x[0][1],y[0],z),(x[0][-1],y[-1],z)),((x[1][0],y[0],z),(x[1][1],y[-1],z))], setName='cartabInt')
cartabExt=gridTabl.genSurfMultiXYZRegion(lstXYZRange=[((x[0][0],y[0],z),(x[0][1],y[-1],z)),((x[1][1],y[0],z),(x[1][-1],y[-1],z))], setName='cartabExt')
#Voladizos
x=xVoladz
y=yLosa
z=zLosa[0]
voladzInt=gridTabl.genSurfMultiXYZRegion(lstXYZRange=[((x[0][1],y[0],z),(x[0][-1],y[-1],z)),((x[1][0],y[0],z),(x[1][1],y[-1],z))], setName='voladzInt')
voladzExt=gridTabl.genSurfMultiXYZRegion(lstXYZRange=[((x[0][0],y[0],z),(x[0][1],y[-1],z)),((x[1][1],y[0],z),(x[1][-1],y[-1],z))], setName='voladzExt')

#                         *** MATERIALS ***
concrProp=tm.MaterialData(name='concrProp',E=concrete.Ecm(),nu=concrete.nuc,rho=concrete.density())
# Isotropic elastic section-material appropiate for plate and shell analysis
riostrEstr_mat=tm.DeckMaterialData(name='riostrEstr_mat',thickness= cantoRiostrEstr,material=concrProp)
riostrEstr_mat.setupElasticSection(preprocessor=prep)
losa_mat=tm.DeckMaterialData(name='losa_mat',thickness= cantoLosa,material=concrProp)
losa_mat.setupElasticSection(preprocessor=prep)
cartabInt_mat=tm.DeckMaterialData(name='cartabInt_mat',thickness=eCartInt,material=concrProp)
cartabInt_mat.setupElasticSection(preprocessor=prep)
cartabExt_mat=tm.DeckMaterialData(name='cartabExt_mat',thickness=eCartExt,material=concrProp)
cartabExt_mat.setupElasticSection(preprocessor=prep)
voladzInt_mat=tm.DeckMaterialData(name='voladzInt_mat',thickness=eVolInt,material=concrProp)
voladzInt_mat.setupElasticSection(preprocessor=prep)
voladzExt_mat=tm.DeckMaterialData(name='voladzExt_mat',thickness=eVolExt,material=concrProp)
voladzExt_mat.setupElasticSection(preprocessor=prep)

#                         ***FE model - MESH***
# IMPORTANT: it's convenient to generate the mesh of surfaces before meshing
# the lines, otherwise, sets of shells can take also beam elements touched by
# them
riostrEstr1_mesh=fem.SurfSetToMesh(surfSet=riostrEstr1,matSect=riostrEstr_mat,elemSize=eSize,elemType='ShellMITC4')
riostrEstr2_mesh=fem.SurfSetToMesh(surfSet=riostrEstr2,matSect=riostrEstr_mat,elemSize=eSize,elemType='ShellMITC4')
losa_mesh=fem.SurfSetToMesh(surfSet=losa,matSect=losa_mat,elemSize=eSize,elemType='ShellMITC4')
cartabInt_mesh=fem.SurfSetToMesh(surfSet=cartabInt,matSect=cartabInt_mat,elemSize=eSize,elemType='ShellMITC4')
cartabExt_mesh=fem.SurfSetToMesh(surfSet=cartabExt,matSect=cartabExt_mat,elemSize=eSize,elemType='ShellMITC4')
voladzExt_mesh=fem.SurfSetToMesh(surfSet=voladzExt,matSect=voladzExt_mat,elemSize=eSize,elemType='ShellMITC4')
voladzInt_mesh=fem.SurfSetToMesh(surfSet=voladzInt,matSect=voladzInt_mat,elemSize=eSize,elemType='ShellMITC4')

allmesh=[riostrEstr1_mesh,riostrEstr2_mesh,losa_mesh,cartabInt_mesh,cartabExt_mesh,voladzInt_mesh,voladzExt_mesh]
fem.multi_mesh(preprocessor=prep,lstMeshSets=allmesh)


import url
import tkinter as tk
from PIL import Image, ImageTk
import general

'''
This is using a known user-agent to extract the data.
https://stackoverflow.com/questions/16627227/http-error-403-in-python-3-web-scraping
'''
try:
    from urllib.request import Request, urlopen
    req = Request('https://www.surfline.com/surf-report/duck-pier/5842041f4e65fad6a7708a45', headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req).read()
    page = webpage.decode( 'UTF-8' )

except:
    print( 'Problem parsing web data.' )
    quit()

# Handles whether opening delimiter uses AM or PM
try:

    OPENING_DELIM = 'Northern Outer Banks PM Report:
'
    CLOSING_DELIM = '
'  # check this. changes from time to time

    start_index = page.index(OPENING_DELIM) + len(OPENING_DELIM)

except:

    OPENING_DELIM = 'Northern Outer Banks AM Report:
'
    CLOSING_DELIM = '
' # check this. changes from time to time

    start_index = page.index( OPENING_DELIM ) + len( OPENING_DELIM )

end_index = page.index( CLOSING_DELIM, start_index )

conditions = page[ start_index : end_index ]

# gets rid of ' ' left over in HTML code
conditions = general.remove( conditions, ' ' )

# formats text for the GUI
conditions = general.guiformat( conditions )

window = tk.Tk()
window.title( 'SURF CONDITIONS' )
window.geometry( '990x550')

im = ImageTk.PhotoImage(url.get_web_image( 'https://s3-us-west-1.amazonaws.com/sl-coldfusion-static-prod/surfnews/images/2010/09_september/earl_south/full/JesseHines_AvalonPier_OBX_Earl-Lusk.jpg'))
panel = tk.Label( window, image = im, height=0, width=0 )
panel.grid()

update_label = tk.Label( text= 'TODAY\'S CONDITIONS: \n\n' + conditions, font=('Times New Roman',15), bg= '#D9C3D3' )
update_label.grid( column=0, row=0 )

window.mainloop()


from django import template
from Freshy.models import OrderItem, ItemRating
register = template.Library()

@register.simple_tag
def get_order_items(obj):
    my_orders = OrderItem.objects.filter(order=obj)
    my_str = ''
    for item in my_orders:
        my_str += 'Food Name: ' + item.item.name + '
'
        my_str += 'Direction On Map:
'
        my_str += 'Kitchen Phone# ' + item.item.kitchen.phone + '
'
    return my_str

@register.simple_tag
def get_order_item_selling(obj):
    my_orders = OrderItem.objects.filter(order=obj)
    my_str = ''
    for item in my_orders:
        my_str += 'Food Name: ' + item.item.name + '
'
    return my_str

@register.simple_tag
def date_format(obj):
    return obj.strftime('%Y-%m-%d')

@register.simple_tag
def get_ratings(obj):
    stars = 0
    count = 0
    entry_list = ItemRating.objects.filter(item__id=obj)
    for item in entry_list:
        stars += item.rating.stars
        count = count + 1
    if count == 0:
        return 0
    return stars/count


"""Script to reset tables and insert demo data"""
#!/usr/bin/env python
import string
import sys

from todo.models import Board, Task
from todo.database import session, drop_tables, create_tables
from todo.constants import TO_DO, IN_PROGRESS, DONE

def main():
    drop_tables()
    create_tables()

    board = Board(name='Demo Board')
    session.add(board)
    session.commit()

    for i in range(6):
        board.task_number += 1
        title = 'Example task {}'.format(string.ascii_uppercase[i])
        description = 'Description of {}'.format(title)

        if i in [0, 1, 2]:
            status = TO_DO
        elif i in [3, 4]:
            status = IN_PROGRESS
        else:
            status = DONE

        task = Task(
            number=board.task_number,
            title=title,
            description=description,
            board_id=board.id,
            status=status)
        session.add(task)
    session.commit()

    return 0

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


def longPal(sentence):
	#split sentence and declare return string
	words = sentence.split()
	longest=""
	# check all words in sentence
	for x in words:
		#check reverse string and length
		if(x[::-1]==x and len(x)>len(longest)):
			longest=x;
	return longest

# call function defined above, print return value
print(longPal("jump into the sea paap joooooooj mom"))


import json
import sys
import os
import semver
from github import Github, GithubException, InputGitAuthor

HTTP_REQUEST_RETRIES = 3
HTTP_REQUEST_DELAY_IN_SECONDS = 2
HTTP_REQUEST_DELAY_MULTIPLIER = 2

packageUser =  os.environ["packageUser"]
packagePAT = os.environ["packagePAT"]
packageEmail =  os.environ["packageEmail"]

ORGANIZATION = "ballerina-platform"
STANDARD_LIBRARY = "stdlib"

MASTER_BRANCH = "master"
MAIN_BRANCH = "main"

VERSION_UPDATE_BRANCH_NAME = "automated/stdlib_version_update"
PULL_REQUEST_TITLE = "[Automated] Update Stdlib module versions"
PULL_REQUEST_BODY = "$subject"

PROPERTIES_FILE = "gradle.properties"

javaArraysModuleName = 'stdlibJavaArraysVersion'
OAuth2ModuleName = 'stdlibOAuth2Version'

SKIPPING_MODULES = ["kafka", "nats", "stan", "rabbitmq", "java.jdbc", "mysql", "serdes"]

def main():
    print("Checking Ballerina Distribution for stdlib version updates")
    module_list = get_stdlib_modules()
    repo = fetch_ballerina_distribution_repo()
    properties_file = fetch_properties_file(repo)
    current_versions = get_current_module_versions(properties_file)
    modified_properties_file, commit_flag, updated_modules = update_properties_file(properties_file, module_list, current_versions)
    if commit_flag:
        commit_changes(modified_properties_file, repo, updated_modules)
        create_pull_request(repo)
        print("Updated gradle.properties file in Ballerina Distribution Successfully")
    else:
        print("Stdlib versions in gradle.properties file are up to date")

# Get stdlib module details from stdlib_modules.json file
def get_stdlib_modules():
    try:
        with open('./release/resources/stdlib_modules.json') as f:
            module_list = json.load(f)
    except:
        print('Failed to read stdlib_modules.json')
        sys.exit()

    return module_list['modules']

# Fetch ballerina-distribution repository with GitHub credentials
def fetch_ballerina_distribution_repo():
    github = Github(packagePAT)
    try:
        repo = github.get_repo(ORGANIZATION + "/" + 'ballerina-distribution')
    except:
        print("Error fetching repository ballerina-distribution")

    return repo

# Fetch the gradle.properties file from the ballerina-distribution repo
def fetch_properties_file(repo):
    try:
        source = repo.get_branch(MAIN_BRANCH)
    except GithubException:
        source = repo.get_branch(MASTER_BRANCH)

    try:
        branch = repo.get_branch(branch=VERSION_UPDATE_BRANCH_NAME)
        repo.merge(VERSION_UPDATE_BRANCH_NAME, source.commit.sha, "Sync default branch")
        file = repo.get_contents(PROPERTIES_FILE, ref=VERSION_UPDATE_BRANCH_NAME)
    except GithubException:
        file = repo.get_contents(PROPERTIES_FILE)

    data = file.decoded_content.decode("utf-8")

    return data

# Get current versions of stdlib modules from gradle.properties file
def get_current_module_versions(properties_file):
    current_versions = {}

    for line in properties_file.splitlines():
        if STANDARD_LIBRARY in line and 'Version=' in line:
            module_name = line.split('=')[0]
            version = line.split('=')[1]
            current_versions[module_name] = version

    return current_versions

# Compare latest version with current version
# Return 1 if latest version > current version
# Return 0 if latest version = current version
# Return -1 if latest version < current version
def compare_version(latest_version, current_version):
    if semver.compare(latest_version.split('-')[0], current_version.split('-')[0]) == 1:
        return latest_version
    else:
        return latest_version

# Update stdlib module versions in the gradle.properties file with module details fetched from stdlib_modules.json
def update_properties_file(data, modules, current_versions):
    modified_data = ''
    updated_modules = []
    current_line = ''
    commit_flag = False

    line_list = data.splitlines()

    for line in line_list:
        if STANDARD_LIBRARY in line.lower():
            current_line = line
            break
        line += '\n'
        modified_data += line
    modified_data = modified_data[0:-1]

    level = 1
    for module in modules:
        if module['level'] == level:
            line = "\n# Stdlib Level " + f"{level:02d}" + "\n"
            modified_data += line
            level += 1

        module_name = module['name'].split('-')[-1]
        latest_version = module['version']

        if module_name == 'jballerina.java.arrays':
            version = compare_version(latest_version, current_versions[javaArraysModuleName])
            line = javaArraysModuleName + "=" + version + "\n"
        elif module_name == 'oauth2':
            version = compare_version(latest_version, current_versions[OAuth2ModuleName])
            line = OAuth2ModuleName + "=" + version + "\n"
        elif module_name in SKIPPING_MODULES:
            continue
        else:
            module_name_in_naming_convention = STANDARD_LIBRARY + module_name.capitalize() + 'Version'
            if module_name_in_naming_convention in current_versions:
                version = compare_version(latest_version, current_versions[module_name_in_naming_convention])
            else:
                version = latest_version
            line = STANDARD_LIBRARY + module_name.capitalize() + "Version=" + version + "\n"

        if line[0:-1] not in line_list:
            updated_modules.append(module_name)
        modified_data += line

    for line in line_list[line_list.index(current_line):len(line_list)]:
        current_line = line
        if STANDARD_LIBRARY not in line.lower() and line != '':
            break

    modified_data += "\n"

    for line in line_list[line_list.index(current_line):len(line_list)]:
        if STANDARD_LIBRARY not in line.lower():
            line += "\n"
            modified_data += line

    # modified_data = modified_data[0:-1]
    if modified_data != data:
        commit_flag = True

    return modified_data, commit_flag, updated_modules

# Commit changes made to the gradle.properties file
def commit_changes(data, repo, updated_modules):
    author = InputGitAuthor(packageUser, packageEmail)

    # If branch already exists checkout and commit else create new branch from master branch and commit
    try:
        source = repo.get_branch(MAIN_BRANCH)
    except GithubException:
        source = repo.get_branch(MASTER_BRANCH)

    try:
        repo.get_branch(branch=VERSION_UPDATE_BRANCH_NAME)
        repo.merge(VERSION_UPDATE_BRANCH_NAME, source.commit.sha, "Sync default branch")
    except:
        repo.create_git_ref(ref=f"refs/heads/" + VERSION_UPDATE_BRANCH_NAME, sha=source.commit.sha)

    contents = repo.get_contents(PROPERTIES_FILE, ref=VERSION_UPDATE_BRANCH_NAME)

    if len(updated_modules) > 0:
        commit_message = "Bump the version of stdlib module(s) - "
        for updated_module in updated_modules:
            commit_message += updated_module
            commit_message += " "
    else:
        commit_message = "Update gradle.properties"

    repo.update_file(
        contents.path,
        commit_message,
        data,
        contents.sha,
        branch=VERSION_UPDATE_BRANCH_NAME,
        author=author
    )

# Create a PR from the branch created
def create_pull_request(repo):
    pulls = repo.get_pulls(state='open', head=VERSION_UPDATE_BRANCH_NAME)

    pr_exists = 0

    # Check if a PR already exists for the module
    for pull in pulls:
        if PULL_REQUEST_TITLE in pull.title:
            pr_exists = pull.number

    # If PR doesn't exists create a new PR
    if pr_exists == 0:
        try:
            repo.create_pull(
                title=PULL_REQUEST_TITLE,
                body=PULL_REQUEST_BODY,
                head=VERSION_UPDATE_BRANCH_NAME,
                base=MAIN_BRANCH
            )
        except GithubException:
            repo.create_pull(
                title=PULL_REQUEST_TITLE,
                body=PULL_REQUEST_BODY,
                head=VERSION_UPDATE_BRANCH_NAME,
                base=MASTER_BRANCH
            )

main()


import numpy as np
import matplotlib.pyplot as plt

data = np.load('Alphabets.npy')
labels = np.load('Alphabet_labels.npy')
alphabets =  np.array(['C','I','O','P','S','U','X','Z'])
for i in range(0,500):
    plt.imshow(data[i].reshape(28,28))
    print(alphabets[labels[i]])
    plt.show()
print(data.shape,labels.shape)


"""
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:

[]                                -->  "no one likes this"
["Peter"]                         -->  "Peter likes this"
["Jacob", "Alex"]                 -->  "Jacob and Alex like this"
["Max", "John", "Mark"]           -->  "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"]  -->  "Alex, Jacob and 2 others like this"
Note: For 4 or more names, the number in "and 2 others" simply increases.

docker:
docker run -it --name likes -v $PWD:/home/app -w /home/app -p 5000:5000 python:3.9-slim python likes.py

docker build -t likes:v1 .
docker-compose up

"""
def likes(names):
    if(len(names)==0):return 'no one likes this'
    elif(len(names)==1):return '{} likes this'.format(names[0])
    elif(len(names)==2):return '{} and {} like this'.format(names[0],names[1])
    elif(len(names)==3):return '{}, {} and {} like this'.format(names[0],names[1],names[2])
    else:
        return '{}, {} and {} others like this'.format(names[0],names[1],len(names)-2)

assert(likes([])== 'no one likes this')
assert(likes(['Peter'])== 'Peter likes this')
assert(likes(['Jacob', 'Alex'])== 'Jacob and Alex like this')
assert(likes(['Max', 'John', 'Mark'])== 'Max, John and Mark like this')
assert(likes(['Alex', 'Jacob', 'Mark', 'Max'])== 'Alex, Jacob and 2 others like this')

print("done")


from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from urllib import parse
import threading, json, logging

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""
    def add(self, route):
        self.RequestHandlerClass.routedef = route

class ApiHandler(BaseHTTPRequestHandler):
    routedef = []

    def do_GET(self):
        self.call()

    def do_POST(self):
        logging.info("Get POST request")
        self.data = json.loads(self.rfile.read(
            int(self.headers['Content-Length'])).decode("UTF-8"))
        self.call()

    def do_DELETE(self):
        self.call()

    def do_PUT(self):
        self.call()

    def call(self):
        self.content = self.serve()
        print(self.content)
        self.setheaders()
        self.wfile.write(self.content['body'].encode('utf-8'))

    def getroutematch(self):
        for route_pattern, route_function, data, authent in self.routedef[self.command.lower()]:
            m = route_pattern.match(self.path)
            if m:
                return m.groupdict(), route_function, data, authent

    def serve(self):
        route_match = self.getroutematch()
        if route_match:
            kwargs, rfunction, data, authent = route_match
            if authent:
                # code authent
                pass
            if data:
                return rfunction(self.data, **kwargs)
            else:
                return rfunction(**kwargs)
        else:
            print('Route "{}"" has not been registered'.format(self.path))
            return None

    def setheaders(self):
        if 'returncode' in self.content:
            self.send_response(self.content['returncode'])
        else:
            self.send_error(404)
            self.content['body'] = '{"error":"Resource not found"}'
        if 'contenttype' in self.content:
            self.send_header(
                'Content-Type',
                self.content['contenttype']
            )
        if 'location' in self.content:
            self.send_header(
                'Location',
                self.content['location']
            )
        self.end_headers()