# coding=utf-8
import sys
import unittest
from bgmi.command import CommandParser, NameSpace

class CommandTest(unittest.TestCase):

    def test_argument_name(self):
        c = CommandParser()
        group_1 = c.add_arg_group('test')
        group_1.add_argument('--id-aa--', arg_type='1')
        sys.argv = ['test.py', '--id-aa--', '123456']
        namespace_1 = c.parse_command()

        self.assertEqual(namespace_1.test.id_aa__, '123456')

    def test_parse_positional_argument(self):
        c = CommandParser()
        c.add_argument('method')
        c.add_argument('sub_method')
        sys.argv = ['test.py', 'method_test', 'sub_method_test']
        namespace_1 = c.parse_command()

        self.assertEqual(namespace_1.method, 'method_test')
        self.assertEqual(namespace_1.sub_method, 'sub_method_test')

    def test_sub_parser(self):
        c = CommandParser()
        group_1 = c.add_arg_group('test')
        sub_1 = group_1.add_sub_parser('sub_action')
        sub_2 = group_1.add_sub_parser('sub_action2')

        # conflict action name: --sub_action
        self.assertRaises(SystemExit, group_1.add_sub_parser, '--sub_action')

        sub_1.add_argument('--force')
        sub_1.add_argument('--id', arg_type='+')
        sub_2.add_argument('--verbose', arg_type='+')

        sys.argv = ['test.py', 'sub_action', '--force']
        namespace_1 = c.parse_command()
        self.assertEqual(namespace_1.test.sub_action.force, True)

        sys.argv = ['test.py', 'sub_action', '--force', '--sub_action2', '--verbose', '1']
        # unrecognized arguments: --sub_action2
        self.assertRaises(SystemExit, c.parse_command)

        sys.argv = ['test.py', 'sub_action2', '--force']
        # unrecognized arguments: --force
        self.assertRaises(SystemExit, c.parse_command)
        sys.argv = ['test.py', 'sub_action2', '--verbose', '666']
        namespace_1 = c.parse_command()
        self.assertEqual(namespace_1.test.sub_action2.verbose, ['666', ])

        d = CommandParser()
        group_2 = d.add_arg_group('action')
        s_1 = group_2.add_sub_parser('update')
        s_1.add_argument('subaction')
        s_2 = group_2.add_sub_parser('delete')
        s_2.add_argument('--subaction2')

        sys.argv = ['test.py', 'update', 'help']
        namespace_2 = d.parse_command()
        self.assertEqual(namespace_2.action.update.subaction, 'help')

        sys.argv = ['test.py', 'delete', '--subaction2']
        namespace_2 = d.parse_command()
        self.assertEqual(namespace_2.action.delete.subaction2, True)

    def test_parse_command(self):
        c = CommandParser()
        group_1 = c.add_arg_group('test')
        # positional argument
        group_1.add_argument('method')
        group_1.add_argument('-v', dest='verbose', default=False)
        group_1.add_argument('--id', dest='id', arg_type='1', default=False)
        group_1.add_argument('--id2', dest='id2', arg_type='+')
        group_1.add_argument('--id3', dest='id3', arg_type='+')

        sys.argv = ['test.py', 'method_test1']
        namespace_1 = c.parse_command()
        self.assertFalse(namespace_1.test.verbose)

        sys.argv = ['test.py', 'method_test2', '-v']
        namespace_2 = c.parse_command()
        self.assertTrue(namespace_2.test.verbose)

        sys.argv = ['test.py', 'method_test3', '-v', '--id', '1', '--id2', '1', '2']
        namespace_3 = c.parse_command()
        self.assertEqual(namespace_3.test.method, 'method_test3')
        self.assertEqual(namespace_3.test.id, '1')
        self.assertEqual(namespace_3.test.id2, ['1', '2'])

    def test_choice(self):
        c = CommandParser()
        g1 = c.add_arg_group('test')
        g1.add_argument('--method', arg_type='1', choice=('GET', 'POST', 'HEAD', ))
        sys.argv = ['test.py', '--method', 'PUT']
        self.assertRaises(SystemExit, c.parse_command)

        c = CommandParser()
        g2 = c.add_arg_group('test')
        sub_1 = g2.add_sub_parser('get_method')
        sub_1.add_argument('--get', arg_type='1', choice=('GET', 'HEAD', ), default='GET')

        sub_2 = g2.add_sub_parser('post_method')
        sub_2.add_argument('--post', arg_type='1', choice=('POST', 'PUT', ))

        sys.argv = ['test.py', 'get_method']
        namespace = c.parse_command()
        self.assertEqual(namespace.test.get_method.get, 'GET')

    def test_required(self):
        c = CommandParser()
        g1 = c.add_arg_group('test')
        g1.add_argument('method', required=True)
        g1.add_argument('--get', required=True)

        sys.argv = ['test.py']
        self.assertRaises(SystemExit, c.parse_command)

        sys.argv = ['test.py', 'GET']
        self.assertRaises(SystemExit, c.parse_command)

        sys.argv = ['test.py', 'GET', '--get']
        self.assertIsInstance(c.parse_command(), NameSpace)

    def test_position_arg_type(self):
        c = CommandParser()
        g1 = c.add_arg_group('test')
        g1.add_argument('position', arg_type='+')
        g1.add_argument('--verbose')
        sys.argv = ['test.py', 'AAA', 'BBB', 'CCC', '--verbose']
        namespace = c.parse_command()
        self.assertEqual(namespace.test.position, ['AAA', 'BBB', 'CCC'])

    def test_mutex_arg(self):
        # ordinary
        c = CommandParser()
        g1 = c.add_arg_group('test')
        g1.add_argument('--clear-all', mutex='--delete')
        g1.add_argument('--delete', arg_type='+')
        sys.argv = ['test.py', '--delete', 'AAA', '--clear-all']
        self.assertRaises(SystemExit, c.parse_command)

        # sub parser
        c = CommandParser()
        g2 = c.add_arg_group('test')
        sub = g2.add_sub_parser('sub')
        sub.add_argument('--clear-all', mutex='--delete')
        sub.add_argument('--delete', arg_type='+')
        sys.argv = ['test.py', 'sub', '--delete', 'AAA', '--clear-all']
        self.assertRaises(SystemExit, c.parse_command)

        c = CommandParser()
        g3 = c.add_arg_group('test')
        g3.add_argument('--clear-all-sub', mutex='--delete-sub')
        sub2 = g3.add_sub_parser('sub')
        sub2.add_argument('--delete-sub', arg_type='+')
        sys.argv = ['test.py', '--clear-all-sub', 'sub', '--delete-sub', 'AAA']
        self.assertIsInstance(c.parse_command(), NameSpace)

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


"""
Given an array that contains both positive and negative integers, find the product of the maximum product subarray.
Expected Time complexity is O(n) and only O(1) extra space can be used.

Input: arr[] = {6, -3, -10, 0, 2}
Output:   180  // The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}
Output:   60  // The subarray is {60}

Input: arr[] = {-2, -3, 0, -2, -40}
Output:   80  // The subarray is {-2, -40}
"""

"""
This can be considered as a DP problem
Similar to max_sum_subarray
"""

def max_product_subarray(nums):
    if not nums:
        return -1

    current_max = current_min = max_product = nums[0]

    for i in range(1, len(nums)):
        current_min, current_max = min(nums[i], nums[i] * current_min, nums[i] * current_max), max(nums[i], nums[i] * current_min, nums[i] * current_max)
        max_product = max(max_product, current_max)
    return max_product

print(max_product_subarray([-2, -3, 0, -2, -40]))

print(max_product_subarray([6, -3, -10, 0, 2]))


# coding: utf-8

from the_tale.linguistics.lexicon.relations import VARIABLE as V
from the_tale.linguistics.lexicon.groups.relations import LEXICON_GROUP

KEYS = [(u'PVP_MISS_ABILITY', 340000, u'Журнал: Неудачное использование способности', LEXICON_GROUP.PVP,
         u'Хранитель пытается применить способность и терпит неудачу.',
         [V.DUELIST_1, V.DUELIST_2], None),

        (u'PVP_SAY', 340001, u'Журнал: Сообщение', LEXICON_GROUP.PVP,
         u'Один из участвующих Хранителей что-то сказал.',
         [V.TEXT], None),

        (u'PVP_USE_ABILITY_BLOOD', 340002, u'Журнал: Использование способности крови', LEXICON_GROUP.PVP,
         u'Хранитель применяет способность крови.',
         [V.EFFECTIVENESS, V.DUELIST_1, V.DUELIST_2], u'duelist_1#N +effectiveness#EF'),

        (u'PVP_USE_ABILITY_FLAME', 340003, u'Журнал: Использование способности пламени', LEXICON_GROUP.PVP,
         u'Хранитель применяет способность пламени.',
         [V.DUELIST_1, V.DUELIST_2], None),

        (u'PVP_USE_ABILITY_ICE', 340004, u'Журнал: Использование способности льда', LEXICON_GROUP.PVP,
         u'Хранитель применяет способность льда.',
         [V.DUELIST_1, V.DUELIST_2], None),

       ]


import unittest
from appium import webdriver

class TestClass(unittest.TestCase):

    def setUp(self):
        desired_capabilities = {}
        desired_capabilities['testobject_api_key'] = 'your TestObject API key here'
        desired_capabilities['testobject_device'] = 'LG_Nexus_4_E960_real'
        desired_capabilities['testobject_appium_version'] = '1.5.2-patched-chromedriver'
        testobject_endpoint = 'http://appium.testobject.com:80/api/appium/wd/hub'
        self.driver = webdriver.Remote(testobject_endpoint, desired_capabilities)

    # All test methods starts with the word "test_"
    def test_open_testobject_website(self):
        self.driver.get("https://testobject.com/")
        if not "TestObject" in self.driver.title:
            raise Exception("Unable to load TestObject")

    def tearDown(self):
        self.driver.quit()

# This will trigger the test
if __name__ == '__main__':
    unittest.main()


from typing import Any, Type
import random
import time
from loguru import logger
from operator import itemgetter
from math import log
from node import Node
from referee import Referee
from tic_tac_toe import TicTacToe
import pickle
from tqdm import tqdm

LOGGER = logger

def train(count_limit, mode='first', first_node=None):
    count = 0
    nth_limit = 0
    tictactoe = TicTacToe()

    # LOGGER.info('get referee')
    referee = Referee()
    # LOGGER.success('got referee')

    if mode == 'first':
        # LOGGER.info('mode is first')
        first_node = tictactoe.set_first_node()
    else:
        # LOGGER.info('use saved first node')
        first_node = first_node
    while count < count_limit:
        if count%10000==0:
            print('='*20)
            print(count)
            print('=' * 20)
        target_node = first_node
        cnt = 0
        depth = 0
        while True:
            # LOGGER.info('calculate ucb')
            target = tictactoe.cal_ucb(target_node)

            #
            # check whether now it is end or not for every turn
            #
            if target is None:
                # LOGGER.info('target is None')
                white_list, black_list, prev_list = tictactoe._return_each_list(target_node)
                # LOGGER.info(f'{white_list},{black_list},{prev_list}')
                if referee.check_end(white_list):
                    tictactoe.update_node(target_node, 'white')
                    count += 1
                    break
                elif referee.check_end(black_list):
                    # print('BLACK WIN!!!='*10)
                    tictactoe.update_node(target_node, 'black')
                    count += 1
                    break
                else:
                    if len(prev_list) == 9:
                        tictactoe.update_node(target_node, 'draw')
                        count += 1
                        break
                    else:
                        pass

            #
            # if it is not the end
            # (i) first, expand the tree
            # (ii) or reach for the end
            #

            if target is None:
                # LOGGER.info('next node is None')
                if target_node.total >= nth_limit:
                    # LOGGER.info('start depth process')
                    tictactoe.start_depth(target_node)
            else:
                if target == 'random':
                    # LOGGER.info('ucb result is random, so choice random one')
                    target = random.choice(target_node.next)
                    target_node = target
                else:
                    # LOGGER.info('reach for the last one')
                    target_node = target
    return first_node

def main():
    first_node = train(100000000)
    with open('./model/TTT', 'wb') as f:
        pickle.dump(first_node,f)

if __name__=='__main__':
    main()


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self, value):
        self.head = Node(value)

    def append(self, value):
        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = Node(value)

    def print_all(self):
        cur = self.head
        while cur is not None:
            print(cur.data)
            cur = cur.next

    def get_node(self, index):
        if index < 0:
            return None
        i = 0
        cur = self.head
        while i < index:
            cur = cur.next
            i += 1
        return cur

    def add_node(self,index, value):
        if index < 0:
            return
        if index == 0:
            temp = self.head
            self.head = Node(value)
            self.head.next = temp
        else:
            cur = self.get_node(index-1)
            if cur is not None:
                temp = cur.next
                new_node = Node(value)
                cur.next = new_node
                new_node.next = temp

    def delete_node(self, index):
        if index < 0:
            return
        if index == 0:
            temp = self.head.next
            self.head = temp
        else:
            cur = self.get_node(index-1)
            if cur is not None:
                temp = cur.next
                cur.next = temp.next

linked_list = LinkedList(5)
linked_list.append(12)
linked_list.append(8)
linked_list.append(1)
linked_list.add_node(0,32)
linked_list.delete_node(0)
linked_list.print_all()


# -*- coding: utf-8 -*-
"""
Created on Fri May 23 10:45:33 2014

@author: Feng-cong Li
"""
from __future__ import print_function, division

from numpy import *
import time
from Tkinter import *
from ttk import *

from wavesynlib import guicomponents
from wavesynlib.guicomponents.tk                import Group, ParamItem
from wavesynlib.guicomponents.classselector     import askClassName
from wavesynlib.application                     import Application, ScriptCode, Scripting
from wavesynlib.basewindow                      import FigureWindow
from wavesynlib.common                          import setMultiAttr, autoSubs, evalFmt, Nonblocking
from wavesynlib.mathtools                       import Algorithm, AlgorithmDict, AlgorithmNode

import threading
import json

class OptimizeGroup(Group):
    def __init__(self, *args, **kwargs):
        self._app = Application.instance
        self.__topwin = kwargs.pop('topwin')

        super(OptimizeGroup, self).__init__(*args, **kwargs)

        paramFrm    = Frame(self)
        paramFrm.pack(side=LEFT, expand=YES, fill=Y)
        self.__num = ParamItem(paramFrm)
        setMultiAttr(self.__num,
            labelText   = 'num',
            entryText   = '1',
            labelWidth  = 5,
            entryWidth  = 8,
            checkFunc   = self._app.checkInt
        )
        self.__num.entry.bind('<Return>', lambda event: self.onSolveClick())
        self.__num.pack(side=TOP)

        self.__pci  = ParamItem(paramFrm)
        setMultiAttr(self.__pci,
            labelText   = 'PCI',
            entryText   = '100',
            labelWidth  = 5,
            entryWidth  = 8,
            checkFunc   = self._app.checkInt
        )
        self.__pci.pack(side=TOP)

        self.__bParallel    = IntVar()
        self.__chkParallel  = Checkbutton(paramFrm, text="Parallel", variable=self.__bParallel)
        self.__chkParallel.pack()

        progfrm = Frame(self)
        progfrm.pack(side=LEFT, expand=YES, fill=Y)

        self.__genbtn = Button(progfrm, text='Generate', command=self.onSolveClick)
        self.__genbtn.pack(side=TOP)
        Button(progfrm, text='Stop', command=self.onStopBtnClick).pack(side=TOP)

        self.__progress = IntVar()
        self.__finishedwav = IntVar()
        self.__progbar = Progressbar(progfrm, orient='horizontal', variable=self.__progress, maximum=100)
        self.__progbar.pack(side=LEFT)
        self.__progbar.config(length=55)
        self.__finishedwavbar = Progressbar(progfrm, orient='horizontal', variable=self.__finishedwav)
        self.__finishedwavbar.pack(side=LEFT)
        self.__finishedwavbar.config(length=30)

        self.name = 'Generate'

        self.getparams = None
        self.__stopflag = False

    def onSolveClick(self):
        t1  = time.clock()
        if self.__bParallel.get():
            self.parallelRun()
        else:
            self.serialRun()
        deltaT  = time.clock() - t1
        print(autoSubs('Total time consumption: $deltaT (s)'))

    def serialRun(self):
        tbicon = self._app.tbicon
        self.__stopflag = False
        wavnum = self.__num.getInt()
        progress = [0]
        waveform = [0]

        algorithm   = self.__topwin.currentAlgorithm

        params = self.__topwin.grpParams.getParams()

        class AlgoThread(threading.Thread):
            def __init__(self, algo, params, waveform, progress):
                self.algo = algo
                self.progress = progress
                threading.Thread.__init__(self)
            def run(self):
                printCode   = True
                self.algo.run(**params)

        self.__finishedwavbar['maximum'] = wavnum

        def progressChecker(k, K, y, *args, **kwargs):
            progress[0] = int(k / K * 100)

        algorithm.progressChecker.append(progressChecker)
        algorithm.progressChecker.interval  = int(self.__pci.entryText)
        try:
            for cnt in range(wavnum):
                algothread = AlgoThread(algorithm, params, waveform, progress)
                algothread.start()

                while algothread.isAlive():
                    self.__progress.set(progress[0])
                    tbicon.progress = int((cnt*100+progress[0])/(wavnum*100)*100)
                    self.__topwin.update()
                    if self.__stopflag:
                        break
                    time.sleep(0.05)
                self.__progress.set(0)
                if self.__stopflag:
                    break
                printCode   = True
                self.__topwin.plotCurrentData()
                self.__finishedwav.set(cnt+1)
        finally:
            algorithm.progressChecker.remove(progressChecker)
        self.__finishedwav.set(0)
        tbicon.state = guicomponents.tk.TBPF_NOPROGRESS

    def parallelRun(self):
        class AlgoThread(threading.Thread):
            def __init__(self, algorithm, parameters, num):
                self.algorithm  = algorithm
                self.parameters = parameters
                self.num        = num
                super(AlgoThread, self).__init__()
            def run(self):
                printCode   = True
                #parameters  = Scripting.paramsToStr(**self.parameters)
                paramStr    = evalFmt('[([], dict({Scripting.paramsToStr(**self.parameters)}))]*{self.num}')
                self.algorithm.parallelRunAndPlot(ScriptCode(paramStr))
        algorithm   = self.__topwin.currentAlgorithm
        parameters  = self.__topwin.grpParams.getParams()
        theThread   = AlgoThread(algorithm, parameters, self.__num.getInt())
        theThread.start()
        while theThread.isAlive():
            self.__topwin.update()
            time.sleep(0.05)

    def onStopBtnClick(self):
        self.__stopflag = True

class ParamsGroup(Group):
    def __init__(self, *args, **kwargs):
        self._app = Application.instance
        self.__topwin   = kwargs.pop('topwin')
        self.balloon    = self._app.balloon

        #Group.__init__(self, *args, **kwargs)
        super(ParamsGroup, self).__init__(*args, **kwargs)
        self.__algo = None
        self.__MAXROW = 3
        self.__params = {}

        self.__frameDict    = {}

        self.name = 'Parameters'

    def appendAlgorithm(self, algorithm):
        #To do: when algo is reset, the frm should be removed
        for algoName in self.__frameDict:
            self.__frameDict[algoName]['frame'].pack_forget()
        frm = Frame(self)
        frm.pack()
        paramInfo   = {}
        params = algorithm['parameters']
        for idx, name in enumerate(params):
            param = params[name]
            paramitem = ParamItem(frm)
            paramitem.labelText = name
            paramitem.labelWidth = 5
            paramitem.entryWidth = 8
            if self.balloon:
                self.balloon.bind_widget(paramitem.label, balloonmsg=param.shortdesc)
            if param.type == 'int':
                paramitem.checkFunc = self._app.checkInt
            elif param.type == 'float':
                paramitem.checkFunc = self._app.checkFloat
            paramitem.grid(row=idx%self.__MAXROW, column=idx//self.__MAXROW)
            #self.__params[param.name] = {'gui':paramitem, 'meta':param}
            paramInfo[param.name] = {'gui':paramitem, 'meta':param}
        self.__algo = algorithm
        #self.__frameDict[algorithm.meta.name]   = frm
        self.__frameDict[algorithm['name']]   = dict(frame=frm, paramInfo=paramInfo)
        self.__params   = paramInfo

    def getParams(self):
        params = self.__params
        convert = {'int':int, 'float':float, 'expression':lambda expr: ScriptCode(expr), '':lambda x: x}
        return {name: convert[params[name]['meta'].type](params[name]['gui'].entryText) for name in params}

    def changeAlgorithm(self, algorithmName):
        for algoName in self.__frameDict:
            self.__frameDict[algoName]['frame'].pack_forget()
        self.__frameDict[algorithmName]['frame'].pack()
        self.__params   = self.__frameDict[algorithmName]['paramInfo']

class AlgoSelGroup(Group):
    def __init__(self, *args, **kwargs):
        self._topwin  = kwargs.pop('topwin')
        super(AlgoSelGroup, self).__init__(*args, **kwargs)

        self.__algoList = Combobox(self, value=[], takefocus=1, stat='readonly', width=12)
        self.__algoList['values']   = []
        self.__algoList.pack()
        self.__algoList.bind('<<ComboboxSelected>>', self.onAlgorithmChange)

        Button(self, text='Load Algorithm', command=self.onLoadAlgorithm).pack()

        self.name = 'Algorithms'

    @property
    def algoList(self):
        return self.__algoList

    def onAlgorithmChange(self, event):
        self._topwin.changeAlgorithm(event.widget.get())

    def onLoadAlgorithm(self):
        printCode   = True

        funcObj    = Nonblocking(askClassName)('wavesynlib.algorithms', Algorithm)
        while funcObj.isRunning():
            #self._topwin.update()
            Application.doEvents()
            time.sleep(0.1)

        classInfo   = funcObj.returnValue

        if not classInfo:
            return
        moduleName, className   = classInfo
        self._topwin.loadAlgorithm(moduleName=moduleName, className=className)

class SingleWindow(FigureWindow):
    windowName  = 'WaveSyn-SingleSyn'

    _xmlrpcexport_  = ['loadAlgorithm']

    def __init__(self, *args, **kwargs):
        FigureWindow.__init__(self, *args, **kwargs)
        self.currentData    = None

        # algorithm dict and current data
        self.algorithms = AlgorithmDict()
        self.lockAttribute('algorithms')
        #

        # The toolbar
        toolTabs    = self.toolTabs
        figureBook  = self.figureBook

        frmAlgo = Frame(toolTabs)
        grpAlgoSel  = AlgoSelGroup(frmAlgo, topwin=self)
        grpAlgoSel.pack(side=LEFT, fill=Y)

        grpParams   = ParamsGroup(frmAlgo, topwin=self)
        grpParams.pack(side=LEFT, fill=Y)

        grpSolve    = OptimizeGroup(frmAlgo, topwin=self)
        grpSolve.pack(side=LEFT, fill=Y)
        toolTabs.add(frmAlgo, text='Algorithm')

        with self.attributeLock:
            setMultiAttr(self,
                grpAlgoSel  = grpAlgoSel,
                grpParams   = grpParams,
                grpSolve    = grpSolve
            )

        self.makeViewTab()
        self.makeMarkerTab()
        self.makeExportTab()
        # End toolbar
        figureBook.makeFigures(
            figureMeta  = [
                dict(name='Envelope',           polar=False),
                dict(name='Phase',              polar=False),
                dict(name='AutoCorrelation',    polar=False),
                dict(name='PSD',                polar=False)
            ]
        )

        with open(Application.instance.configFileName) as f:
            config  = json.load(f)
        algorithms  = config['SingleWaveformAlgorithms']

        for algo in algorithms:
            self.loadAlgorithm(moduleName=algo['ModuleName'], className=algo['ClassName'])

        self.grpAlgoSel.algoList.current(len(algorithms)-1)

        figEnvelope = figureBook[0]
        figEnvelope.plotFunction  = lambda currentData, *args, **kwargs:\
            figEnvelope.plot(abs(currentData), *args, **kwargs)

        figPhase    = figureBook[1]
        figPhase.plotFunction   = lambda currentData, *args, **kwargs:\
            figPhase.plot(angle(currentData), *args, **kwargs)

        def plot_acdb(currentData, *args, **kwargs):
            s   = currentData
            if not isinstance(s, ndarray):
                s   = array(s)
            N       = len(s)
            ac      = convolve(s, conj(s[::-1]))
            acdb    = 20*log10(abs(ac))
            acdb    = acdb - max(acdb)
            figAuto.plot(r_[(-N+1):N], acdb, *args, **kwargs)

        figAuto     = figureBook[2]
        figAuto.plotFunction    = plot_acdb

        figPSD      = figureBook[3]
        figPSD.plotFunction     = lambda currentData, *args, **kwargs:\
            figPSD.plot(abs(fft.fft(currentData)), *args, **kwargs)

    @Scripting.printable
    def loadAlgorithm(self, moduleName, className):
        node    = AlgorithmNode(moduleName, className)
        self.algorithms.add(node)
        values  = self.grpAlgoSel.algoList['values']
        if values == '':
            values  = []
        if isinstance(values, tuple):
            values  = list(values)
        values.append(node['name'])
        self.grpAlgoSel.algoList['values']  = values
        self.grpAlgoSel.algoList.current(len(values)-1)
        self.grpParams.appendAlgorithm(node)

    def changeAlgorithm(self, algorithmName):
        self.grpParams.changeAlgorithm(algorithmName)

    @property
    def currentAlgorithm(self):
        return self.algorithms[self.grpAlgoSel.algoList.get()]


import pyhf
import json

import numpy as np
import matplotlib.pylab as plt

signal = [5.0, 10.0]
background = [50.0, 60.0]
bkg_uncerts=[5.0, 12.0]

model = pyhf.simplemodels.hepdata_like(signal_data=signal,
                                        bkg_data=background,
                                        bkg_uncerts=bkg_uncerts)
#model

print(f'  channels: {model.config.channels}')
print(f'     nbins: {model.config.channel_nbins}')
print(f'   samples: {model.config.samples}')
print(f' modifiers: {model.config.modifiers}')
print(f'parameters: {model.config.parameters}')
print(f'  nauxdata: {model.config.nauxdata}')
print(f'   auxdata: {model.config.auxdata}')

print(model.config.auxdata)

print(model.expected_data([1.0, 1.0, 1.0]))

print(model.expected_data([1.0, 1.0, 1.0], include_auxdata=False))

print(model.expected_actualdata([1.0, 1.0, 1.0]))

print(model.expected_auxdata([1.0, 1.0, 1.0]))

print(model.config.suggested_init())

print(model.config.suggested_bounds())

print(model.config.suggested_fixed())

init_pars = model.config.suggested_init()
print(model.expected_actualdata(init_pars))

print(model.config.poi_index)

bkg_pars = [*init_pars] # my clever way to "copy" the list by value
bkg_pars[model.config.poi_index] = 0
model.expected_actualdata(bkg_pars)

observations = [52.5, 65.] + model.config.auxdata

bins = [0,1]

fig, ax = plt.subplots()
ax.bar(bins, background, 1.0, label=r'$t\bar{t}$', edgecolor='red', alpha=0.5)
ax.bar(bins, signal, 1.0, label=r'signal', edgecolor='blue', bottom=background, alpha=0.5)
ax.scatter(bins, observations[0:2], color='black', label='observed')
#ax.set_ylim(0,6)
ax.legend();

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

x = model.logpdf(pars = bkg_pars, data = observations)
print(x)

x = model.logpdf( pars = init_pars, data = observations)
print(x)

x = pyhf.infer.mle.fit(data = observations, pdf = model)
print(x)

CLs_obs, CLs_exp = pyhf.infer.hypotest( 1.0, # null hypothesis
                                        [52.5, 65.] + model.config.auxdata,
                                        model,
                                        return_expected_set = True
                                        )

print(f'      Observed CLs: {CLs_obs}')
for expected_value, n_sigma in zip(CLs_exp, np.arange(-2,3)):
    print(f'Expected CLs({n_sigma:2d} sigma): {expected_value}')

x = model.config.suggested_bounds()[model.config.poi_index]
print(x)

CLs_obs, CLs_exp = pyhf.infer.hypotest(
    1.0, # null hypothesis
    [52.5, 65.] + model.config.auxdata,
    model,
    return_expected_set = True,
    qtilde=True,
)

print(f'      Observed CLs: {CLs_obs}')
for expected_value, n_sigma in zip(CLs_exp, np.arange(-2,3)):
    print(f'Expected CLs({n_sigma:2d} sigma): {expected_value}')

poi_values = np.linspace(0.1, 5, 50)
results = [
    pyhf.infer.hypotest(
        poi_value,
        observations,
        model,
        return_expected_set=True,
        qtilde=True
    )
    for poi_value in poi_values
]

import pyhf.contrib.viz.brazil # not imported by default!
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
fig.set_size_inches(5, 3)
ax.set_title(u"Hypothesis Tests")
ax.set_xlabel(u"$\mu$")
ax.set_ylabel(u"$\mathrm{CL}_{s}$")

pyhf.contrib.viz.brazil.plot_results(ax, poi_values, results)

observed = np.asarray([h[0] for h in results]).ravel()
expected = np.asarray([h[1][2] for h in results]).ravel()
print(f'Upper limit (obs): mu = {np.interp(0.05, observed[::-1], poi_values[::-1])}')
print(f'Upper limit (exp): mu = {np.interp(0.05, expected[::-1], poi_values[::-1])}')

plt.show()


import pygame
from os import path

DECK = []

class Player:
    health = 20
    hand = []

class Card:
    def __init__(self, techtype, weakness, resistance, image_path):
        self.techtype = techtype
        self.weakness = weakness
        self.resistance = resistance
        self.image_path = image_path

annie_conda = Card('python', 'java', 'bash', "assets/AnnieConda.png")
bayo_wolf = Card('scratch', 'turtle', 'java', "assets/BayoWolf.png")
captain_javo = Card('java', 'scratch', 'python', "assets/CaptainJavo.png")


#!/usr/bin/env python

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
from collections import OrderedDict

class Wutp():

    def __init__(self, url):

        self.url = url

        uClient = uReq(url)
        html = uClient.read()
        uClient.close()

        self.parsed = soup(html, "html.parser")

    def convert(self, string):
        string = string.replace('\n', '').replace(u'\xa0', ' ')
        string = string.encode('ascii', 'ignore').decode('utf-8')
        return string

    def traverse(self):
        """ traverses a page and returns an ordered dict of headings as keys
        and corresponding points as values """

        content = self.parsed.findAll("table", {"class": 'mcnTextContentContainer'})

        news = OrderedDict()
        heading_list = []   # keeps tracks of added headings
        point_list = []     # keeps track of added points
        points = False      # keeps track of if a point or a heading
        current_heading = ''

        for index,c in enumerate(content):
            if points:
                all_points = c.findAll('li')

                # -- if there are lists use the text of lists
                if len(all_points) > 0:
                    for each_point in all_points:
                        nested_points = each_point.findAll('li')
                        # -- if there are nested lists get only the first span
                        # tag because the loop will grab the texts of the
                        # other lists later on
                        if len(nested_points) > 0:
                            first_tag = each_point.find('span')
                            point_list.append(first_tag.text)
                            news[current_heading].append(self.convert(first_tag.text))
                        # -- if no nested list just grab the text of the list
                        else:
                            point_list.append(each_point.text)
                            news[current_heading].append(self.convert(each_point.text))

                # -- if no lists but still after a heading, then just grab the text
                else:
                    if c.text not in point_list:
                        point_list.append(c.text)
                        news[current_heading].append(self.convert(c.text))

            # -- if it's a heading add it under headings
            if c['cellpadding'] == '18':
                if c.text not in heading_list:
                    heading_list.append(c.text)
                    current_heading = self.convert(c.text)
                    news[current_heading] = []
                # -- next iteration will be points
                points = True

            # -- need try and except for index out of range error
            try:
                if content[index+1]['cellpadding'] == '18':
                    # -- next iteration will be a heading
                    points = False
            except:
                pass

        # -- remove last item which is copyright footer
        news.popitem()

        self.news = news

        return news

    def get_headings(self):
        """ returns an array of the headings in the page """
        return [key for key in self.news]

    def get_points(self):
        ''' returns a two dimensional array with points of a heading at each
        index'''

        return [v for key,v in self.news.items()]

    @staticmethod
    def get_urls():
        """ returns a dictionary of issues with url title as key and url target
        as value """

        urls = {}

        base_url = 'http://us3.campaign-archive2.com/home/?u=4946817b18454973fb1cd7ecc&id=e81d77774f'

        uClient = uReq(base_url)
        html = uClient.read()
        uClient.close()

        archive_parsed = soup(html, "html.parser")

        all_lists = archive_parsed.findAll('li')

        for each_list in all_lists:
            link = each_list.find('a')
            link_target = link['href']
            urls[link.text]=link_target

        return urls

    @staticmethod
    def get_ordered_urls():
        """ returns an array of urls in order of date """
        urls = []

        base_url = 'http://us3.campaign-archive2.com/home/?u=4946817b18454973fb1cd7ecc&id=e81d77774f'

        uClient = uReq(base_url)
        html = uClient.read()
        uClient.close()

        archive_parsed = soup(html, "html.parser")

        all_lists = archive_parsed.findAll('li')

        for each_list in all_lists:
            link = each_list.find('a')
            link_target = link['href']
            urls.append(link_target)

        return urls

    @staticmethod
    def get_dates():
        """ returns an array of dates of published issues from newest to oldest
        """
        dates = []

        base_url = 'http://us3.campaign-archive2.com/home/?u=4946817b18454973fb1cd7ecc&id=e81d77774f'

        uClient = uReq(base_url)
        html = uClient.read()
        uClient.close()

        archive_parsed = soup(html, "html.parser")

        all_lists = archive_parsed.findAll('li')

        for each_list in all_lists:
            unformatted = each_list.text
            date = unformatted.split(' ')[0]
            dates.append(date)

        return dates

if __name__ == '__main__':
    url = 'http://us3.campaign-archive2.com/?u=4946817b18454973fb1cd7ecc&id=091f19cbd4'
    wutp = Wutp(url)
    wutp.traverse()

    print('------------------ HEADINGS ----------------------')
    print(wutp.get_headings())
    print('------------------ POINTS ------------------------')
    print(wutp.get_points())
    # print('------------------- CONTENT ----------------------')
    # print(wutp.get_content())
    # print('------------------- URLS -------------------------')
    # print(Wutp.get_urls())
    # print('-------------------- DATES ------------------------')
    # print(Wutp.get_dates())


from flask import Flask
from flask import request, jsonify
from flask_cors import CORS

app = Flask(__name__)
app.config["DEBUG"] = True

CORS(app)

@app.route('/', methods=['GET'])
def home():
    return "
App en funcionamiento
"

@app.route('/contact-form', methods=['POST'])
def get_form():
    print(request.json)
    return jsonify({'task': 'task'}), 200
app.run()


# coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold copyright, and consult the git log if you
# need to determine who owns an individual contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

from hypothesis.control import assume
from hypothesis.searchstrategy.strategies import SearchStrategy

class FixedStrategy(SearchStrategy):

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

    def do_draw(self, data):
        block = data.draw_bytes(self.block_size, self.distribution)
        assert len(block) == self.block_size
        value = self.from_bytes(block)
        assume(self.is_acceptable(value))
        return value

    def distribution(self, random, n):
        assert n == self.block_size
        for _ in range(100):
            value = self.draw_value(random)
            if self.is_acceptable(value):
                block = self.to_bytes(value)
                assert len(block) == self.block_size
                return block
        raise AssertionError(
            'After 100 tries was unable to draw a valid value. This is a bug '
            'in the implementation of %s.' % (type(self).__name__,))

    def draw_value(self, random):
        raise NotImplementedError('%s.draw' % (
            type(self).__name__,
        ))

    def to_bytes(self, value):
        raise NotImplementedError('%s.to_bytes' % (
            type(self).__name__,
        ))

    def from_bytes(self, value):
        raise NotImplementedError('%s.from_bytes' % (
            type(self).__name__,
        ))

    def is_acceptable(self, value):
        return True


from importlib import reload
import copy
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
import scipy.integrate

import cppimport.import_hook
import bem2d
import bem2d.newton_rate_state

bem2d = reload(bem2d)
plt.close("all")

# TODO: Try inclined fault
# TODO: Figure out how to enter boundary condition better?

# Constants and model parameters
OUTDIR = "/Users/meade/Desktop/output/"
NEWTON_TOL = 1e-12
MAXITER = 5000
ODE_ATOL = 1e-6
ODE_RTOL = 1e-6
N_NODES_PER_ELEMENT = 3
SPY = 365.25 * 24 * 60 * 60  # Seconds per year
TIME_INTERVAL = SPY * np.array([0.0, 1000.0])
PARAMETERS = {}
PARAMETERS["mu"] = 3e10
PARAMETERS["nu"] = 0.25
PARAMETERS["density"] = 2700  # rock density (kg/m^3)
PARAMETERS["cs"] = np.sqrt(
    PARAMETERS["mu"] / PARAMETERS["density"]
)  # Shear wave speed (m/s)
PARAMETERS["eta"] = PARAMETERS["mu"] / (
    2 * PARAMETERS["cs"]
)  # Radiation damping coefficient (kg / (m^2 * s))
PARAMETERS["d_c"] = 0.05  # state evolution length scale (m)
PARAMETERS["f_0"] = 0.6  # baseline coefficient of friction
PARAMETERS["block_velocity_x"] = 1e-9
PARAMETERS["block_velocity_y"] = 0
PARAMETERS["v_0"] = 1e-6  # reference velocity

# Create fault elements
N_ELEMENTS = 50
N_NODES = 3 * N_ELEMENTS
ELEMENTS_FAULT = []
ELEMENT = {}
L = 10000
x1, y1, x2, y2 = bem2d.discretized_line(-L, 0, L, 0, N_ELEMENTS)

for i in range(0, x1.size):
    ELEMENT["x1"] = x1[i]
    ELEMENT["y1"] = y1[i]
    ELEMENT["x2"] = x2[i]
    ELEMENT["y2"] = y2[i]
    ELEMENT["a"] = 0.015  # frictional a parameter ()
    ELEMENT["b"] = 0.020  # frictional b parameter ()
    ELEMENT["sigma_n"] = 50e6  # normal stress (Pa)
    ELEMENTS_FAULT.append(ELEMENT.copy())
ELEMENTS_FAULT = bem2d.standardize_elements(ELEMENTS_FAULT)

# Extract parameters for later use as arrays
ELEMENTS_FAULT_ARRAYS = {}
ELEMENTS_FAULT_ARRAYS["a"] = np.array(
    [np.tile(_["a"], 3) for _ in ELEMENTS_FAULT]
).flatten()
ELEMENTS_FAULT_ARRAYS["b"] = np.array(
    [np.tile(_["b"], 3) for _ in ELEMENTS_FAULT]
).flatten()
ELEMENTS_FAULT_ARRAYS["additional_normal_stress"] = np.array(
    [np.tile(_["sigma_n"], 3) for _ in ELEMENTS_FAULT]
).flatten()
ELEMENTS_FAULT_ARRAYS["element_normals"] = np.empty((N_ELEMENTS, 2))
ELEMENTS_FAULT_ARRAYS["element_normals"][:, 0] = np.array(
    [_["x_normal"] for _ in ELEMENTS_FAULT]
).flatten()
ELEMENTS_FAULT_ARRAYS["element_normals"][:, 1] = np.array(
    [_["y_normal"] for _ in ELEMENTS_FAULT]
).flatten()

# Calculate slip to traction partials on the fault
START_TIME = time.time()
_, SLIP_TO_STRESS, SLIP_TO_TRACTION = bem2d.quadratic_partials_all(
    ELEMENTS_FAULT, ELEMENTS_FAULT, PARAMETERS["mu"], PARAMETERS["nu"]
)
PARTIALS_TIME = time.time() - START_TIME

def calc_state(state, velocity):
    """ State evolution law : aging law """
    dstate_dt = (
        ELEMENTS_FAULT_ARRAYS["b"]
        * PARAMETERS["v_0"]
        / PARAMETERS["d_c"]
        * (
            np.exp((PARAMETERS["f_0"] - state) / ELEMENTS_FAULT_ARRAYS["b"])
            - (velocity / PARAMETERS["v_0"])
        )
    )
    return dstate_dt

def steady_state(velocities):  # Should I eliminate this since its only called once?
    """ Steady-state state for initial condition """
    state = scipy.optimize.fsolve(calc_state, 0.5 * np.ones(N_NODES), args=(velocities))
    return state

def calc_derivatives(t, x_and_state):
    """ Derivatives to feed to ODE integrator """
    state = x_and_state[2::3]
    x = np.empty(2 * N_NODES)
    x[0::2] = x_and_state[0::3]
    x[1::2] = x_and_state[1::3]

    # Current shear stress on fault (slip->traction)
    tractions = SLIP_TO_TRACTION @ x

    # Solve for the current velocity...This is the algebraic part
    current_velocity = np.empty(2 * N_NODES)
    bem2d.newton_rate_state.rate_state_solver(
        ELEMENTS_FAULT_ARRAYS["element_normals"],
        tractions,
        state,
        current_velocity,  # Modified in place and returns velocity solution
        ELEMENTS_FAULT_ARRAYS["a"],
        PARAMETERS["eta"],
        PARAMETERS["v_0"],
        0.0,
        ELEMENTS_FAULT_ARRAYS["additional_normal_stress"],
        NEWTON_TOL,
        MAXITER,
        N_NODES_PER_ELEMENT,
    )

    dx_dt = -current_velocity  # Is the negative sign for slip deficit convention?
    dx_dt[0::2] += PARAMETERS["block_velocity_x"]
    dx_dt[1::2] += PARAMETERS["block_velocity_y"]
    velocity_magnitude = np.linalg.norm(current_velocity.reshape((-1, 2)), axis=1)
    dstate_dt = calc_state(state, velocity_magnitude)
    derivatives = np.empty(3 * N_NODES)
    derivatives[0::3] = dx_dt[0::2]
    derivatives[1::3] = dx_dt[1::2]
    derivatives[2::3] = dstate_dt
    return derivatives

# Set initial conditions and time integrate
INITIAL_VELOCITY_X = 1e-3 * PARAMETERS["block_velocity_x"] * np.ones(N_NODES)
INITIAL_VELOCITY_Y = 1e-3 * PARAMETERS["block_velocity_y"] * np.ones(N_NODES)
INITIAL_VELOCITY_MAGNITUDE = np.sqrt(INITIAL_VELOCITY_X ** 2 + INITIAL_VELOCITY_Y ** 2)
INITIAL_CONDITIONS = np.empty(3 * N_NODES)
INITIAL_CONDITIONS[0::3] = INITIAL_VELOCITY_X
INITIAL_CONDITIONS[1::3] = INITIAL_VELOCITY_Y
INITIAL_CONDITIONS[2::3] = steady_state(INITIAL_VELOCITY_MAGNITUDE)

SOLVER = scipy.integrate.RK23(
    calc_derivatives,
    TIME_INTERVAL.min(),
    INITIAL_CONDITIONS,
    TIME_INTERVAL.max(),
    rtol=ODE_RTOL,
    atol=ODE_ATOL,
    vectorized=False,
)

START_TIME = time.time()
SOLUTION = {}
SOLUTION["t"] = [SOLVER.t]
SOLUTION["y"] = [SOLVER.y.copy()]
SOLUTION["stress"] = [np.zeros(3 * N_NODES)]

while SOLVER.t < TIME_INTERVAL.max():
    SOLVER.step()
    N_STEP = len(SOLUTION["t"])
    print(
        f"t = {SOLVER.t / SPY:05.6f}"
        + " of "
        + f"{TIME_INTERVAL.max() / SPY:05.6f}"
        + f" ({100 * SOLVER.t / TIME_INTERVAL.max():.3f}"
        + "%)"
        + f" {N_STEP} steps"
    )
    SOLUTION["t"].append(SOLVER.t)
    SOLUTION["y"].append(SOLVER.y.copy())

    # Calculate on fault stresses too
    x = np.empty(2 * N_NODES)
    x[0::2] = SOLVER.y[0::3]
    x[1::2] = SOLVER.y[1::3]
    stresses = SLIP_TO_STRESS @ x
    SOLUTION["stress"].append(stresses.copy())

SOLUTION["t"] = np.array(SOLUTION["t"])
SOLUTION["y"] = np.array(SOLUTION["y"])
# SOLUTION['u_x'] = SOLUTION['y'][:,0::2]
SOLUTION["stress"] = np.array(SOLUTION["stress"])
SOLVER_TIME = time.time() - START_TIME
print("Partials time: " + f"{PARTIALS_TIME:.2f}" + " (seconds)")
print("Solver time: " + f"{SOLVER_TIME:.2f}" + " (seconds)")

def plot_time_series():
    """ Plot time integrated time series for each node """
    plt.figure(figsize=(12, 9))
    plt.subplot(3, 2, 1)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["y"][:, 0::3], linewidth=0.5)
    plt.ylabel("$u_x$ (m)")

    plt.subplot(3, 2, 2)
    plt.plot(SOLUTION["y"][:, 0::3], linewidth=0.5)
    plt.ylabel("$u_x$ (m)")

    plt.subplot(3, 2, 3)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["y"][:, 1::3], linewidth=0.5)
    plt.ylabel("$u_y$ (m)")

    plt.subplot(3, 2, 4)
    plt.plot(SOLUTION["y"][:, 1::3], linewidth=0.5)
    plt.ylabel("$u_y$ (m)")

    plt.subplot(3, 2, 5)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["y"][:, 2::3], linewidth=0.5)
    plt.xlabel("time (years)")
    plt.ylabel("state")

    plt.subplot(3, 2, 6)
    plt.plot(SOLUTION["y"][:, 2::3], linewidth=0.5)
    plt.xlabel("steps")
    plt.ylabel("state")
    plt.suptitle("Displacement and state")
    plt.show(block=False)

plot_time_series()

def plot_time_series_velocity():
    """ Plot time integrated time series for each node """
    plt.figure(figsize=(12, 9))
    t_diff = SOLUTION["t"][0:-1]  # WHAAA???
    dt = np.diff(SOLUTION["t"])
    solution_diff = np.diff(SOLUTION["y"], axis=0) / dt[:, None]
    solution_diff = np.log10(np.abs(solution_diff))

    plt.subplot(3, 2, 1)
    plt.plot(t_diff / SPY, solution_diff[:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}v_x$ (m/s)")

    plt.subplot(3, 2, 2)
    plt.plot(solution_diff[:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}v_x$ (m/s)")

    plt.subplot(3, 2, 3)
    plt.plot(t_diff / SPY, solution_diff[:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}v_y$ (m/s)")

    plt.subplot(3, 2, 4)
    plt.plot(solution_diff[:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}v_y$ (m/s)")

    plt.subplot(3, 2, 5)
    plt.plot(t_diff / SPY, solution_diff[:, 2::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\theta}$ (1/s)")
    plt.xlabel("$t$ (years)")

    plt.subplot(3, 2, 6)
    plt.plot(solution_diff[:, 2::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\theta}$ (1/s)")
    plt.xlabel("step")
    plt.suptitle("Displacement and state rate changes")
    plt.show(block=False)

plot_time_series_velocity()

def plot_stress_time_series():
    """ Plot time integrated time series for each node """
    plt.figure(figsize=(12, 9))
    plt.subplot(3, 2, 1)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["stress"][:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\sigma_{xx}$ (Pa)")

    plt.subplot(3, 2, 2)
    plt.plot(SOLUTION["stress"][:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\sigma_{xx}$ (Pa)")

    plt.subplot(3, 2, 3)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["stress"][:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\sigma_{yy}$ (Pa)")

    plt.subplot(3, 2, 4)
    plt.plot(SOLUTION["stress"][:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\sigma_{yy}$ (Pa)")

    plt.subplot(3, 2, 5)
    plt.plot(SOLUTION["t"] / SPY, SOLUTION["stress"][:, 2::3], linewidth=0.5)
    plt.xlabel("time (years)")
    plt.ylabel(r"$\sigma_{xy}$ (Pa)")

    plt.subplot(3, 2, 6)
    plt.plot(SOLUTION["stress"][:, 2::3], linewidth=0.5)
    plt.xlabel("steps")
    plt.ylabel(r"$\sigma_{xy}$ (Pa)")
    plt.suptitle("Stresses")
    plt.show(block=False)

plot_stress_time_series()

def plot_stress_time_series_velocity():
    """ Plot time integrated time series for each node """
    t_diff = SOLUTION["t"][0:-1]  # WHAAA???
    dt = np.diff(SOLUTION["t"])
    solution_diff = np.diff(SOLUTION["stress"], axis=0) / dt[:, None]
    solution_diff = np.log10(np.abs(solution_diff))

    plt.figure(figsize=(12, 9))
    plt.subplot(3, 2, 1)
    plt.plot(t_diff / SPY, solution_diff[:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{xx}$ (Pa)")

    plt.subplot(3, 2, 2)
    plt.plot(solution_diff[:, 0::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{xx}$ (Pa)")

    plt.subplot(3, 2, 3)
    plt.plot(t_diff / SPY, solution_diff[:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{yy}$ (Pa)")

    plt.subplot(3, 2, 4)
    plt.plot(solution_diff[:, 1::3], linewidth=0.5)
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{yy}$ (Pa)")

    plt.subplot(3, 2, 5)
    plt.plot(t_diff / SPY, solution_diff[:, 2::3], linewidth=0.5)
    plt.xlabel("time (years)")
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{xy}$ (Pa)")

    plt.subplot(3, 2, 6)
    plt.plot(solution_diff[:, 2::3], linewidth=0.5)
    plt.xlabel("steps")
    plt.ylabel(r"$\log_{10}\dot{\sigma}_{xy}$ (Pa)")
    plt.suptitle("Stress rate changes")
    plt.show(block=False)

plot_stress_time_series_velocity()

def plot_invariants_time_series_velocity():
    """ Plot time integrated time series for each node """
    t_diff = SOLUTION["t"][0:-1]  # WHAAA???
    dt = np.diff(SOLUTION["t"])
    solution_diff = np.diff(SOLUTION["stress"], axis=0) / dt[:, None]

    # Calculate a few stress invariants
    I1 = solution_diff[:, 0::3] + solution_diff[:, 1::3]
    I2 = (
        solution_diff[:, 0::3] * solution_diff[:, 1::3] - solution_diff[:, 2::3] ** 2
    )  # 2nd invariant
    J2 = (I1 ** 2) / 3.0 - I2  # 2nd invariant (deviatoric)
    I1 = np.log(np.abs(I1))
    I2 = np.log(np.abs(I2))
    J2 = np.log(np.abs(J2))

    plt.figure(figsize=(12, 9))
    plt.subplot(3, 2, 1)
    plt.plot(t_diff / SPY, I1, linewidth=0.5)
    plt.ylabel(r"$\log_{10} \, |\dot{\mathrm{I}}_1|$ (Pa)")

    plt.subplot(3, 2, 2)
    plt.plot(I1, linewidth=0.5)
    plt.ylabel(r"$\log_{10}|\dot{\mathrm{I}}_1|$ (Pa)")

    plt.subplot(3, 2, 3)
    plt.plot(t_diff / SPY, I2, linewidth=0.5)
    plt.ylabel(r"$\log_{10} \, |\dot{\mathrm{I}}_2|$ (Pa$^2$)")

    plt.subplot(3, 2, 4)
    plt.plot(I2, linewidth=0.5)
    plt.ylabel(r"$\log_{10} \, |\dot{\mathrm{I}}_2|$ (Pa$^2$)")

    plt.subplot(3, 2, 5)
    plt.plot(t_diff / SPY, J2, linewidth=0.5)
    plt.xlabel("time (years)")
    plt.ylabel(r"$\log_{10} \, |\dot{\mathrm{J}}_2|$ (Pa$^2$)")

    plt.subplot(3, 2, 6)
    plt.plot(J2, linewidth=0.5)
    plt.xlabel("steps")
    plt.ylabel("$\log_{10} \, |\mathrm{\dot{J}}_2|$ (Pa$^2$)")
    plt.suptitle(r"Some stress invariant rate changes")
    plt.show(block=False)

plot_invariants_time_series_velocity()

def plot_slip_profile():
    """ Plot time integrated time series for each node """
    plot_times = np.floor(np.linspace(0, SOLUTION["y"].shape[0] - 1, 50)).astype(int)
    plot_x = np.array([_["x_integration_points"] for _ in ELEMENTS_FAULT]).flatten()
    plt.figure(figsize=(6, 9))
    y_labels = ["$u_x$ (m)", "$u_y$ (m)", "state"]
    for i, y_label in enumerate(y_labels):
        plt.subplot(3, 1, i + 1)
        for j in range(plot_times.size):
            plt.plot(plot_x, SOLUTION["y"][plot_times[j], i::3], linewidth=0.5)
        plt.ylabel(y_label)
    plt.xlabel("$x$ (m)")
    plt.show(block=False)

plot_slip_profile()

def plot_volume(time_idx, count):
    # Observation points for internal evaluation and visualization
    n_pts = 100
    x_plot = np.linspace(-25e3, 25e3, n_pts)
    y_plot = np.linspace(-25e3, 25e3, n_pts)
    x_plot, y_plot = np.meshgrid(x_plot, y_plot)
    x_plot = x_plot.flatten()
    y_plot = y_plot.flatten()
    obs_pts = np.array([x_plot, y_plot]).T.copy()

    def common_plot_elements():
        # Plot fault trace
        for element in ELEMENTS_FAULT:
            plt.plot(
                [element["x1"], element["x2"]],
                [element["y1"], element["y2"]],
                "-k",
                linewidth=1.0,
                zorder=50,
            )
        x_lim = np.array([x_plot.min(), x_plot.max()])
        y_lim = np.array([y_plot.min(), y_plot.max()])
        plt.xticks([x_lim[0], 0, x_lim[1]])
        plt.yticks([y_lim[0], 0, y_lim[1]])
        plt.gca().set_aspect("equal")
        plt.ylabel("$y$ (m)")

    # Internal evaluation for fault
    fault_slip = np.empty(2 * N_NODES)
    fault_slip[0::2] = SOLUTION["y"][time_idx, 0::3]
    fault_slip[1::2] = SOLUTION["y"][time_idx, 1::3]
    displacement_from_fault, stress_from_fault = bem2d.integrate(
        obs_pts, ELEMENTS_FAULT, PARAMETERS["mu"], PARAMETERS["nu"], "slip", fault_slip
    )

    fault_slip_prev = np.empty(2 * N_NODES)
    fault_slip_prev[0::2] = SOLUTION["y"][time_idx - 1, 0::3]
    fault_slip_prev[1::2] = SOLUTION["y"][time_idx - 1, 1::3]
    displacement_from_fault_prev, stress_from_fault_prev = bem2d.integrate(
        obs_pts,
        ELEMENTS_FAULT,
        PARAMETERS["mu"],
        PARAMETERS["nu"],
        "slip",
        fault_slip_prev,
    )

    # Backward difference to get velocities
    dt = SOLUTION["t"][time_idx] - SOLUTION["t"][time_idx - 1]
    displacement_from_fault = (
        displacement_from_fault_prev - displacement_from_fault
    ) / dt
    stress_from_fault_ = (stress_from_fault_prev - stress_from_fault) / dt

    ux_plot = displacement_from_fault[0, :]
    uy_plot = displacement_from_fault[1, :]
    u_plot_field = np.sqrt(ux_plot ** 2 + uy_plot ** 2)  # displacement magnitude
    u_plot_field = np.log10(u_plot_field)

    sxx_plot = stress_from_fault_[0, :]
    syy_plot = stress_from_fault_[1, :]
    sxy_plot = stress_from_fault_[2, :]
    I1 = sxx_plot + syy_plot  # 1st invariant
    I2 = sxx_plot * syy_plot - sxy_plot ** 2  # 2nd invariant
    J2 = (I1 ** 2) / 3.0 - I2  # 2nd invariant (deviatoric)
    s_plot_field = np.log10(np.abs(J2))

    contour_vec_1 = np.arange(-10, 2, 0.25)
    plt.figure(figsize=(8, 8))
    plt.subplot(2, 1, 1)
    plt.contourf(
        x_plot.reshape(n_pts, n_pts),
        y_plot.reshape(n_pts, n_pts),
        u_plot_field.reshape(n_pts, n_pts),
        # n_contours,
        contour_vec_1,
        extend="both",
        cmap=plt.get_cmap("plasma"),
    )
    plt.colorbar(fraction=0.046, pad=0.04, extend="both", label="$||v_i||$ (m)")
    plt.contour(
        x_plot.reshape(n_pts, n_pts),
        y_plot.reshape(n_pts, n_pts),
        u_plot_field.reshape(n_pts, n_pts),
        # n_contours,
        contour_vec_1,
        extend="both",
        linewidths=0.25,
        colors="k",
    )
    common_plot_elements()
    plt.gca().set_aspect("equal")

    n_contours = 20
    # contour_vec_2 = np.arange(-10, 11, 1)
    contour_vec_2 = np.arange(-20, 41, 1)

    plt.subplot(2, 1, 2)
    plt.contourf(
        x_plot.reshape(n_pts, n_pts),
        y_plot.reshape(n_pts, n_pts),
        s_plot_field.reshape(n_pts, n_pts),
        contour_vec_2,
        # n_contours,
        extend="both",
        cmap=plt.get_cmap("hot_r"),
    )
    plt.colorbar(
        fraction=0.046,
        pad=0.04,
        extend="both",
        label="$\log_{10} \, |\dot{\mathrm{J}}_2|$ (Pa$^2$)",
    )
    plt.contour(
        x_plot.reshape(n_pts, n_pts),
        y_plot.reshape(n_pts, n_pts),
        s_plot_field.reshape(n_pts, n_pts),
        contour_vec_2,
        # n_contours,
        extend="both",
        linewidths=0.25,
        colors="k",
    )
    common_plot_elements()
    plt.gca().set_aspect("equal")
    plt.xlabel("$x$ (m)")
    current_time = SOLUTION["t"][time_idx] / SPY
    plt.suptitle("t = " + f"{current_time:.4f}" + " (years)")
    # f"{SOLVER_TIME:.2f}" + " (seconds)")

    plt.show(block=False)
    print("Writing: " + OUTDIR + str(count).zfill(7) + ".png")
    plt.savefig(OUTDIR + str(count).zfill(7) + ".png")
    plt.close("all")

# n_frames = 50
# plot_idx = np.floor(np.linspace(1, SOLUTION["y"].shape[0] - 1, n_frames)).astype(int)
# plot_idx = np.floor(np.linspace(1, SOLUTION["y"].shape[0] - 1, n_frames)).astype(int)
# plot_idx = np.arange(1, SOLUTION["t"].size, 2)
# plot_idx = np.arange(10000, 29000, 100)
# for i in range(0, plot_idx.size):
#     plot_volume(plot_idx[i], i)

# # Convert .pngs to .mp4
# # TODO: make Quicktime compatible
# mp4_name = OUTDIR + str(time.time()) + ".mp4"
# png_name = OUTDIR + "%07d.png"
# convert_command = (
#     "ffmpeg -framerate 10 -i "
#     + png_name
#     + " -c:v libx264 -r 30 -y -v 32 -loglevel panic "
#     + mp4_name
# )
# os.system(convert_command)


'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''

# Bitcoin Cash (BCH)   qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk
# Ether (ETH) -        0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB
# Litecoin (LTC) -     Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu
# Bitcoin (BTC) -      34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd

# contact :- github@jamessawyer.co.uk

"""
Problem:
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder.

What is the smallest positive number that is evenly divisible(divisible with no
remainder) by all of the numbers from 1 to N?
"""

def solution(n):
    """Returns the smallest positive number that is evenly divisible(divisible
    with no remainder) by all of the numbers from 1 to n.

    >>> solution(10)
    2520
    >>> solution(15)
    360360
    >>> solution(20)
    232792560
    >>> solution(22)
    232792560
    >>> solution(3.4)
    6
    >>> solution(0)
    Traceback (most recent call last):
        ...
    ValueError: Parameter n must be greater or equal to one.
    >>> solution(-17)
    Traceback (most recent call last):
        ...
    ValueError: Parameter n must be greater or equal to one.
    >>> solution([])
    Traceback (most recent call last):
        ...
    TypeError: Parameter n must be int or passive of cast to int.
    >>> solution("asd")
    Traceback (most recent call last):
        ...
    TypeError: Parameter n must be int or passive of cast to int.
    """
    try:
        n = int(n)
    except (TypeError, ValueError) as e:
        raise TypeError("Parameter n must be int or passive of cast to int.")
    if n <= 0:
        raise ValueError("Parameter n must be greater or equal to one.")
    i = 0
    while True:
        i += n * (n - 1)
        nfound = 0
        for j in range(2, n):
            if i % j != 0:
                nfound = 1
                break
        if nfound == 0:
            if i == 0:
                i = 1
            return i

if __name__ == "__main__":
    print(solution(int(input().strip())))


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

plt.figure(figsize=(17, 5))

img = cv2.imread('hand.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height = img.shape[0]
width = img.shape[1]
plt.subplot(1, 3, 1)
plt.imshow(img)
plt.axis('off')
plt.title('original')

# OpenCV를 이용한 변환 행렬 도출
center = (width / 2, height / 2)
cv_M = cv2.getRotationMatrix2D(center, 90, 1.0)  # 회전 방향이 반시계방향(CCW; Counter Clock-Wise)
cv_result = cv2.warpAffine(img, cv_M, (width, height))
print('>> OpenCV Rotation matrix')
print(cv_M, end='\n\n')

plt.subplot(1, 3, 2)
plt.imshow(cv_result)
plt.axis('off')
plt.title('cv_result')

theta = np.deg2rad(90)
my_m = np.array([[1,0,-width/2],[0,1,-height/2],[0,0,1]])
my_m = np.array([[np.cos(theta),np.sin(theta),1],[-np.sin(theta),np.cos(theta),1],[0,0,1]]).dot(my_m)
my_m = np.array([[1,0,width/2],[0,1,height/2],[0,0,1]]).dot(my_m)

print('>> My matrix')
print(my_m[:2])
my_result = cv2.warpAffine(img, my_m[:2], (width, height))

plt.subplot(1, 3, 3)
plt.imshow(my_result)
plt.axis('off')
plt.title('my_result')

# figure 출력
plt.tight_layout()
plt.show()


handler = open('a.txt', 'r')
words = handler.read().split()
handler.close()
mp = {}

for i in words:
    if i not in mp:
        mp[i]=1
    else:
        mp[i]+=1

ss=list(mp.items())
ss.sort(key = lambda x : x[1],  reverse=True )
for  x  in  ss:
   print (x[0])


"""Рекурсия против цикла
Вывод чисел по убыванию, начиная с текущего и до нуля
"""

def count_cycle(i):
    """Цикл"""
    while i >= 0:
        print(i)
        i -= 1

count_cycle(3)

def count_recur(i):
    """Рекурсия"""
    print(i)
    # базовый случай (шаг завершения рекурс. вызовов)
    if i <= 0:
        return
    # рекурсивный случай (вызов ф-ции из себя)
    count_recur(i-1)

count_recur(3)

"""
1. Написать базовый случай
2. Написать шаг рекурсии
3. ПРАВИЛЬНО! определить как изменятся входные аргументы в рекурсивных вызовах
"""

Урок 2. Практическое задание/Урок 2. Коды примеров/task_2.py


n = int(input())
data = []
for i in range(n):
    data.append(list(map(int, input().split())))
ans = 0
prex = -1 * 10**10
data.sort()
print(data)
for i in range(n):
    x, l = data[i]
    print(x,l)
    if prex <= x - l:
        prex = x + l
    else:
        ans += 1
        prex = min(prex, x+l)
print(n-ans)


import services.controlers.loggControler
import services.querys.formIncidentQuery
from services.models.formIncidentModel import *
from services.exceptions import *
import time
import datetime
from datetime import datetime
import os
import hashlib
import re
import cgi
import urllib
import json
from google.appengine.ext import db

class FormIncidentsControler:

	def get(self):
		state = 300
		formList=[]
		try:
			formIncidentQuery = services.querys.formIncidentQuery.FormIncidentQuery()
			formsObj = formIncidentQuery.getAll()
			for formObj in formsObj:
				formObj = formObj.toDictFront()
				strFormJson = json.JSONEncoder().encode(formObj)
				formList.append(strFormJson)
			state = OK
		except Exception as e:
			MESSAGE =  e.message
			loggControler = services.controlers.loggControler.LoggControler()
			loggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)
		return state, formList

	def getById(self, identifier):
		state = 300
		form={}
		try:
			formIncidentQuery = services.querys.formIncidentQuery.FormIncidentQuery()
			formObj = formIncidentQuery.getById(identifier)
			form = formObj.toDictFront()
			state = OK
		except Exception as e:
			loggControler = services.controlers.loggControler.LoggControler()
			loggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)
		return state, form

	def add(self, formJson):
		messageTrans="FORMULARIO_INCIDENTE_NO_REGISTRADO"
		state = 300
		data = {}
		try:
			doRegister = True
			form = formJson

			# Verifica si ya existe ese tipo de formulario. Si no, hace el correspondiente registro.
			formTypeQuery = services.querys.formTypeQuery.FormTypeQuery()
			fields = self.toStrFields(form)

			# Crea una instancia de formulario con los campos estaticos definidos
			formObj = FormIncident(formJson=json.JSONEncoder().encode(formJson))

			# Agrega los campos dinamicos al modelo
			formIncidentQuery = services.querys.formIncidentQuery.FormIncidentQuery()
			for fieldName in fields.split(","):
				val = db.TextProperty()
				val = form[fieldName]
				setattr(formObj, fieldName, val)
				#setattr(formObj, fieldName, db.Text(form[fieldName]))

			# Registra el formulario
			if doRegister == True:
				state, idForm = formIncidentQuery.addObj(formObj)
				if state == OK:
					messageTrans="FORMULARIO_INCIDENTE_REGISTRADO"
					data["formDatastoreId"] = str(idForm)
		except Exception as e:
			loggControler = services.controlers.loggControler.LoggControler()
			loggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)
		return messageTrans, state, data

	def edit(self, formJson):
		messageTrans="FORMULARIO_INCIDENTE_NO_REGISTRADO"
		state = 300
		try:
			doRegister = True
			form = formJson

			# Verifica si ya existe ese tipo de formulario. Si no, hace el correspondiente registro.
			formTypeQuery = services.querys.formTypeQuery.FormTypeQuery()
			fields = self.toStrFields(form)

			# Crea una instancia de formulario con los campos estaticos definidos
			formObj = FormIncident(formJson=formJson)

			# Agrega los campos dinamicos al modelo
			formIncidentQuery = services.querys.formIncidentQuery.FormIncidentQuery()
			for fieldName in fields.split(","):
				setattr(formObj, fieldName, db.Text(form[fieldName]))

			# Registra el formulario
			if doRegister == True:
				state1, idForm = formIncidentQuery.addObj(formObj)
				if state1 == OK:
					messageTrans="FORMULARIO_INCIDENTE_REGISTRADO"
					state=300

		except Exception as e:
			loggControler = services.controlers.loggControler.LoggControler()
			loggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)
		return messageTrans, state

	def toStrFields(self, form):
		fieldsList = sorted(list(form.keys()), reverse=False)
		fields = ""
		count = 0
		for field in fieldsList:
			if count > 0:
				fields += ","
			fields += field
			count+=1
		return fields

	def isDynamicField(self, fieldName):
		return (fieldName != "id" and fieldName != "name" and fieldName != "version" and fieldName != "date" and fieldName != "hour")


from sklearn.metrics import r2_score, mean_squared_error
import numpy as np
from ExtractResult import Result
from LASSOModel import Shooting, LASSOEstimator
from utility import assign_weights, get_current_data, compute_weightedLASSO, get_beta_div_zeros, print_features_active, \
    compute_lasso
import sys

sys.argv[1:] = [str(x) for x in sys.argv[1:]]
file_name = sys.argv[1]
file_name_dict = sys.argv[2]
ext = ".npz"
file = "ENEL_2014/"+file_name+ext

file_dict = "ENEL_2014/"+file_name_dict+ext

results_dict = Result(file_dict, "lasso")
results = Result(file, "lasso")

#dict_ = results.extract_dict()
dict_ = results_dict.extract_dict()

XTrain, YTrain, XVal, YVal = results.extract_train_val()

new_loss, beta = compute_lasso(XTrain, YTrain, XVal, YVal,score = "mean_squared_error")
print("loss lineare", new_loss)

score = "mean_squared_error"
if score=="r2_score":
    score_f = r2_score
    scoring = "r2"
else:
    score_f = mean_squared_error
    scoring = "mean_squared_error"

verbose = True

###compute ranking

weights_data = results.extract_weights()

index_mse = len(weights_data) - 1
weights_data = weights_data[index_mse]
weights = assign_weights(weights_data.copy())

keys_ = np.array(list(dict_.keys())).astype("int64")
original_features = len(keys_)
final_weights = np.zeros(original_features)

for key in keys_:
    final_weights[key] += np.sum(weights_data[dict_.get(key).astype("int64")])

ordered_final_weights = np.argsort(final_weights)[::-1]
if verbose:
    print("-------------")
    print("ranking of the featues:", ordered_final_weights)
    print("-------------")
ordered_indexes = np.argsort(weights_data)[::-1]
losses = []

#new_loss, _ = compute_lasso(XTrain, YTrain, XVal, YVal, score)

#print("new_loss", new_loss)

losses = []
indexes_tot = []
n_features = len(ordered_final_weights)

for i in range(n_features):

        ###compute LASSO
        indexes = []
        for k in ordered_final_weights[:i+1]:
            indexes = np.union1d(indexes,dict_.get(k))

        del_ = np.array([], dtype = "int64")
        for key in ordered_final_weights[:i+1]:
            for key_1 in ordered_final_weights[i+1:]:
                    del_ = np.append(del_,np.intersect1d((list)(dict_.values())[key], (list)(dict_.values())[key_1]))

        a = np.in1d(indexes,del_)
        indexes = np.delete(indexes, np.where(a==True)[0])

        indexes = indexes.astype("int64")
        XTrain_current, XTest_current = get_current_data(XTrain, XVal, indexes)

        print("----------------------------")
        print("iteration ", i)

        keys_sel = ordered_final_weights[:i+1]

        weights_ = weights[indexes]

        model = Shooting(weights_)
        lasso = LASSOEstimator(model)

        loss, beta = compute_weightedLASSO(lasso,XTrain_current,YTrain, XTest_current, YVal,scoring, score_f, verbose)
        losses.append(loss)

        beta = np.abs(beta)
        beta_indexes,beta_ordered = get_beta_div_zeros(beta)

        print(indexes[beta_indexes])
        print_features_active(keys_sel, indexes[beta_indexes], dict_)

        np.savez(file_name+"ranking"+ext, mses = losses, indexes = indexes_tot)

print("min mse", np.min(losses), "with:", indexes_tot(np.argmin(losses)))


import ua_parser.user_agent_parser as ua
import pyspark.sql
from pyspark.sql import functions as fun
import pyspark.sql.types as types

def change_headers(data, new_headers):
    """
    Changes the headers to the recived headers set
    :param data: Dataframe to change headers
    :param new_headers: List of headers
    :return:
    """
    if len(data.columns) != len(new_headers):
        raise IndexError("Column length is different. DF length is %s passed headers legth is %s" % (len(data.columns),
                                                                                len(new_headers)))
    rename = [fun.col(data.columns[i]).alias(new_headers[i]) for i in range(len(data.columns))]
    return data.select(*rename)

def null_udf():
    return fun.udf(lambda: None, types.StringType())

def ip_address(headers_array):

    """
    selects the ip address header from the set of headers
    :param headers_array: List of headers
    :return: String user agent string
    """

    for header in headers_array:
        if header.lower().startswith("x-forwarded-for:"):
            return header.lower().replace("x-forwarded-for:", "")
    return ""

def map_agent(user_agent):
    """
    Falattens the user agent dictionary into a Spark row and truncates cells
    :param user_agent: String user agent header
    ##:return: pyspark.sql.Row
    """
    ua_dict = ua.Parse(user_agent)
    result = {
        'user_agent_id': ua_dict['string'],
        'device_brand': (ua_dict['device']['brand'] or '').replace("\"", "")[:100],
        'device_family': (ua_dict['device']['family'] or '').replace("\"", "")[:50],
        'device_model': (ua_dict['device']['model'] or '').replace("\"", "")[:100],
        'os_family': (ua_dict['os']['family'] or '').replace("\"", "")[:50],
        'os_version': (ua_dict['os']['major'] or '').replace("\"", "")[:100],
        'browser_family': (ua_dict['user_agent']['family'] or '').replace("\"", "")[:50],
        'browser_version': (ua_dict['user_agent']['major'] or '').replace("\"", "")[:100],
        'app_version': '',
        'gps_lat': '',
        'gps_long': ''
    }

    if 'appver' in user_agent:
        tokens = [kv.strip().split('=') for kv in user_agent.split(';')]
        items = {item[0]: item[-1] for item in tokens}
        appver = items.get('appver', '')
        # Truncate sometimes devs put dates in this field
        result['app_version'] = appver[:20]

        gps_tokens = items.get('gps', ',').split(',')
        if len(gps_tokens) == 2:
            result['gps_lat'] = gps_tokens[0]
            result['gps_long'] = gps_tokens[1]

    return pyspark.sql.Row(**result)

def user_agent_header(headers_array):
    """
    selects the user agenet header from the set of headers
    :param headers_array: List of headers
    :return: String user agent string
    """
    for header in headers_array:
        if header.startswith("User-Agent:"):
            # Truncate string so it will fit in the Redshift schema
            return header.replace("User-Agent:", "")[:512]
    return ""


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

import sqlite3
import os

class Database():
    def __init__(self, filename="address_book.db"):
        self.dbfilename = filename
        if os.path.exists(self.dbfilename):
            #print("Dosya mevcut olduğu için yeni dosya oluşturulmadı!")
            pass
        else:
            print("Database dosyası oluşturuldu!")
            db = sqlite3.connect(self.dbfilename)
            db.execute('PRAGMA encoding="UTF-8"')
            c = db.cursor()
            c.execute(
                "CREATE TABLE IF NOT EXISTS records\
                (record_id INTEGER PRIMARY KEY, \
                name TEXT, \
                last_name TEXT, \
                phone_number TEXT, \
                email_address TEXT \
                )")
            db.commit()
            c.close()

    def truncate(self):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.executescript("DELETE FROM records; VACUUM;")
        db.commit()
        c.close()

    def add_record(self, name='', last_name='', phone_number='', email_address=''):
        db = sqlite3.connect(self.dbfilename)
        # db.text_factory = lambda x: unicode(x, 'utf-8', 'ignore') #It converts strings into unicode objects.
        # name=name.decode('utf8')
        # last_name=last_name.decode('utf8')

        c = db.cursor()
        c.execute("INSERT INTO records(name, last_name, phone_number, email_address) VALUES (?,?,?,?)",
                  (name, last_name, phone_number, email_address))
        db.commit()
        c.close()

    def update_record(self, id, name, last_name, phone_number, email_address):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute("UPDATE records SET name=?, last_name=?, phone_number=?, email_address=? WHERE record_id=?",
                  (name, last_name, phone_number, email_address, id))
        db.commit()
        c.close()

    def delete_record(self, record_id):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute('DELETE FROM records WHERE record_id = ?', (record_id,))
        db.commit()
        c.close()

    def list_all(self, ):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute('SELECT * FROM records')
        records = c.fetchall()
        c.close()
        return records

    def fromid(self, id):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute("SELECT * FROM records WHERE record_id=?", (id,))
        records = c.fetchall()
        c.close()
        return records

    def fromname(self, ad):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute("SELECT * FROM records WHERE name LIKE ? OR last_name LIKE ?", ("%" + ad + "%", "%" + ad + "%"))
        records = c.fetchall()
        c.close()
        return records

    def fromphone(self, phone):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute("SELECT * FROM records WHERE phone_number LIKE ?", ("%" + phone + "%",))
        records = c.fetchall()
        c.close()
        return records

    def fromemail(self, email):
        db = sqlite3.connect(self.dbfilename)
        c = db.cursor()
        c.execute("SELECT * FROM records WHERE email_address LIKE ?", ("%" + email + "%",))
        records = c.fetchall()
        c.close()
        return records

016-Python Uygulamalar/Adres Defteri with Tkinter/Database.py


from __future__ import division, absolute_import, print_function

from os.path import join, sep, dirname

import pytest

from numpy.distutils.misc_util import (
    appendpath, minrelpath, gpaths, get_shared_lib_extension, get_info, Configuration
    )
from numpy.testing import (
    assert_, assert_equal, assert_raises
    )

ajoin = lambda *paths: join(*((sep,)+paths))

class TestAppendpath(object):

    def test_1(self):
        assert_equal(appendpath('prefix', 'name'), join('prefix', 'name'))
        assert_equal(appendpath('/prefix', 'name'), ajoin('prefix', 'name'))
        assert_equal(appendpath('/prefix', '/name'), ajoin('prefix', 'name'))
        assert_equal(appendpath('prefix', '/name'), join('prefix', 'name'))

    def test_2(self):
        assert_equal(appendpath('prefix/sub', 'name'),
                     join('prefix', 'sub', 'name'))
        assert_equal(appendpath('prefix/sub', 'sup/name'),
                     join('prefix', 'sub', 'sup', 'name'))
        assert_equal(appendpath('/prefix/sub', '/prefix/name'),
                     ajoin('prefix', 'sub', 'name'))

    def test_3(self):
        assert_equal(appendpath('/prefix/sub', '/prefix/sup/name'),
                     ajoin('prefix', 'sub', 'sup', 'name'))
        assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sup/sup2/name'),
                     ajoin('prefix', 'sub', 'sub2', 'sup', 'sup2', 'name'))
        assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'),
                     ajoin('prefix', 'sub', 'sub2', 'sup', 'name'))

class TestMinrelpath(object):

    def test_1(self):
        n = lambda path: path.replace('/', sep)
        assert_equal(minrelpath(n('aa/bb')), n('aa/bb'))
        assert_equal(minrelpath('..'), '..')
        assert_equal(minrelpath(n('aa/..')), '')
        assert_equal(minrelpath(n('aa/../bb')), 'bb')
        assert_equal(minrelpath(n('aa/bb/..')), 'aa')
        assert_equal(minrelpath(n('aa/bb/../..')), '')
        assert_equal(minrelpath(n('aa/bb/../cc/../dd')), n('aa/dd'))
        assert_equal(minrelpath(n('.././..')), n('../..'))
        assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd'))

class TestGpaths(object):

    def test_gpaths(self):
        local_path = minrelpath(join(dirname(__file__), '..'))
        ls = gpaths('command/*.py', local_path)
        assert_(join(local_path, 'command', 'build_src.py') in ls, repr(ls))
        f = gpaths('system_info.py', local_path)
        assert_(join(local_path, 'system_info.py') == f[0], repr(f))

class TestSharedExtension(object):

    def test_get_shared_lib_extension(self):
        import sys
        ext = get_shared_lib_extension(is_python_ext=False)
        if sys.platform.startswith('linux'):
            assert_equal(ext, '.so')
        elif sys.platform.startswith('gnukfreebsd'):
            assert_equal(ext, '.so')
        elif sys.platform.startswith('darwin'):
            assert_equal(ext, '.dylib')
        elif sys.platform.startswith('win'):
            assert_equal(ext, '.dll')
        # just check for no crash
        assert_(get_shared_lib_extension(is_python_ext=True))

class TestAddData(object):

    def test_data_dir_raises(self):
        """
        Test that invalid input to the method raises the correct TypeError.
        """

        config = Configuration()
        with pytest.raises(TypeError) as exepinfo:
            config.add_data_dir(0)

        assert_(str(exepinfo.value) == 'not a string: 0')

    def test_data_files_raises(self):
        """
        Test that invalid input to the method raises the correct TypeError.
        """

        config = Configuration()
        with pytest.raises(TypeError) as exepinfo:
            config.add_data_files(0)
        expected_return = 'expected str, bytes or os.PathLike object, not int'

        assert_(str(exepinfo.value) == expected_return)

def test_installed_npymath_ini():
    """
    Regression test for gh-7707.  If npymath.ini wasn't installed, then this
    will give an error.
    """
    info = get_info('npymath')

    assert isinstance(info, dict)
    assert "define_macros" in info

def test_add_data_files_TypeError():
    # ensures that if called a none value, add_data_files raises exception
    c = Configuration()
    with assert_raises(TypeError):
         c.add_data_files(None)

def test_add_data_dir():
    """
    Mocks a config object with empty data_files
    ensures that no data is added and no exceptions are rasied
    """
    class mock(Configuration):
        def get_distribution(self):
            return mockDist()
    class mockDist():
        datafiles = "something"
        data_files = []

    c = mock()
    c.add_data_dir('fun')
    assert_equal([], c.data_files)

def test_add_data_files():
    """
    Mocking a config object with get_dist returns None
    ensures that no errors are raised and empty file is added
    """
    class mock(Configuration):
        def get_distribution(self):
            return None

    c = mock()
    c.add_data_files('fun')
    assert_equal([('', [])], c.data_files)


from __future__ import absolute_import, division, print_function

import datasets

_DESCRIPTION = """\

"""
_URL = "https://www.gutenberg.org/files/2554/2554-h/2554-h.htm"
_DATA_URL = "https://raw.githubusercontent.com/patrickvonplaten/datasets/master/crime_and_punishment.txt"

class CrimeAndPunishConfig(datasets.BuilderConfig):
    """BuilderConfig for Crime and Punish."""

    def __init__(self, data_url, **kwargs):
        """BuilderConfig for BlogAuthorship

        Args:
          data_url: `string`, url to the dataset (word or raw level)
          **kwargs: keyword arguments forwarded to super.
        """
        super(CrimeAndPunishConfig, self).__init__(
            version=datasets.Version(
                "1.0.0",
            ),
            **kwargs,
        )
        self.data_url = data_url

class CrimeAndPunish(datasets.GeneratorBasedBuilder):

    VERSION = datasets.Version("0.1.0")
    BUILDER_CONFIGS = [
        CrimeAndPunishConfig(
            name="crime-and-punish",
            data_url=_DATA_URL,
            description="word level dataset. No processing is needed other than replacing newlines with <eos> tokens.",
        ),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # datasets.features.FeatureConnectors
            features=datasets.Features(
                {
                    "line": datasets.Value("string"),
                }
            ),
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            homepage=_URL,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""

        if self.config.name == "crime-and-punish":
            data = dl_manager.download_and_extract(self.config.data_url)

            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"data_file": data, "split": "train"},
                ),
            ]
        else:
            raise ValueError("{} does not exist".format(self.config.name))

    def _generate_examples(self, data_file, split):

        with open(data_file, "rb") as f:
            id_counter = 0
            add_text = False
            crime_and_punishment_occ_counter = 0

            for line in f:
                line = line.decode("UTF-8")
                if "CRIME AND PUNISHMENT" in line:
                    crime_and_punishment_occ_counter += 1
                    add_text = crime_and_punishment_occ_counter == 3
                if "End of Project" in line:
                    add_text = False

                if add_text is True:
                    result = {"line": line}
                    id_counter += 1
                    yield id_counter, result


'''
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
'''
from typing import List
class Solution(object):
    # O(N)
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        memo = {}
        for i, n in enumerate(nums):
            if target - n in memo:
                return [memo[target-n], i]
            else:
                memo[n] = i

import unittest
functions = [Solution().__getattribute__(f) for f in dir(Solution()) if not f.startswith('__')]
class Test(unittest.TestCase):
    def test1(self):
        for f in functions:
            self.assertEqual(f(nums = [2,7,11,15], target = 9), [0,1], f.__name__)
unittest.main()


#!/usr/bin/env python
import json
import boto3

from time import sleep
from datetime import datetime, timedelta

def ft(tags):
    return {tag["Key"]: tag["Value"] for tag in tags}

def get_instances(ec2, name_filter):
    filters = [
        {"Name": "instance-state-name", "Values": ["running"]},
        {"Name": "tag:Name", "Values": [name_filter]},
    ]
    return [
        i
        for r in ec2.describe_instances(Filters=filters)["Reservations"]
        for i in r["Instances"]
    ]

def get_instances(ec2, name_filter):
    filters = [
        {"Name": "instance-state-name", "Values": ["running"]},
        {"Name": "tag:Name", "Values": [name_filter]},
    ]
    return [
        i
        for r in ec2.describe_instances(Filters=filters)["Reservations"]
        for i in r["Instances"]
    ]

def get_instance_ips_by_group(profile, region, group):
    ec2 = boto3.session.Session(profile_name=profile, region_name=region).client("ec2")
    filters = [
        {"Name": "instance-state-name", "Values": ["running"]},
        {"Name": "tag:group", "Values": [group]},
    ]
    return {
        i["InstanceId"]: i["PrivateDnsName"]
        for r in ec2.describe_instances(Filters=filters)["Reservations"]
        for i in r["Instances"]
    }

def get_asg(profile, region, name):
    asg = boto3.session.Session(profile_name=profile, region_name=region).client(
        "autoscaling"
    )

def refresh_alertmanagers(deploys):
    alertmanagers = {}
    for profile, regions in deploys.items():
        alertmanagers[profile] = {}
        for region in regions:
            alrtmgrs = get_instance_ips_by_group(profile, region, "alertmanager")
            alertmanagers[profile][region] = alrtmgrs
    return alertmanagers

def get_session(account_number, region):
    session = boto3.Session()
    sts = session.client("sts")
    if "cn-" in region:
        RoleArn = "arn:aws-cn:iam::{}:role/janrain/roles/janrain-admins".format(
            account_number
        )
    else:
        RoleArn = "arn:aws:iam::{}:role/janrain/roles/janrain-admins".format(
            account_number
        )
    assumed_role = sts.assume_role(RoleArn=RoleArn, RoleSessionName=account_number)
    return boto3.Session(
        aws_access_key_id=assumed_role["Credentials"]["AccessKeyId"],
        aws_secret_access_key=assumed_role["Credentials"]["SecretAccessKey"],
        aws_session_token=assumed_role["Credentials"]["SessionToken"],
        region_name=region,
    )

def summarize_instances(instances):
    results = []
    for i in instances:
        if "KeyName" not in i:
            key_name = None
        else:
            key_name = i["KeyName"]
        if (
            "Name" in ft(i["Tags"])
            and "zookeeper-ec2-storage" not in ft(i["Tags"])['Name']
            and "logs-ec2-storage" not in ft(i["Tags"])['Name']
            and "keep_me" not in ft(i["Tags"])
        ):
            results.append(
                {
                    "InstanceId": i["InstanceId"],
                    "LaunchTime": datetime.strftime(i["LaunchTime"], "%Y-%m-%d"),
                    "VpcId": i["VpcId"],
                    "Tags": ft(i["Tags"]),
                    "KeyName": key_name,
                }
            )
    return results


# -*- coding: utf-8 -*-
"""
Author: BigCat
"""
import os

URL = "https://datachart.500.com/ssq/history/"
path = "newinc/history.php?start={}&end="

BOLL_NAME = [
    ("红球", "red"),
    ("蓝球", "blue")
]

train_data_path = "data/"
train_data_file = "data.csv"

# 模型相关参数
windows_size = 3
batch_size = 1
sequence_len = 6
red_n_class = 33
red_epochs = 1
red_embedding_size = 32
red_hidden_size = 32
red_layer_size = 1
blue_n_class = 16
blue_epochs = 1
blue_embedding_size = 32
blue_hidden_size = 32
blue_layer_size = 1

# 模型训练参数
red_learning_rate = 0.001
red_beta1 = 0.9
red_beta2 = 0.999
red_epsilon = 1e-08
blue_learning_rate = 0.001
blue_beta1 = 0.9
blue_beta2 = 0.999
blue_epsilon = 1e-08

# 模型路径
model_path = os.getcwd() + "/model/"
red_ball_model_path = model_path + "/red_ball_model/"
blue_ball_model_path = model_path + "/blue_ball_model/"

# 模型名
pred_key_name = "key_name.json"
red_ball_model_name = "red_ball_model"
blue_ball_model_name = "blue_ball_model"
extension = "ckpt"

# 日志路径
log_path = os.getcwd() + "/log/"
access_log = log_path + "access.log"
error_log = log_path + "error.log"


from django.urls import path
from django.conf.urls import *
from . import views
from .views import IdeaViewSet, HistoryViewSet, OwnIdeasViewSet
from rest_framework import routers

app_name = 'website'

urlpatterns = [
    url(r'^$', views.homepage, name='index'),
    url(r'^$', HistoryViewSet.as_view, name='history'),
    url(r'^ideas/$', IdeaViewSet.as_view, name='idea-list'),
    url(r'^ideas/user/(?P<pk>\d+)/$', OwnIdeasViewSet.as_view, name='own-idea-list'),

    path('index', views.IndexView.as_view(), name='index'),
    path('history', views.HistoryView.as_view(), name='history'),
    path('ideas', views.IdeasView.as_view(), name='ideas'),
    url(r'^idea/new/$', views.idea_new, name='idea_new'),
    url(r'^idea/(?P<pk>\d+)/$', views.idea_detail, name='idea_detail'),
    path('phasergame', views.PhaserGameView.as_view(), name='phasergame'),

    # url(r'^signup/$', views.signup, name='signup'),
    url(r'^signup/$', views.signup, name='signup'),
    url(r'^account_activation_sent/$', views.account_activation_sent, name='account_activation_sent'),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',
        views.activate, name='activate'),
]