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

# 45. Jump Game II (H)_3
# Created by xc 20/04/2017
"""
    最后一个测试点不过,说明复杂度还是太大了
    动态规划竟然不好用
    http://www.cnblogs.com/ganganloveu/p/3761715.html
    参考了网上的思路:

"""
class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 当前的总的步数
        total_step = 0

        # 经过total_step所能到达的距离
        current_reach = 0

        # 从0~i中能到达的最大范围
        max_distance = 0

        for i in range(0, len(nums)):
            if current_reach >= len(nums) - 1:
                break
            if i > current_reach:
                total_step += 1
                current_reach = max_distance
            max_distance = max(max_distance, nums[i] + i)
        return total_step

code/45. Jump Game II/45. Jump Game II (H)_3.py


try:
    import unittest
    from com.itt.tds.db.dao_impl.ClientDAOImpl import ClientDAOImpl
    from com.itt.tds.model.Client import Client
    from com.itt.tds.db.exceptions.ClientAlreadyExistsException import ClientAlreadyExistsException
    from com.itt.tds.db.exceptions.ClientNotFoundException import ClientNotFoundException
    from com.itt.tds.db.exceptions.DBException import DBException

except ImportError as error:
    print(error.__str__())
    from com.itt.tds.logs.LogManager import LogManager
    log = LogManager.get_logger()
    if log:
        log.log_warn(
            'ClientUnitTest', 'Import Module', error.__str__(), str(error))

class ClientsUnitTest(unittest.TestCase):
    _client_dao = ClientDAOImpl()

    def setUp(self):
        """Initialization method for test cases which will run for each test
        case"""
        self.test_data = self.read_data('test_data/clients.txt')

    def read_data(self, file_name):
        """Function is responsible for reading the given file and return the file
        data as dictionary
            Passing Arguments:
            file_name : Represents a file name which needs to be read

            Return Value:
            dictionary : Returns a dictionary type of object which stores the file
            data as per line basis
        """
        test_data_dict = {}
        i = 0
        file_handler = open(file_name)
        for data in file_handler.readlines():
            if i == 0:
                pass
            else:
                if data[len(data) - 1] == '\n':
                    data = data[:len(data) - 1]
                test_data_dict[i] = data
            i += 1
        file_handler.close()
        return test_data_dict

#    @unittest.skip("Add client step")
    def test_01_add_client(self):
        """
        Test case for adding new client into the database.It is useful for
        testing the functionality of
        ClientDAO's add method."""
        try:
            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                client.host_name = test_str[1]
                client.user_name = test_str[2]
                ClientsUnitTest._client_dao.add(client)
                self.assertTrue(
                    ClientsUnitTest._client_dao.get_client(client.user_id))

            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                self.assertTrue(ClientsUnitTest._client_dao.delete(client))

        except DBException as error:
            print(error.get_message())

#    @unittest.skip("Add client step")
    def test_02_add_client_exception(self):
        """
        Test case for adding new client into the database.It is useful for
        testing the functionality of
        ClientDAO's add method.It should throw an exception because of adding
        the same client twice."""
        count = 0
        try:
            while count < 2:
                for k, v in self.test_data.items():
                    client = Client()
                    test_str = v.split(',')
                    client.user_id = test_str[0]
                    client.host_name = test_str[1]
                    client.user_name = test_str[2]
                    ClientsUnitTest._client_dao.add(client)
                    self.assertTrue(
                        ClientsUnitTest._client_dao.get_client(client.user_id))
                count += 1

        except ClientAlreadyExistsException as error:
            print(error.get_message())
            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                self.assertTrue(ClientsUnitTest._client_dao.delete(client))

        except DBException as error:
            print(error.get_message())

#    @unittest.skip("get all client step")
    def test_03_get_all_client(self):
        """
        Test case for getting all clients into the system."""
        try:
            return_value = ClientsUnitTest._client_dao.get_clients()
            self.assertGreater(len(return_value), 1)

        except DBException as error:
            print(error.error_string())

#    @unittest.skip("update client step")
    def test_04_update_client(self):
        """
        Test case for updating client into the database.It is useful for
        testing the functionality of
        ClientDAO's modify method."""
        for k, v in self.test_data.items():
            client = Client()
            test_str = v.split(',')
            client.user_id = test_str[0]
            client.host_name = test_str[1]
            client.user_name = test_str[2]
            ClientsUnitTest._client_dao.add(client)
            self.assertTrue(
                ClientsUnitTest._client_dao.get_client(client.user_id))

        for k, v in self.test_data.items():
            client = Client()
            test_str = v.split(',')
            client.user_id = test_str[0]
            client.host_name = test_str[1]
            client.user_name = test_str[2]
            ClientsUnitTest._client_dao.modify(client)
            client = ClientsUnitTest._client_dao.get_client(client.user_id)
            self.assertEqual(client.user_id, int(test_str[0]))
            self.assertEqual(client.host_name, test_str[1])
            self.assertEqual(client.user_name, test_str[2])

        for k, v in self.test_data.items():
            client = Client()
            test_str = v.split(',')
            client.user_id = test_str[0]
            self.assertTrue(ClientsUnitTest._client_dao.delete(client))

        try:
            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                client.host_name = test_str[1]
                client.user_name = test_str[2]
                self.assertTrue(ClientsUnitTest._client_dao.modify(client))

        except ClientNotFoundException as error:
            print(error.get_message())

        except DBException as error:
            print(error.get_message())

#    @unittest.skip("delete client step")
    def test_05_delete_client(self):
        """
        Test case for deleting client from the database.It is useful
        for testing the functionality of
        ClientDAO's delete method."""
        try:
            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                client.host_name = test_str[1]
                client.user_name = test_str[2]
                ClientsUnitTest._client_dao.add(client)
                self.assertTrue(
                    ClientsUnitTest._client_dao.get_client(client.user_id))

            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                self.assertTrue(ClientsUnitTest._client_dao.delete(client))

            for k, v in self.test_data.items():
                client = Client()
                test_str = v.split(',')
                client.user_id = test_str[0]
                self.assertTrue(ClientsUnitTest._client_dao.delete(client))

        except ClientAlreadyExistsException as error:
            print(error.get_message())

        except ClientNotFoundException as error:
            print(error.get_message())

        except DBException as error:
            print(error.get_message())

    def tearDown(self):
        return None

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


import pandas as pd
from FileLoader import FileLoader

def youngestFellah(data, val):
    print("1", data.head())
    dataY = data[data.Year == val]
    print("2", dataY.head())
    print("3", data.head())
    return {
        'M': dataY[dataY.Sex == 'M'].Age.min(),
        'F': dataY[dataY.Sex == 'F'].Age.min()
    }

if __name__ == "__main__":
    loader = FileLoader()
    df = loader.load("../assets/athlete_events.csv")
    print(youngestFellah(df, 2004))


import urllib.parse
from typing import Any

from lambda_pipeline.types import FrozenDict, LambdaContext, PipelineData
from pydantic import BaseModel, validator

from nrlf.core.errors import ItemNotFound
from nrlf.core.model import APIGatewayProxyEventModel

class RaiseValidationErrorModel(BaseModel):
    foo: bool

    @validator("foo")
    def something(value):
        raise ValueError

class RaiseItemNotFoundErrorModel(BaseModel):
    foo: bool

    @validator("foo")
    def something(value):
        raise ItemNotFound

def throw_validation_error(
    data: PipelineData,
    context: LambdaContext,
    event: APIGatewayProxyEventModel,
    dependencies: FrozenDict[str, Any],
) -> PipelineData:
    RaiseValidationErrorModel(foo="1")

def throw_item_not_found_error(
    data: PipelineData,
    context: LambdaContext,
    event: APIGatewayProxyEventModel,
    dependencies: FrozenDict[str, Any],
) -> PipelineData:
    RaiseItemNotFoundErrorModel(foo="1")

def make_aws_event(
    body=None,
    methodArn={},
    authorizer={},
    version="1",
    headers={},
    query_params={},
    path_params={},
):
    return {
        "resource": "/",
        "path": "/",
        "httpMethod": "GET",
        **methodArn,
        "headers": {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9;version="
            + version,
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "en-US,en;q=0.9",
            "cookie": "s_fid=7AAB6XMPLAFD9BBF-0643XMPL09956DE2; regStatus=pre-register",
            "Host": "70ixmpl4fl.execute-api.us-east-2.amazonaws.com",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "upgrade-insecure-requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
            "X-Amzn-Trace-Id": "Root=1-5e66d96f-7491f09xmpl79d18acf3d050",
            "X-Forwarded-For": "52.255.255.12",
            "X-Forwarded-Port": "443",
            "X-Forwarded-Proto": "https",
            **headers,
        },
        "multiValueHeaders": {
            "accept": [
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9;version="
                + version
            ],
            "accept-encoding": ["gzip, deflate, br"],
            "accept-language": ["en-US,en;q=0.9"],
            "cookie": [
                "s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2; regStatus=pre-register;"
            ],
            "Host": ["70ixmpl4fl.execute-api.ca-central-1.amazonaws.com"],
            "sec-fetch-dest": ["document"],
            "sec-fetch-mode": ["navigate"],
            "sec-fetch-site": ["none"],
            "upgrade-insecure-requests": ["1"],
            "User-Agent": [
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
            ],
            "X-Amzn-Trace-Id": ["Root=1-5e66d96f-7491f09xmpl79d18acf3d050"],
            "X-Forwarded-For": ["52.255.255.12"],
            "X-Forwarded-Port": ["443"],
            "X-Forwarded-Proto": ["https"],
        },
        "queryStringParameters": query_params,
        "multiValueQueryStringParameters": None,
        "pathParameters": {k: urllib.parse.quote(v) for k, v in path_params.items()},
        "stageVariables": None,
        "requestContext": {
            "resourceId": "2gxmpl",
            "resourcePath": "/",
            "httpMethod": "GET",
            "extendedRequestId": "JJbxmplHYosFVYQ=",
            "requestTime": "10/Mar/2020:00:03:59 +0000",
            "path": "/Prod/",
            "accountId": "123456789012",
            "protocol": "HTTP/1.1",
            "stage": "Prod",
            "domainPrefix": "70ixmpl4fl",
            "requestTimeEpoch": 1583798639428,
            "requestId": "77375676-xmpl-4b79-853a-f982474efe18",
            "identity": {
                "cognitoIdentityPoolId": None,
                "accountId": None,
                "cognitoIdentityId": None,
                "caller": None,
                "sourceIp": "52.255.255.12",
                "principalOrgId": None,
                "accessKey": None,
                "cognitoAuthenticationType": None,
                "cognitoAuthenticationProvider": None,
                "userArn": None,
                "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
                "user": None,
            },
            "domainName": "70ixmpl4fl.execute-api.us-east-2.amazonaws.com",
            "apiId": "70ixmpl4fl",
            "authorizer": authorizer,
        },
        "body": body,
        "isBase64Encoded": False,
    }


import io
import os
import re
import six
import json
import time
import yaml
import unittest
import gramex.cache
import pandas as pd
import sqlalchemy as sa
from lxml import etree
from gramex.cache import hashfn
from gramex.config import variables, str_utf8
from six import string_types
from markdown import markdown
from collections import OrderedDict
from orderedattrdict import AttrDict
from tornado.template import Template
from orderedattrdict.yamlutils import AttrDictYAMLLoader
from pandas.util.testing import assert_frame_equal
from nose.tools import eq_, ok_, assert_raises
import dbutils
from . import folder

cache_folder = os.path.join(folder, 'test_cache')
state_file = os.path.join(cache_folder, '.state')
small_delay = 0.01

def touch(path, times=None, data=None):
    with io.open(path, 'ab') as handle:
        os.utime(path, times)
        if data is not None:
            handle.write(data)

class TestReloadModule(unittest.TestCase):
    def test_reload_module(self):
        # When loaded, the counter is not incremented
        from testlib.test_cache.common import val
        eq_(val[0], 0)

        # On first load, the counter is incremented once
        import testlib.test_cache.mymodule
        eq_(val[0], 1)

        # On second load, it stays cached
        import testlib.test_cache.mymodule      # noqa
        eq_(val[0], 1)

        # The first time, we get the reloaded date. The module may be reloaded
        gramex.cache.reload_module(testlib.test_cache.mymodule)
        count = val[0]
        # On explicit reload_module, it still stays cached
        gramex.cache.reload_module(testlib.test_cache.mymodule)
        eq_(val[0], count)

        # Change the module
        pyfile = testlib.test_cache.mymodule.__file__.rstrip('c')
        module_timestamp_delay = 0.005
        time.sleep(module_timestamp_delay)
        touch(pyfile)

        # Regular import does not reload
        import testlib.test_cache.mymodule
        eq_(val[0], count)

        # ... but reload_module DOES reload, and the counter increments
        gramex.cache.reload_module(testlib.test_cache.mymodule)
        eq_(val[0], count + 1)

        # Subsequent call does not reload
        gramex.cache.reload_module(testlib.test_cache.mymodule)
        eq_(val[0], count + 1)

class TestOpener(unittest.TestCase):
    def check_args(self, *args, **kwargs):
        return AttrDict(args=args, kwargs=kwargs)

    def test_params(self):
        # gramex.cache.opener should have a callable callback
        with assert_raises(ValueError):
            gramex.cache.opener(None)
        with assert_raises(ValueError):
            gramex.cache.opener('text')

    def test_opener(self):
        o = gramex.cache.opener(self.check_args)
        path = os.path.join(cache_folder, 'template.txt')

        result = o(path)
        eq_(type(result.args[0]), io.TextIOWrapper)
        eq_(result.args[0].name, path)
        eq_(result.args[0].encoding, 'utf-8')
        eq_(result.kwargs, {})

        result = o(path, encoding='cp1252')
        eq_(type(result.args[0]), io.TextIOWrapper)
        eq_(result.args[0].encoding, 'cp1252')
        eq_(result.kwargs, {})

        result = o(path, mode='rb', encoding=None, errors=None)
        eq_(type(result.args[0]), io.BufferedReader)
        eq_(result.kwargs, {})

        result = o(path, num=1, s='a', none=None)
        eq_(result.kwargs, {'num': 1, 's': 'a', 'none': None})

    def test_reader(self):
        o = gramex.cache.opener(self.check_args, read=True)
        path = os.path.join(cache_folder, 'template.txt')

        with io.open(path, encoding='utf-8') as handle:
            text = handle.read()
        result = o(path)
        eq_(result.args, (text, ))
        eq_(result.kwargs, {})

        with io.open(path, mode='rb') as handle:
            text = handle.read()
        result = o(path, mode='rb', encoding=None, errors=None)
        eq_(result.args, (text, ))
        eq_(result.kwargs, {})

        result = o(path, num=1, s='a', none=None)
        eq_(result.kwargs, {'num': 1, 's': 'a', 'none': None})

class TestOpen(unittest.TestCase):
    @staticmethod
    def check_file_cache(path, check):
        check(reload=True)
        check(reload=False)
        touch(path)
        time.sleep(small_delay)
        check(reload=True)

    def test_rel(self):
        # Passing rel=True picks up the file from the current directory
        path = 'test_cache/template.txt'
        with io.open(os.path.join(cache_folder, 'template.txt'), encoding='utf-8') as handle:
            expected = handle.read()
        result = gramex.cache.open(path, 'txt', rel=True)
        eq_(result, expected)

    def test_open_text(self):
        path = os.path.join(cache_folder, 'template.txt')
        expected = io.open(path, encoding='utf-8', errors='ignore').read()

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'text', _reload_status=True)
            eq_(reloaded, reload)
            eq_(result, expected)

        self.check_file_cache(path, check)
        eq_(gramex.cache.open(path), gramex.cache.open(path, 'text'))
        eq_(gramex.cache.open(path), gramex.cache.open(path, 'txt'))

    def test_open_bin(self):
        path = os.path.join(cache_folder, 'data.bin')
        expected = io.open(path, mode='rb').read()

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'bin', _reload_status=True)
            eq_(reloaded, reload)
            eq_(result, expected)

        self.check_file_cache(path, check)

    def test_open_csv(self):
        path = os.path.join(cache_folder, 'data.csv')
        expected = pd.read_csv(path, encoding='utf-8')

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'csv', _reload_status=True,
                                                 encoding='utf-8')
            eq_(reloaded, reload)
            assert_frame_equal(result, expected)

        self.check_file_cache(path, check)
        assert_frame_equal(gramex.cache.open(path), gramex.cache.open(path, 'csv'))

    def test_open_json(self):
        path = os.path.join(cache_folder, 'data.json')
        with io.open(path, encoding='utf-8') as handle:
            expected = json.load(handle, object_pairs_hook=OrderedDict)

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'json', _reload_status=True,
                                                 object_pairs_hook=OrderedDict)
            eq_(reloaded, reload)
            ok_(isinstance(result, OrderedDict))
            eq_(result, expected)

        self.check_file_cache(path, check)
        eq_(gramex.cache.open(path), gramex.cache.open(path, 'json'))

    def test_open_jsondata(self):
        path = os.path.join(cache_folder, 'data.jsondata')
        expected = pd.read_json(path)

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'jsondata', _reload_status=True)
            eq_(reloaded, reload)
            assert_frame_equal(result, expected)

        self.check_file_cache(path, check)
        assert_frame_equal(gramex.cache.open(path), gramex.cache.open(path, 'jsondata'))

    def test_open_yaml(self):
        path = os.path.join(cache_folder, 'data.yaml')
        with io.open(path, encoding='utf-8') as handle:
            expected = yaml.load(handle, Loader=AttrDictYAMLLoader)

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'yaml', _reload_status=True,
                                                 Loader=AttrDictYAMLLoader)
            eq_(reloaded, reload)
            ok_(isinstance(result, AttrDict))
            eq_(result, expected)

        self.check_file_cache(path, check)
        eq_(gramex.cache.open(path), gramex.cache.open(path, 'yaml'))

    def test_open_template(self):
        path = os.path.join(cache_folder, 'template.txt')

        def check(reload):
            result, reloaded = gramex.cache.open(
                path, 'template', _reload_status=True, autoescape=None)
            eq_(reloaded, reload)
            ok_(isinstance(result, Template))
            first_line = result.generate(name='高').decode('utf-8').split('\n')[0]
            eq_(first_line, '1: name=高')

        self.check_file_cache(path, check)

    def test_open_markdown(self):
        path = os.path.join(cache_folder, 'markdown.md')
        extensions = [
            'markdown.extensions.codehilite',
            'markdown.extensions.extra',
            'markdown.extensions.toc',
            'markdown.extensions.meta',
            'markdown.extensions.sane_lists',
            'markdown.extensions.smarty',
        ]
        with io.open(path, encoding='utf-8') as handle:
            expected = markdown(handle.read(), output_format='html5', extensions=extensions)

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'md', _reload_status=True, encoding='utf-8')
            eq_(reloaded, reload)
            ok_(isinstance(result, six.text_type))
            eq_(result, expected)

        self.check_file_cache(path, check)
        eq_(gramex.cache.open(path), gramex.cache.open(path, 'md'))

    def test_open_xml(self):
        path = os.path.join(cache_folder, 'data.svg')
        expected = etree.parse(path)

        def check(reload):
            result, reloaded = gramex.cache.open(path, 'svg', _reload_status=True)
            eq_(reloaded, reload)
            eq_(etree.tostring(result), etree.tostring(expected))

        self.check_file_cache(path, check)
        for ext in ['xml', 'svg', 'rss', 'atom']:
            eq_(etree.tostring(gramex.cache.open(path)),
                etree.tostring(gramex.cache.open(path, ext)))

    def test_save(self):
        path = os.path.join(cache_folder, 'data.csv')
        data = pd.read_csv(path, encoding='utf-8')
        config = {
            'csv': dict(index=False, ignore_keyword=1),
            'xlsx': dict(index=False, sheet_name='Sheet1', ignore_keyword=1),
            'html': dict(index=False, escape=False, ignore_keyword=1),
            'hdf': dict(index=False, key='data', format='fixed', ignore_keyword=1),
            'json': dict(orient='records', ignore_keyword=1),
            # 'stata': dict(index=False),   # cannot test since it doesn't support unicode
        }
        for ext, kwargs in config.items():
            target = os.path.join(cache_folder, 'killme.' + ext)
            gramex.cache.save(data, target, **kwargs)
            try:
                result = gramex.cache.open(target)
                if ext == 'html':
                    result = result[0]
                elif ext == 'json':
                    result = pd.DataFrame(data)
                assert_frame_equal(result, data)
            finally:
                os.remove(target)

    def test_custom_cache(self):
        path = os.path.join(cache_folder, 'data.csv')
        cache = {}
        kwargs = {'_reload_status': True, '_cache': cache}
        result, reloaded = gramex.cache.open(path, 'csv', **kwargs)
        cache_key = (path, 'csv', hashfn(None), frozenset())
        self.assertIn(cache_key, cache)

        # Initially, the file is loaded
        eq_(reloaded, True)

        # Next time, it's loaded from the cache
        result, reloaded = gramex.cache.open(path, 'csv', **kwargs)
        eq_(reloaded, False)

        # If the cache is deleted, it reloads
        del cache[cache_key]
        result, reloaded = gramex.cache.open(path, 'csv', **kwargs)
        eq_(reloaded, True)

        # Additional kwargs are part of the cache key
        result, reloaded = gramex.cache.open(path, encoding='utf-8', **kwargs)
        cache_key = (path, None, hashfn(None), frozenset([('encoding', 'utf-8')]))
        self.assertIn(cache_key, cache)
        eq_(reloaded, True)
        result, reloaded = gramex.cache.open(path, encoding='utf-8', **kwargs)
        eq_(reloaded, False)

        # Changing the kwargs reloads the data
        result, reloaded = gramex.cache.open(path, encoding='cp1252', **kwargs)
        eq_(reloaded, True)
        result, reloaded = gramex.cache.open(path, encoding='cp1252', **kwargs)
        eq_(reloaded, False)

        # Cache is not fazed by non-hashable inputs.
        result, reloaded = gramex.cache.open(
            path,
            header=0,
            parse_dates={'date': [0, 1, 2]},
            dtype={'a': int, 'b': float, 'c': int},
            **kwargs)
        cache_key = (path, None, hashfn(None), frozenset([
            ('header', 0),                              # hashable values hashed as-is
            ('parse_dates', '{"date":[0,1,2]}'),        # converts to compact json if possible
            ('dtype', None),                            # gives up with None otherwise
        ]))
        self.assertIn(cache_key, cache)

    def test_change_cache(self):
        # gramex.cache.set_cache() changes the default cache
        path = os.path.join(cache_folder, 'data.csv')
        new_cache = {}
        old_cache = gramex.cache._OPEN_CACHE
        cache_key = (path, 'csv', hashfn(None), frozenset())

        # Ensure that the path is cached
        gramex.cache.open(path, 'csv')
        self.assertIn(cache_key, old_cache)
        old_cache_data = dict(old_cache)

        # Updating the cache copies data and empties from the old one
        gramex.cache._OPEN_CACHE = gramex.cache.set_cache(new_cache, old_cache)
        eq_(new_cache, old_cache_data)
        eq_(old_cache, {})

        # New requests are cached in the new cache
        result, reloaded = gramex.cache.open(path, 'csv', _reload_status=True)
        eq_(reloaded, False)
        self.assertIn(cache_key, new_cache)
        del new_cache[cache_key]
        old_cache.pop(cache_key, None)
        self.assertNotIn(cache_key, new_cache)
        result, reloaded = gramex.cache.open(path, 'csv', _reload_status=True)
        eq_(reloaded, True)
        self.assertIn(cache_key, new_cache)
        self.assertNotIn(cache_key, old_cache)

    def test_multiple_loaders(self):
        # Loading the same file via different callbacks should return different results
        path = os.path.join(cache_folder, 'multiformat.csv')
        data = gramex.cache.open(path, 'csv')
        ok_(isinstance(data, pd.DataFrame))
        text = gramex.cache.open(path, 'text')
        ok_(isinstance(text, string_types))
        none = gramex.cache.open(path, lambda path: None)
        ok_(none is None)

    def test_invalid_callbacks(self):
        path = os.path.join(cache_folder, 'multiformat.csv')
        with assert_raises(TypeError):
            gramex.cache.open(path, 'nonexistent')
        with assert_raises(TypeError):
            gramex.cache.open(path, 1)
        with assert_raises(TypeError):
            gramex.cache.open('invalid.ext')

    def test_stat(self):
        path = os.path.join(cache_folder, 'multiformat.csv')
        stat = os.stat(path)
        eq_(gramex.cache.stat(path), (stat.st_mtime, stat.st_size))
        eq_(gramex.cache.stat('nonexistent'), (None, None))

    def test_transform(self):
        # Check that transform function is applied and used as a cache key
        cache = {}
        path = os.path.join(cache_folder, 'data.csv')

        data = gramex.cache.open(path, 'csv', transform=len, _cache=cache)
        eq_(data, len(pd.read_csv(path)))                   # noqa - ignore encoding
        cache_key = (path, 'csv', hashfn(len), frozenset([]))
        self.assertIn(cache_key, cache)

        def transform2(d):
            return d['a'].sum()

        data = gramex.cache.open(path, 'csv', transform=transform2, _cache=cache)
        eq_(data, pd.read_csv(path)['a'].sum())             # noqa - ignore encoding
        cache_key = (path, 'csv', hashfn(transform2), frozenset([]))
        self.assertIn(cache_key, cache)

        # Check that non-callable transforms are ignored but used as cache key
        data = gramex.cache.open(path, 'csv', transform='ignore', _cache=cache)
        assert_frame_equal(data, pd.read_csv(path))         # noqa - ignore encoding
        cache_key = (path, 'csv', hashfn('ignore'), frozenset([]))
        self.assertIn(cache_key, cache)

        # Check that temporary caches are hashed by function
        v = 1
        data = gramex.cache.open(path, 'csv', lambda x: v, _cache=cache)
        eq_(data, 1)
        v = 2
        data = gramex.cache.open(path, 'csv', lambda x: v, _cache=cache)
        eq_(data, 2)

class TestSqliteCacheQuery(unittest.TestCase):
    data = pd.read_csv(os.path.join(cache_folder, 'data.csv'), encoding='utf-8')
    states = [['t1'], 'SELECT COUNT(*) FROM t1', lambda: gramex.cache.stat(state_file)]

    @classmethod
    def setUpClass(cls):
        cls.url = dbutils.sqlite_create_db('test_cache.db', t1=cls.data, t2=cls.data)
        cls.engine = sa.create_engine(cls.url, encoding=str_utf8)

    @classmethod
    def tearDownClass(cls):
        dbutils.sqlite_drop_db('test_cache')

    def test_wheres(self):
        w = gramex.cache._wheres
        eq_(w('db', 'tbl', 'db', ['x']), "(db='db' AND tbl='x')")
        eq_(w('db', 'tbl', 'db', ['x', 'y']), "(db='db' AND tbl='x') OR (db='db' AND tbl='y')")
        eq_(w('db', 'tbl', 'db', ['a.x']), "(db='a' AND tbl='x')")
        eq_(w('db', 'tbl', 'db', ['a.x', 'y']), "(db='a' AND tbl='x') OR (db='db' AND tbl='y')")
        eq_(w('db', 'tbl', 'db', ['a.x', 'b.y']), "(db='a' AND tbl='x') OR (db='b' AND tbl='y')")

    def test_query_state_invalid(self):
        # Empty state list raises an error
        with assert_raises(ValueError):
            gramex.cache.query('SELECT * FROM t1', self.engine, state=[])
        # State list with invalid type raises an error
        with assert_raises(ValueError):
            gramex.cache.query('SELECT * FROM t1', self.engine, state=[None])
        # Anything other than a string, list/tuple or function should raise a TypeError
        with assert_raises(TypeError):
            gramex.cache.query('SELECT * FROM t1', self.engine, state=1)

    def test_query_value(self):
        assert_frame_equal(gramex.cache.query('SELECT * FROM t2', engine=self.engine), self.data)

    def test_query_cache(self):
        sql = 'SELECT * FROM t1 LIMIT 2'
        kwargs = dict(sql=sql, engine=self.engine, state=['t1'], _reload_status=True)
        c0 = len(gramex.cache._QUERY_CACHE)
        eq_(gramex.cache.query(**kwargs)[1], True)
        c1 = len(gramex.cache._QUERY_CACHE)
        eq_(gramex.cache.query(**kwargs)[1], False)
        c2 = len(gramex.cache._QUERY_CACHE)
        eq_(c1, c0 + 1)
        eq_(c1, c2)

    def test_query_states(self):
        # Check for 3 combinations
        # 1. state is a list of table names. (Currently, this only works with sqlite)
        # 2. state is a string (query to check row count)
        # 3. state is a callable (checks updated time of .state file)
        for state in self.states:
            msg = 'failed at state=%s, url=%s' % (state, self.url)
            sql = 'SELECT * FROM t1'
            kwargs = dict(sql=sql, engine=self.engine, state=state, _reload_status=True)
            eq_(gramex.cache.query(**kwargs)[1], True, msg)
            eq_(gramex.cache.query(**kwargs)[1], False, msg)
            eq_(gramex.cache.query(**kwargs)[1], False, msg)

            # Update the data
            if callable(state):
                touch(state_file, data=b'x')
            else:
                self.data.to_sql('t1', self.engine, if_exists='append', index=False)

            eq_(gramex.cache.query(**kwargs)[1], True, msg)
            eq_(gramex.cache.query(**kwargs)[1], False, msg)
            eq_(gramex.cache.query(**kwargs)[1], False, msg)

        # If state is None, always reload the query
        kwargs['state'] = None
        eq_(gramex.cache.query(**kwargs)[1], True, msg)
        eq_(gramex.cache.query(**kwargs)[1], True, msg)
        eq_(gramex.cache.query(**kwargs)[1], True, msg)

class TestMySQLCacheQuery(TestSqliteCacheQuery):
    states = ['SELECT COUNT(*) FROM t1', lambda: gramex.cache.stat(state_file)]

    @classmethod
    def setUpClass(cls):
        cls.url = dbutils.mysql_create_db(variables.MYSQL_SERVER, 'test_cache',
                                          t1=cls.data, t2=cls.data)
        cls.engine = sa.create_engine(cls.url, encoding=str_utf8)

    @classmethod
    def tearDownClass(cls):
        dbutils.mysql_drop_db(variables.MYSQL_SERVER, 'test_cache')

class TestPostgresCacheQuery(TestSqliteCacheQuery):
    states = ['SELECT COUNT(*) FROM t1', lambda: gramex.cache.stat(state_file)]

    @classmethod
    def setUpClass(cls):
        cls.url = dbutils.postgres_create_db(variables.POSTGRES_SERVER, 'test_cache',
                                             **{'t1': cls.data, 't2': cls.data, 'sc.t3': cls.data})
        cls.engine = sa.create_engine(cls.url, encoding=str_utf8)

    def test_schema(self):
        assert_frame_equal(
            gramex.cache.query('SELECT * FROM sc.t3', engine=self.engine), self.data)

    @classmethod
    def tearDownClass(cls):
        dbutils.postgres_drop_db(variables.POSTGRES_SERVER, 'test_cache')

def wait(future):
    wait_till(future.done)
    return future.result()

def wait_till(condition):
    while not condition():
        time.sleep(small_delay)

class TestSubprocess(unittest.TestCase):
    args = ['python', os.path.join(folder, 'subprocess_check.py')]          # Instant result
    args1 = ['python', os.path.join(folder, 'subprocess_check.py'), '1']    # Result after delay
    hello = ['python', '-c', 'print("hello")']

    @staticmethod
    def msg(s):
        '''Returns the string + newline as UTF-8 bytestring'''
        return (s + os.linesep).encode('utf-8')

    def test_stream_none(self):
        proc = gramex.cache.Subprocess(self.args)
        stdout, stderr = [wait(future) for future in proc.wait_for_exit()]
        eq_(stdout, self.msg('OUT:0'))
        eq_(stderr, self.msg('ERR:0'))

        proc = gramex.cache.Subprocess(self.args1)
        stdout, stderr = [wait(future) for future in proc.wait_for_exit()]
        eq_(stdout, self.msg('OUT:0') + self.msg('OUT:1'))
        eq_(stderr, self.msg('ERR:0') + self.msg('ERR:1'))

    def test_stream_list(self):
        proc = gramex.cache.Subprocess(
            self.args, stream_stdout='list_out', stream_stderr='list_err', buffer_size='line')
        [wait(future) for future in proc.wait_for_exit()]
        eq_(proc.list_out, [self.msg('OUT:0')])
        eq_(proc.list_err, [self.msg('ERR:0')])

        proc = gramex.cache.Subprocess(
            self.args1, stream_stdout='list_out', stream_stderr='list_err', buffer_size='line')
        wait_till(lambda: len(proc.list_out) > 0)
        wait_till(lambda: len(proc.list_err) > 0)
        eq_(proc.list_out, [self.msg('OUT:0')])
        eq_(proc.list_err, [self.msg('ERR:0')])
        wait_till(lambda: len(proc.list_out) > 1)
        wait_till(lambda: len(proc.list_err) > 1)
        eq_(proc.list_out, [self.msg('OUT:0'), self.msg('OUT:1')])
        eq_(proc.list_err, [self.msg('ERR:0'), self.msg('ERR:1')])
        [wait(future) for future in proc.wait_for_exit()]
        eq_(proc.list_out, [self.msg('OUT:0'), self.msg('OUT:1')])
        eq_(proc.list_err, [self.msg('ERR:0'), self.msg('ERR:1')])

    def test_stream_queue(self):
        proc = gramex.cache.Subprocess(
            self.args, stream_stdout='queue_out', stream_stderr='queue_err')
        [wait(future) for future in proc.wait_for_exit()]
        eq_(proc.queue_out.get(), self.msg('OUT:0'))
        eq_(proc.queue_err.get(), self.msg('ERR:0'))

        proc = gramex.cache.Subprocess(
            self.args1, stream_stdout='queue_out', stream_stderr='queue_err', buffer_size='line')
        eq_(proc.queue_out.get(), self.msg('OUT:0'))
        eq_(proc.queue_err.get(), self.msg('ERR:0'))
        eq_(proc.queue_out.get(), self.msg('OUT:1'))
        eq_(proc.queue_err.get(), self.msg('ERR:1'))
        [wait(future) for future in proc.wait_for_exit()]
        eq_(proc.queue_out.qsize(), 0)
        eq_(proc.queue_err.qsize(), 0)

    def test_stream_blend(self):
        proc = gramex.cache.Subprocess(
            self.args1, stream_stdout='list_out', stream_stderr='list_out', buffer_size='line')
        [wait(future) for future in proc.wait_for_exit()]
        eq_(set(proc.list_out), {self.msg(s) for s in ('OUT:0', 'OUT:1', 'ERR:0', 'ERR:1')})

        proc = gramex.cache.Subprocess(
            self.args1, stream_stdout='queue_out', stream_stderr='queue_out', buffer_size='line')
        [wait(future) for future in proc.wait_for_exit()]
        items = set()
        for index in range(proc.queue_out.qsize()):
            items.add(proc.queue_out.get_nowait())
        eq_(items, {self.msg(s) for s in ('OUT:0', 'OUT:1', 'ERR:0', 'ERR:1')})

    def test_daemon_reuse(self):
        procs = [
            wait(gramex.cache.daemon(self.args)),
            wait(gramex.cache.daemon(self.args)),
            wait(gramex.cache.daemon(self.args1)),
        ]
        eq_(procs[0].proc.pid, procs[1].proc.pid)
        ok_(procs[0].proc.pid != procs[2].proc.pid)
        for proc in procs:
            [wait(future) for future in proc.wait_for_exit()]

    def test_daemon_stream(self):
        out = []
        proc = wait(gramex.cache.daemon(self.args, stream=out.append))
        [wait(future) for future in proc.wait_for_exit()]
        eq_(set(out), {self.msg('OUT:0'), self.msg('ERR:0')})

    def test_daemon_first_line(self):
        # Streaming output is still possible
        out = []
        proc = wait(gramex.cache.daemon(self.hello, first_line='hello', stream=out.append))
        [wait(future) for future in proc.wait_for_exit()]
        eq_(set(out), {self.msg('hello')})

        # Incorrect first line raises an error
        with assert_raises(AssertionError):
            proc = wait(gramex.cache.daemon(self.args, first_line='NOTHING'))
        [wait(future) for future in proc.wait_for_exit()]

        # Correct first line can be a string or regex
        proc = wait(gramex.cache.daemon(self.hello, first_line='hello'))
        [wait(future) for future in proc.wait_for_exit()]
        proc = wait(gramex.cache.daemon(self.args, first_line=re.compile(r'(OUT|ERR):\d\s*')))
        [wait(future) for future in proc.wait_for_exit()]

def tearDownModule():
    if os.path.exists(state_file):
        os.unlink(state_file)


'''

How much did the item cost : 65.64
How much did the person give you: 100.00
The person ’s change is $34 .36
The bills or the change should be:
1 twenties
1 tens
0 fives
4 ones
1 quarters1 dimes
0 nickels
1 pennies

2020.05.08 tziss85@gmail.com
    Printed only non zero bills & coins

'''
cost=float(input("How much did the item cost : "))
money=float(input("How much did the person give you :"))
change = money - cost
print("The persons' change is %1.2f" % change)

remain = change
twenties = 0
tens = 0
fives = 0
ones = 0
quarters = 0
dimes = 0
nickels = 0
pennies = 0

def print_change_bills():
    if twenties > 0:
        msg = "%d twenties"
        if twenties == 1:
            msg = "%d twenty"
        print(msg % twenties)
    if tens > 0:
        msg = "%d tens"
        if tens == 1:
            msg = "%d ten"
        print(msg % tens)
    if fives > 0:
        msg = "%d fives"
        if fives == 1:
            msg = "%d five"
        print(msg % fives)
    if ones > 0:
        msg = "%d ones"
        if ones == 1:
            msg = "%d one"
        print(msg % ones)
    if quarters > 0:
        msg = "%d quarters"
        if quarters == 1:
            msg = "%d quarter"
        print(msg % quarters)

if remain >= 20 :
    twenties = int(remain) // 20
else:
    twenties = 0

remain = remain - 20 * twenties
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 10:
    tens = int(remain) // 10
else:
    tens = 0

remain = remain - 10 * tens
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 5:
    fives = int(remain) // 5
else:
    fives = 0

remain = remain - 5 * fives
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 1:
    ones = int(remain)
else:
    ones = 0

remain = (float)(remain - ones)
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 0.25:
    quarters = (int)(remain / 0.2)
else:
    quarters = 0

remain = remain - quarters * 0.25

print_change_bills()

if remain > 0.00:
    print("Bill is %1.2f" % remain)


def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

# Ask for user input
n = int(input("Enter a number: "))

# Check and print prime numbers
for i in range(2, n+1):
    if is_prime(i):
        print(i)


import sys
import gtk
from gettext import gettext as _

import tcosmonitor.shared
import os

def print_debug(txt):
    if tcosmonitor.shared.debug:
        print >> sys.stderr, "%s::%s" % (__name__, txt)
        #print("%s::%s" % (__name__, txt), file=sys.stderr)

class TcosClassView(object):
    def __init__(self, main):
        print_debug("__init__()")
        self.main=main
        self.ui=self.main.ui
        self.hosts={}
        self.__selected_icon=None
        self.selected=[]
        self.class_external_exe=None
        self.class_external_video=None
        self.class_external_send=None
        self.avalaible_info=[
                    [_("IP"), 'ip' ],
                    [ _("Hostname"), 'hostname' ],
                    [ _("Username"), 'username'],
                    [ _("Logged"), 'logged'],
                    [ _("Time log in"), 'time_logged'],
                    [ _("Screen locked"), 'blocked_screen'],
                    [ _("Network locked"), 'blocked_net'],
                        ]
        self.default_tip = _("Place mouse on any computer to see brief info about it.\n\
You can select and unselect multiple host clicking on every one.\n\
Drag and drop hosts to positions and save clicking on right mouse button.")

        self.icon_tooltips = None

        self.classview=self.ui.get_object('classview')
        self.classeventbox=self.ui.get_object('classeventbox')
        self.classeventbox1=self.ui.get_object('classeventbox1')
        self.classview.drag_dest_set(gtk.DEST_DEFAULT_MOTION |
                                  gtk.DEST_DEFAULT_HIGHLIGHT |
                                  gtk.DEST_DEFAULT_DROP,
                                  [], gtk.gdk.ACTION_MOVE)
        self.classview.drag_dest_set(0, [], 0)
        self.classview.connect('drag_motion', self.motion_cb)
        self.classview.connect('drag_drop', self.on_drag_data_received)
        self.classeventbox.connect("button_press_event", self.on_classview_click)
        #self.classeventbox.connect("size-allocate", self.get_max_pos)
        self.classeventbox.connect("motion-notify-event", self.on_classview_event)

        self.oldpos={}
        #self.classview.set_size_request(200, 200)
        self.initialX=10
        self.initialY=10
        self.position=[10,10]
        self.iconsize=[115,115]

        # gtk.Frame don't support changing background color (default gray) use gtk eventbox
        print_debug("setting white background")
        self.classeventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("white"))
        self.classeventbox1.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('white'))
        self.loadpos()

    def get_max_pos(self, *args):
        x, y, width, height = self.classeventbox.get_allocation()
        #print_debug("get_max_pos() width=%s height=%s"%(width, height))
        return [width, height]

    def isenabled(self):
        """
        return True if only configuration enable IconView
        prevent to work if ClassView is hidden
        """
        if self.main.config.GetVar("listmode") == 'icons' or \
             self.main.config.GetVar("listmode") == 'both' or \
             self.main.config.GetVar("listmode") == 'class':
            return True
        return False

    def isactive(self):
        """
        Return True if IconView is enabled and is active (We click on it)
        know this getting tabindex of viewtabas widget.
          0 => active list view
          1 => active icon view
        """
        if not self.isenabled:
            return False
        if self.main.viewtabs.get_current_page() != 2:
            return False
        #print_debug("isactive() ClassView Mode active")
        return True

    def set_selected(self, ip):
        self.__selected_icon=ip

    def get_selected(self):
        return self.__selected_icon

    def get_host(self, ip):
        if self.hosts.has_key(ip):
            return self.hosts[ip]['hostname']

    def __increment_position(self):
        maxpos=self.get_max_pos()
        #print_debug("__increment_position() self.position[0](%s) >= maxpos[0](%s) -self.iconsize[0](%s)"%(self.position[0], maxpos[0], self.iconsize[0]))
        if self.position[0] + self.iconsize[0] >= maxpos[0] - self.iconsize[0]:
            #print_debug("__increment_position() NEW FILE")
            self.position[1]=self.position[1]+self.iconsize[1]
            self.position[0]=self.initialX
        else:
            self.position[0]=self.position[0]+self.iconsize[0]
        print_debug("__increment_position()  position=%s"%(self.position))

    def __getoverride(self, ax, ay, aip):
        # read oldpos to know override saved settings
        for h in self.oldpos:
            if h == aip:
                # self movement
                continue
            x, y = self.oldpos[h]
            diffx=abs(ax-x) - (self.iconsize[0]-5)
            diffy=abs(ay-y) - (self.iconsize[1]-20)
            if diffx < 0 and diffy < 0:
                #print_debug("__getoverride() h=%s self.oldpos[h]=%s => [%s,%s] diffx=%s diffy=%s"%(h, self.oldpos[h], ax, ay, diffx, diffy))
                return True
        # read pos of printed icons
        for w in self.classview.get_children():
            x, y, width, height = w.get_allocation()
            ip=[]
            for c in w.get_children():
                c.get_model().foreach(lambda model, path, iter: ip.append(model.get_value(iter, 1)) )
            if aip == ip[0]:
                # self movement
                continue
            diffx=abs(ax-x) - (self.iconsize[0]-5)
            diffy=abs(ay-y) - (self.iconsize[1]-20)
            #print_debug("__getoverride() ### POSITION ### Elem[%s,%s] new[%s,%s] => abs(ax-x)=%s abs(ay-y)=%s restax=%s restay=%s"%(x,y,ax,ay,abs(ax-x), abs(ay-y), diffx, diffy ))
            if diffx < 0 and diffy < 0:
                print_debug("__getoverride() ### POSITION ### Elem[%s,%s] new[%s,%s] => abs(ax-x)=%s abs(ay-y)=%s restax=%s restay=%s"%(x, y, ax, ay, abs(ax-x), abs(ay-y), diffx, diffy ))
                return True
        return False

    def savepos(self, widget, action):
        if action == "reset":
            self.oldpos={}
            self.main.config.SetVar("positions", "")
            self.main.config.SaveToFile()
            print_debug("savepos() reset to %s"%self.oldpos)
            self.main.write_into_statusbar( _("Positions reset to defaults.") )
            return
        for w in self.classview.get_children():
            x, y, width, height = w.get_allocation()
            ip=[]
            for c in w.get_children():
                c.get_model().foreach(lambda model, path, iter: ip.append(model.get_value(iter, 1)) )
            print_debug("savepos() ### POSITION ### x=%s y=%s width=%s height=%s ip=%s"%(x, y, width, height, ip))
            self.oldpos[ip[0]]=[x,y]
        print_debug("savepos() self.oldpos=%s"%self.oldpos)
        txt=""
        for ip in self.oldpos:
            txt+="%s:%s:%s,"%(ip, self.oldpos[ip][0], self.oldpos[ip][1] )
        # remove last coma
        txt=txt[:-1]
        print_debug("savepos() txt=%s"%txt)
        self.main.config.SetVar("positions", txt)
        self.main.config.SaveToFile()
        self.main.write_into_statusbar( _("Positions saved.") )

    def loadpos(self):
        print_debug("loadpos()")
        txt=self.main.config.GetVar("positions")
        if txt == "":
            return
        self.oldpos={}
        a=txt.split(',')
        for host in a:
            if len(host) < 1:
                continue
            h=host.split(':')
            self.oldpos[h[0]]=[int(h[1]),int(h[2])]
        print_debug("loadpos() self.oldpos=%s"%self.oldpos)

    def clear(self):
        for w in self.classview.get_children():
            w.destroy()
        self.position=[self.initialX,self.initialY]
        print_debug("clear() restore position to %s"%(self.position))
        self.selected=[]

    def generate_icon(self, data):
        print_debug("generate_icon() ip=%s hostname=%s"%(data['ip'], data['hostname']) )

        iconview=gtk.IconView()
        model = gtk.ListStore(str, str, gtk.gdk.Pixbuf)
        if data['username'] == tcosmonitor.shared.NO_LOGIN_MSG and not data['standalone']:
            pixbuf = gtk.gdk.pixbuf_new_from_file(tcosmonitor.shared.IMG_DIR + tcosmonitor.shared.icon_image_no_logged)
        elif data['standalone']:
            pixbuf = gtk.gdk.pixbuf_new_from_file(tcosmonitor.shared.IMG_DIR + tcosmonitor.shared.icon_image_standalone)
        else:
            pixbuf = gtk.gdk.pixbuf_new_from_file(tcosmonitor.shared.IMG_DIR + tcosmonitor.shared.icon_image_thin)

        if not data['active']:
            pixbuf.saturate_and_pixelate(pixbuf, 0.6, True)

        if data['image_blocked']:
            pixbuf2 = data['image_blocked']
            print_debug("generate_icon() compositing isblocked=True")
            pixbuf2.composite(pixbuf, 0, 0, pixbuf.props.width, pixbuf.props.height, 0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)

        iconview.set_model(model)
        iconview.set_text_column(0)
        iconview.set_pixbuf_column(2)
        if hasattr(iconview.props, 'has_tooltip'):
            iconview.props.has_tooltip = True

        #if data['username'] == tcosmonitor.shared.NO_LOGIN_MSG:
        #    model.append([data['username'], data['ip'], pixbuf])
        # show hostname instead of username in standalone
        if data['standalone']:
            model.append([data['hostname'].split('.')[0], data['ip'], pixbuf])
        else:
            model.append([data['username'], data['ip'], pixbuf])

        iconview.show()
        # in old versions of gtk we need to put explicity iconview size
        if gtk.gtk_version < (2, 10, 0):
            iconview.set_size_request(pixbuf.props.width+14, pixbuf.props.height+28)

        # connect drag and drop signal with external data
        iconview.drag_dest_set( gtk.DEST_DEFAULT_ALL, [( 'text/uri-list', 0, 2 ), ], gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_COPY)
        iconview.connect( 'drag_data_received', self.on_external_drag_data_received, data['ip'])

        #iconview.set_size_request(110,110)
        iconview.set_item_width(82)
        button = gtk.Button()
        button.set_relief(gtk.RELIEF_NONE)
        button.add(iconview)

        button.drag_source_set(gtk.gdk.BUTTON1_MASK, [], gtk.gdk.ACTION_COPY)
        if data['active']:
            button.connect("button_press_event", self.on_iconview_click, data['ip'])
        button.connect("enter", self.on_button_enter, data['ip'])
        button.set_size_request(111, 113)
        button.show_all()

        if self.oldpos.has_key(data['ip']):
            # we have and old possition
            print_debug("generate_icon() found old position => %s"%self.oldpos[data['ip']])
            self.classview.put(button, self.oldpos[data['ip']][0], self.oldpos[data['ip']][1] )
        else:
            #while self.__getoverride(self.position[0], self.position[1], data['ip'] ):
            #    print_debug("generate_icon() OVERRIDE ICON !!!")
            #    self.__increment_position()
            self.classview.put(button, self.position[0], self.position[1])
            print_debug("generate_icon() put not positioned icon at [%s,%s] !!!"%(self.position[0], self.position[1]))
            self.__increment_position()

        self.hosts[data['ip']]=data

    def on_external_drag_data_received( self, widget, context, x, y, selection, targetType, dtime, ip_recv):
        ip=None
        if not self.ismultiple():
            if not ip_recv:
                return
            ip=ip_recv
            self.set_selected(ip)
        print_debug("get_selected()=%s get_multiple()=%s" %(self.get_selected(), self.get_multiple()))
        filenames=[]
        files = selection.data.split('\n')
        extensions = (".avi", ".mpg", ".mpeg", ".ogg", ".ogm", ".asf", ".divx",
                    ".wmv", ".vob", ".m2v", ".m4v", ".mp2", ".mp4", ".ac3",
                    ".ogg", ".mp1", ".mp2", ".mp3", ".wav", ".wma")
        print_debug("on_external_drag_data_received() files=%s dtime=%s ip=%s"%(files, dtime, ip))
        for f in files:
            if f:
                filenames.append(f.strip().replace('%20', ' '))
                #break
        if len(filenames) < 1:
            return

        if filenames[0].startswith('file:///') and filenames[0].lower().endswith('.desktop') and os.path.isfile(filenames[0][7:]):
            if self.class_external_exe != None:
                self.class_external_exe(filenames[0][7:])
                print_debug("get_selected() ip=%s file=%s" %(self.get_selected(), filenames[0][7:]))
        elif filenames[0].startswith('file:///') and filter(filenames[0].lower().endswith, extensions) and os.path.isfile(filenames[0][7:]):
            if self.class_external_video != None:
                self.class_external_video(filenames[0][7:])
                print_debug("get_selected() ip=%s file=%s" %(self.get_selected(), filenames[0][7:]))
        elif filenames[0].startswith('file:///') and os.path.isfile(filenames[0][7:]):
            if self.class_external_send != None:
                self.class_external_send(filenames)
                print_debug("get_selected() ip=%s file=%s" %(self.get_selected(), filenames))
        else:
            tcosmonitor.shared.error_msg( _("%s is not a valid file to exe or send") %(os.path.basename(filenames[0][7:])) )
        return True

    def on_drag_data_received(self, widget, context, x, y, dtime):
        button=context.get_source_widget()
        if not button:
            #print context
            #print dir(context)
            #print context.get_data()
            #print context.targets
            print_debug("on_drag_data_received() no button detected")
            return
        bx, by, width, height = button.get_allocation()
        # calculate newx and newy with valid positions
        newx=x-(width/2)
        newy=y-(height/2)
        maxpos=self.get_max_pos()
        if newx < 0:
            newx=10
        if newy < 0:
            newy=10
        print_debug("on_drag_data_received() newx=%s newy=%s maxpos[0]=%s maxpos[1]=%s"%(newx, newy, maxpos[0], maxpos[1]))
        if newx > maxpos[0]:
            print_debug("on_drag_data_received() newx=%s > maxpos[0]=%s or negative"%(newx, maxpos[0]))
            return
        if newy > maxpos[1]:
            print_debug("on_drag_data_received() newy=%s > maxpos[1]=%s or negative"%(newy, maxpos[1]))
            return
        # get button ip address and pass to __getoverride to not put 2 hosts (with different IP) in same position
        ip=[]
        for c in button.get_children():
            c.get_model().foreach(lambda model, path, iter: ip.append(model.get_value(iter, 1)) )
        if self.hosts[ip[0]]['active']:
            # set unselect if host is active
            self.change_select(c, ip[0])
        #if self.__getoverride(newx, newy, ip[0]):
        #    print_debug("on_drag_data_received() ip=%s another host is near x=%s y=%s, don't move!!"%(ip[0], x, y) )
        #    self.main.write_into_statusbar( _("Can't move icon, another host is near.") )
        #    return
        self.classview.move(button, newx, newy)

    def motion_cb(self, widget, context, x, y, time):
        context.drag_status(gtk.gdk.ACTION_MOVE, time)
        return True

    def change_select(self, widget, ip):
        #print_debug("change_colour() ip=%s widget=%s"%(ip,widget))
        colour_selected=gtk.gdk.color_parse("#98ec98") # green
        colour_white=gtk.gdk.color_parse("white")
        style = widget.get_style().copy()

        if self.isselected(ip):
            style.base[gtk.STATE_NORMAL] = colour_white
            style.base[gtk.STATE_PRELIGHT] = colour_white
            self.set_unselect(ip)
        else:
            style.base[gtk.STATE_NORMAL] = colour_selected
            style.base[gtk.STATE_PRELIGHT] = colour_selected
            self.set_select(ip)
        widget.set_style(style)

    def on_iconview_click(self, widget, event, ip):
        if event.button == 3:
            # right click show menu
            print_debug("on_iconview_click() ip=%s" %(ip))
            self.main.menus.RightClickMenuOne( None , None, ip)
            self.main.menu.popup( None, None, None, event.button, event.time)
            #self.set_select(ip)
            self.set_selected(ip)
            return True
        if event.button == 1:
            # select host (change color) and call set_selected or set_unselected
            for c in widget.get_children():
                self.change_select(c, ip)

    def on_classview_click(self, iv, event):
        if event.button == 3:
            # need to remake allmenu (for title selected|all )
            #print_debug( "on_classview_click() all=%s"%self.selected )
            self.main.menus.RightClickMenuAll()
            self.main.allmenu.popup( None, None, None, event.button, event.time)
            return

    def on_button_enter(self, button, ip):
        txt=""
        data=self.hosts[ip]
        for info in self.avalaible_info:
            if data[info[1]] == True:
                value=_("yes")
            elif data[info[1]] == False:
                value=_("no")
            else:
                value=data[info[1]]
            txt+=" %s: %s \n" %(info[0], value)
        if hasattr(button, 'set_tooltip_text'):
            button.set_tooltip_text(txt)
        else:
            self.icon_tooltips = gtk.Tooltips() #deprecated
            self.icon_tooltips.set_tip(button, txt)

    def get_multiple(self):
        return self.selected

    def set_select(self, ip):
        print_debug("set_select() ip=%s all=%s"%(ip, self.selected))
        if ip in self.selected:
            return
        self.selected.append(ip)

    def set_unselect(self, ip):
        if self.isselected(ip):
            self.selected.remove(ip)
        print_debug("set_unselect() ip=%s all=%s"%(ip, self.selected))

    def isselected(self, ip):
        if ip in self.selected:
            #print_debug("isselected() TRUE ip=%s"%ip)
            return True
        #print_debug("isselected() FALSE ip=%s"%ip)
        return False

    def ismultiple(self):
        if not self.isactive():
            return False
        print_debug("ismultiple() self.selected=%s"%self.selected)
        if len(self.selected) > 0:
            return True
        else:
            return False

    def on_classview_event(self, widget, event):
        if not event.state:
            #print_debug("on_classview_event() tip")
            if hasattr(widget, 'set_tooltip_text'):
                widget.set_tooltip_text(self.default_tip)
            else:
                self.icon_tooltips = gtk.Tooltips() # deprecated
                self.icon_tooltips.set_tip(widget, self.default_tip)

    def change_lockscreen(self, ip, pixbuf2, status_screen, status_net):
        print_debug("change_lockscreen() ip=%s pixbuf=%s"%(ip, pixbuf2))
        self.hosts[ip]['blocked_screen']=status_screen
        self.hosts[ip]['blocked_net']=status_net
        data=self.hosts[ip]
        if data['username'] == tcosmonitor.shared.NO_LOGIN_MSG:
            pixbuf = gtk.gdk.pixbuf_new_from_file(tcosmonitor.shared.IMG_DIR + tcosmonitor.shared.icon_image_no_logged)
        else:
            pixbuf = gtk.gdk.pixbuf_new_from_file(tcosmonitor.shared.IMG_DIR + tcosmonitor.shared.icon_image_thin)
        pixbuf2.composite(pixbuf, 0, 0, pixbuf.props.width, pixbuf.props.height, 0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)
        for w in self.classview.get_children():
            for c in w.get_children():
                model=c.get_model()
                if model[0][1] == ip:
                    model2 = gtk.ListStore(str, str, gtk.gdk.Pixbuf)
                    c.set_model(model2)
                    c.set_text_column(0)
                    c.set_pixbuf_column(2)
                    if data['username'] == tcosmonitor.shared.NO_LOGIN_MSG:
                        model2.append([data['hostname'].replace('.aula',''), data['ip'], pixbuf])
                    else:
                        model2.append([data['username'], data['ip'], pixbuf])
                    #model[0][2]=pixbuf
                    return


"""
=====
Distributed by: Notre Dame SCAI Lab (MIT Liscense)
- Associated publication:
url: https://arxiv.org/abs/2010.03957
doi:
github: https://github.com/zabaras/transformer-physx
=====
"""
import logging
import os, sys
from abc import abstractmethod

import torch
from torch import nn
from .utils import  Conv1D

logger = logging.getLogger(__name__)

class PhysformerBase(nn.Module):
    """Parent class for physical transformers
    """
    model_name: str = "transformer_model"

    def __init__(self, config, *inputs, **kwargs):
        super().__init__(*inputs, **kwargs)
        # Save config in model
        self.config = config

    @abstractmethod
    def forward(self):
        pass

    @abstractmethod
    def generate(self):
        pass

    def get_input_embeddings(self):
        # TODO: Is this really needed?
        return self.wte

    def set_input_embeddings(self, new_embeddings):
        # TODO: Is this really needed?
        self.wte = new_embeddings

    def _init_weights(self, module):
        """ Initialize the weights.
        """
        if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
            if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.LayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)

    def _num_parameters(self) -> int:
        """Gets number of learnable parameters

        Returns:
            int: Number of parameters
        """
        count = 0
        for name, param in self.named_parameters():
            # print(name, param.numel())
            count += param.numel()
        return count

    def tie_weights(self):
        """
        Tie the weights between the input embeddings and the output embeddings.
        If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning
        the weights instead.
        """
        output_embeddings = self.get_output_embeddings()
        if output_embeddings is not None:
            self._tie_or_clone_weights(output_embeddings, self.get_input_embeddings())

    def _tie_or_clone_weights(self, output_embeddings, input_embeddings):
        """ Tie or clone module weights depending of whether we are using TorchScript or not
        """
        if self.config.torchscript:
            output_embeddings.weight = nn.Parameter(input_embeddings.weight.clone())
        else:
            output_embeddings.weight = input_embeddings.weight

        if getattr(output_embeddings, "bias", None) is not None:
            output_embeddings.bias.data = torch.nn.functional.pad(
                output_embeddings.bias.data,
                (0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0],),
                "constant",
                0,
            )
        if hasattr(output_embeddings, "out_features") and hasattr(input_embeddings, "num_embeddings"):
            output_embeddings.out_features = input_embeddings.num_embeddings

    def save_model(self, save_directory: str, epoch: int = 0) -> None:
        """Saves transformer model to the specified directory.

        Args:
            save_directory (str): Folder to save file at
            epoch (int, optional): Epoch number to name model file. Defaults to 0.

        Raises:
            AssertionError: If provided directory is not valid.
        """
        if os.path.isfile(save_directory):
            raise AssertionError("Provided path ({}) should be a directory, not a file".format(save_directory))

        os.makedirs(save_directory, exist_ok=True)
        # If we save using the predefined names, we can load using `from_pretrained`
        output_model_file = os.path.join(save_directory, "{}{:d}.pth".format(self.model_name, epoch))
        # Save pytorch model to file
        torch.save(self.state_dict(), output_model_file)

    def load_model(self, file_or_path_directory: str, epoch: int = 0) -> None:
        """Load a transformer model from the specified file or path

        Args:
            file_or_path_directory (str): File or folder path to load state dictionary from.
            epoch (int, optional): Epoch of current model for file name, used if folder path is provided. Defaults to 0.

        Raises:
            FileNotFoundError: If provided file or directory could not be found.
        """
        if os.path.isfile(file_or_path_directory):
            logger.info('Loading embedding model from file: {}'.format(file_or_path_directory))
            self.load_state_dict(torch.load(file_or_path_directory, map_location=lambda storage, loc: storage))
        elif  os.path.isdir(file_or_path_directory):
            file_path = os.path.join(file_or_path_directory, "{}{:d}.pth".format(self.model_name, epoch))
            logger.info('Loading embedding model from file: {}'.format(file_path))
            self.load_state_dict(torch.load(file_path, map_location=lambda storage, loc: storage))
        else:
            raise FileNotFoundError("Provided path or file ({}) does not exist".format(file_or_path_directory))


#!/usr/bin/python2.7

import numpy as np
import math
import time
from bool_func import *
from socket_funcs import *

# returns hamming distance between two INTEGERS (by calculating binary hamming)
def ham10(x,y):
    '''
    x is first value, y is the second value
    IE 110 and 001 = hamming distance of 3 then
       6   and 1   = hamming distance of 3
    '''
    return bin(x^y).count('1')

socket_in = './rx1_send.uds'
socket_out= './rx2_send.uds'

# Open Server Socket
s = open_socket_serv(socket_out)

while(1):
    output_stream = socket_recv(socket_in)

    ###################
    # Viterbi Decoder #
    ###################

    # Convert (binary) symbols in output stream to 0,1,2,3
    sym = np.empty(len(output_stream)/2, dtype=np.int8)
    j = i = 0
    while i < len(output_stream):
        if output_stream[i] == 0 and output_stream[i+1] == 0:
            sym[j] = 0
        elif output_stream[i] == 0 and output_stream[i+1] == 1:
            sym[j] = 1
        elif output_stream[i] == 1 and output_stream[i+1] == 0:
            sym[j] = 2
        elif output_stream[i] == 1 and output_stream[i+1] == 1:
            sym[j] = 3
        i += 2
        j += 1

    # calculate Accumulated Error Metrics (aem)
    aem = np.empty((len(sym),4), dtype=np.int8) # (index, state#0-3)

    # t0->t1
    aem[0,0] = ham10(sym[0], 0)
    aem[0,1] = aem[0,3] = 666  # these will never be a valid starting state
    aem[0,2] = ham10(sym[0], 3)

    # t1->t2
    aem[1,0] = ham10(sym[1], 0) + aem[0,0]
    aem[1,1] = ham10(sym[1], 2) + aem[0,2]
    aem[1,2] = ham10(sym[1], 3) + aem[0,0]
    aem[1,3] = ham10(sym[1], 1) + aem[0,2]

    # t2 -> t_end
    for i in range(2,len(sym)):

        # aem for state zero
        if ( ham10(sym[i], 0) + aem[(i-1),0] <= ham10(sym[i], 3) + aem[(i-1),1] ):
            aem[i,0] = ham10(sym[i], 0) + aem[(i-1),0]
        else:
            aem[i,0] = ham10(sym[i], 3) + aem[(i-1),1]

        # aem for state one
        if ( ham10(sym[i], 2) + aem[(i-1),2] <= ham10(sym[i], 1) + aem[(i-1),3] ):
            aem[i,1] = ham10(sym[i], 2) + aem[(i-1),2]
        else:
            aem[i,1] = ham10(sym[i], 1) + aem[(i-1),3]

        # aem for state two
        if ( ham10(sym[i], 3) + aem[(i-1),0] <= ham10(sym[i], 0) + aem[(i-1),1] ):
            aem[i,2] = ham10(sym[i], 3) + aem[(i-1),0]
        else:
            aem[i,2] = ham10(sym[i], 0) + aem[(i-1),1]

        # aem for state three
        if ( ham10(sym[i], 1) + aem[(i-1),2] <= ham10(sym[i], 2) + aem[(i-1),3] ):
            aem[i,3] = ham10(sym[i], 1) + aem[(i-1),2]
        else:
            aem[i,3] = ham10(sym[i], 2) + aem[(i-1),3]

    # These states are invalid choices for traceback == inf
    aem[len(sym)-1,3] = aem[len(sym)-1,2] = aem[len(sym)-1,1] = aem[len(sym)-2,3] = \
    aem[len(sym)-2,2] = 666

    # Traceback to receive origin states
    stht = np.empty(len(sym)) # state history table
    stht[0] = current_state = 0 # current best path state
    for i in range(len(sym)-1,0,-1):
        if current_state == 0: # prev possible states are 0 and 1
            if aem[i,0] < aem[i,1]:
                stht[i] = 0
            elif aem[i,0] > aem[i,1]:
                stht[i] = 1
            else:
                # print("Error S0: equal error metrics during traceback")
                stht[i] = 0 # arbitrary assignment
        elif current_state == 1: # prev possible states are 2 and 3
            if aem[i,2] < aem[i,3]:
                stht[i] = 2
            elif aem[i,2] > aem[i,3]:
                stht[i] = 3
            else:
                # print("Error S1: equal error metrics during traceback")
                stht[i] = 3 # arbitrary assignment
        elif current_state == 2: # prev possible states are 0 and 1
            if aem[i,0] < aem[i,1]:
                stht[i] = 0
            elif aem[i,0] > aem[i,1]:
                stht[i] = 1
            else:
                # print("Error S2: equal error metrics during traceback")
                stht[i]=0 # arbitrary assignment
        else: # prev possible states are 2 and 3
            if aem[i,2] < aem[i,3]:
                stht[i] = 2
            elif aem[i,2] > aem[i,3]:
                stht[i] = 3
            else:
                # print("Error S3: equal error metrics during traceback")
                stht[i] = 3 # arbitrary assignment
        current_state = stht[i]

    # Inserts the (guaranteed) initial first zero state
    stht = np.insert(stht,0,0)

    # Decode bitstream from state history table
    decoded_message = np.empty(len(sym),dtype=np.int8)

    for i in range(0,len(stht)-1):
        if stht[i+1] < stht[i] or stht[i+1] == stht[i] and stht[i] == 0:
            decoded_message[i] = 0
        elif stht[i+1] > stht[i] or stht[i+1] == stht[i] and stht[i] == 3:
            decoded_message[i] = 1
    decoded_message = np.delete(decoded_message,-1)

    # tx_message = pack_bits(decoded_message)
    socket_serv(s,decoded_message)

s.close()


#  File: FibonacciBase.py

#  Description: Homework#8

#  Student Name: Julio Gonzalez

#  Student UT EID: jcg3245

#  Course Name: CS 303E

#  Unique Number: 50860

#  Date Created: 4/30/16

#  Date Last Modified: 4/30/16

def main():
  number = eval(input("Enter a number: "))
  a = 0
  b = 1
  c = 0
  d = 0
  fib_list = []
  while d < number:
    d += c
    c = a + b
    a = b
    b = c
    fib_list.append(c)
  rev_list = fib_list[::-1]
  diff = number - rev_list[0]
  print(number, "= ", end = "")
  if rev_list[0] == number:
    print("1", end = "")
    rev_list.pop(0)
  else:
    rev_list.pop(0)
    print("1", end = "")
  for i in rev_list:
    if diff >= i:
      print("1", end = "" )
      diff = diff - i
    else:
      print("0", end = "")
  print(" (fib)")

main()


from typing import List, Tuple, Dict

import numpy as np

from watts.solvers.base import BaseSolver
from watts.generators.base import BaseGenerator
from watts.validators.level_validator import LevelValidator
from watts.validators.agent_validator import RandomAgentValidator, ParentCutoffValidator, _eval_solver_on_generator

class DeepMindFullValidator(LevelValidator):
    """Is the new level too easy as measured by the parent's zero-shot performance on it
    and a random agent's performance? Yes/No?"""
    def __init__(self,
                 network_factory_monad,
                 env_config: dict,
                 low_cutoff: float = -np.inf,
                 high_cutoff: float = np.inf,
                 margin: float = 0.01,
                 n_tasks_difference_greater_than_margin: int = 2,
                 n_tasks_parent_greater_than_high: int = 4,
                 n_repeats: int = 5):
        """

        @param network_factory_monad: network factory build fn for the random agent validator
        @param env_config: env_config info for both validators
        @param low_cutoff: lower bound of what's too hard. default is -inf
        @param high_cutoff: upper bound of what is too easy. default is inf
        @param margin: By how much should the learned agent do better than the baseline? float = 0.01,
        @param n_tasks_difference_greater_than_margin: For how many games should the learned agent minus baseline do better than the margin? Must be less than n_repeats. int = 2,
        @param n_tasks_parent_greater_than_high: For how many games should the learned agent perform better the high_cutoff before the task is considered solved? int = 4,
        @param n_repeats: number of times to run an evaluate
        """
        self.n_repeats = n_repeats
        assert n_tasks_parent_greater_than_high <= n_repeats
        assert n_tasks_difference_greater_than_margin <= n_repeats
        # using deepmind's notation in the comments
        # this is m_>
        self.margin = margin
        # this is m_s
        self.high_cutoff = high_cutoff
        # this is m_cont
        self.low_cutoff = low_cutoff
        # this is m_>_cont
        self.p_just_right = n_tasks_difference_greater_than_margin / self.n_repeats
        # this is m_solved
        self.p_solved_cutoff = n_tasks_parent_greater_than_high / self.n_repeats

        self.random_agent_validator = RandomAgentValidator(network_factory_monad, env_config,
                                                           low_cutoff, high_cutoff, n_repeats)
        self.parent_validator = ParentCutoffValidator(env_config, low_cutoff, high_cutoff, n_repeats)

    def validate_level(self,  generators: List[BaseGenerator], solvers: List[BaseSolver], **kwargs) -> Tuple[bool, Dict]:
        """

        @param generators: Generator class that we can extract a level string from
        @param solvers: Solver class that can play a game
        @param kwargs: future proofing
        :return: True/False is this level a good level to use?
        """
        _, random_agent_data = self.random_agent_validator.validate_level(generators=generators, solvers=solvers)
        _, parent_data = self.parent_validator.validate_level(generators=generators, solvers=solvers)

        # on average, the random policy scores less than low_cutoff
        #   a control policy return threshold 𝑚cont = 5 would [remove] any training tasks where a control policy is
        #   able to get a return of at least 5
        too_easy_for_random = np.any(random_agent_data['scores'] >= self.low_cutoff)
        # on average, does the parent do better than random by some margin
        #   The combination, for example, of
        #   𝑚> = 2 and 𝑚>cont = 0.9 would only allow training tasks
        #   where the agent achieves a return in all ten episode samples
        #   of at least 2 reward more than the return achieved by the
        #   control policy
        #
        # we don't collapse the runs yet. We want to know on how many runs did we exceed
        # the margin by? This should be vector subtraction.
        difference = parent_data['scores'] - random_agent_data['scores']
        parent_is_better_than_random = np.mean(difference >= self.margin) > self.p_just_right
        # agent has low probability of scoring high on a given task
        #   As a final example, the combination of
        #   𝑚s = 450 and 𝑚solved = 0.1 would disallow training on
        #   any task where the agent is able to achieve more than 450
        #   reward on any of its episode samples
        not_too_easy_for_parent = np.mean(parent_data['scores'] >= self.high_cutoff) < self.p_solved_cutoff

        data = {
            'ran_val': random_agent_data,
            'pcv_val': parent_data,
        }

        if not too_easy_for_random and parent_is_better_than_random and not_too_easy_for_parent:
            return True, data
        else:
            return False, data

class DeepMindAppendixValidator(LevelValidator):
    """Is the new level too easy or too hard as measured by the parent's zero-shot performance on it?
     Yes/No?"""
    def __init__(self,
                 env_config: dict,
                 low_cutoff: float = -np.inf,
                 n_repeats: int = 100):
        """

        @param env_config: env_config info for both validators
        @param low_cutoff: lower bound of what's too hard. default is -inf
        @param n_repeats: number of times to run an evaluate
        """
        self.config = env_config
        self.low_cutoff = low_cutoff
        self.n_repeats = n_repeats

    def validate_level(self,  generators: List[BaseGenerator], solvers: List[BaseSolver], **kwargs) -> Tuple[bool, Dict]:
        """

        @param generators: Generator class that we can extract a level string from
        @param solvers: Solver class that can play a game
        @param kwargs: future proofing
        :return: True/False is this level a good level to use?
        """
        scores = []
        wins = []
        for n in range(self.n_repeats):
            win, score, _ = _eval_solver_on_generator(generator=generators[0], solver=solvers[0], config=self.config)
            scores.append(score)
            wins.append(win)
        # if agent scores equal to or better than low_cutoff at least once
        scores = np.array(scores)
        not_too_hard = np.any(scores >= self.low_cutoff)
        # agent scores equal to or better than low_cutoff on less than or equal to half of its rollouts
        not_too_easy = np.sum(scores >= self.low_cutoff) <= (self.n_repeats // 2)
        return not_too_easy and not_too_hard, {'scores': np.array(scores),
                                               'wins': np.array(wins)}


# Configuration file for the Sphinx documentation builder.

# -- Project information

import inspect
import uniport

import sphinx_autodoc_typehints

project = 'uniPort'
copyright = u'2022, Kai Cao'
author = 'Kai Cao'

release = uniport.__version__
version = uniport.__version__

# -- General configuration

extensions = [
    'sphinx.ext.duration',
    'sphinx.ext.doctest',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.intersphinx',
    'sphinx.ext.viewcode',
    'sphinx_markdown_tables',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.napoleon',
    'sphinx_copybutton',
    'nbsphinx',
    'myst_parser',
]

# Generate the API documentation when building
autosummary_generate = True
autodoc_member_order = 'bysource'

napoleon_google_docstring = False
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_use_rtype = True  # having a separate entry generally helps readability
napoleon_use_param = True
napoleon_custom_sections = [('Params', 'Parameters')]
todo_include_todos = False

intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'sphinx': ('https://www.sphinx-doc.org/en/master/', None),
}
intersphinx_disabled_domains = ['std']

templates_path = ['_templates']
html_static_path = ['_static']
html_logo = '_static/uniPort.png'

# -- Options for HTML output

html_theme = 'sphinx_rtd_theme'

# -- Options for EPUB output
epub_show_urls = 'footnote'

# latex_engine = 'xelatex'
# latex_use_xindy = False
# latex_elements = {
#     'preamble': '\\usepackage[UTF8]{ctex}\n',
# }

html_theme_options = dict(navigation_depth=4, logo_only=True)  # Only show the logo

from recommonmark.parser import CommonMarkParser
source_parsers = {
    '.md': CommonMarkParser,
}
source_suffix = ['.rst', '.md']


# data visualization
import matplotlib.pyplot as plt

# numeric analysis
import pandas as pd
import numpy as np

# Random forest classifier
from sklearn.ensemble import RandomForestClassifier

# oversampling methods
from imblearn.over_sampling import RandomOverSampler
from imblearn.over_sampling import SMOTE
from imblearn.over_sampling import BorderlineSMOTE
from imblearn.over_sampling import SVMSMOTE
from imblearn.over_sampling import ADASYN
from imblearn.pipeline import Pipeline

from eval_cost_sensitive_ML import (evaluate_model,
                                    verbosity_for_summary_stats,
                                    get_scores)

def RF_model():
	"""
	Random Forest classifier with cost sensitive settings

	Returns
	-------
	model
		Random Forest model
	"""	""
	return RandomForestClassifier(n_estimators=1000,
	                              class_weight='balanced',
	                              random_state=1,
	                              n_jobs=-1)

def get_oversampling_models(SEED=1):
	"""
	get_oversampling_models gets oversampling models

	Parameters
	----------
	SEED : int, optional
		set seed for reproduciblity, by default 1

	Returns
	-------
	models
		models

	"""""

	models, names = list(), list()

	# RandomOverSampler
	models.append(RandomOverSampler(random_state=SEED))
	names.append('ROS')

	# SMOTE
	models.append(SMOTE(random_state=SEED))
	names.append('SMOTE')

	# BorderlineSMOTE
	models.append(BorderlineSMOTE())
	names.append('BLSMOTE')

	# SVMSMOTE
	models.append(SVMSMOTE())
	names.append('SVMSMOTE')

	# ADASYN
	models.append(ADASYN())
	names.append('ADASYN')

	return models, names

def run_oversampling_models(X,y, verbose=True, show_plots=True,  savefigure=False,  figure_name=None):
	"""
	run_oversampling_models evaluates oversampling methods with Random Forest

	Parameters
	----------
	X : DataFrame/Numpy arrays
		inputs
	y : DataFrame/Numpy arrays
		output
	verbose : bool, optional
		option to see print messages, by default True
	show_plots : bool, optional
		option to show plots as results, by default True
	savefigure : bool, optional
		option to save figure, by default False
	figure_name : str, optional
		name of the figure, by default None

	Returns
	-------
	Numpy arrays
		F1 Score, F0.5 Score, sensitivity and specificity

	Raises
	------
	TypeError
		When the user chooses to save but failed to specify a figure name
	"""    ""

	models, names = get_oversampling_models()
	results = list()

	# evaluate each model
	for i in range(len(models)):

	    model = RF_model()

	    # define the pipeline steps
	    steps = [('o', models[i]), ('m', model)]

	    # define the pipeline
	    pipeline = Pipeline(steps=steps)

	    # evaluate the model and store results
	    scores = evaluate_model(X, y, pipeline)

	    results.append(scores)

	    if verbose:
	        # summarize and store
	        verbosity_for_summary_stats(i=i, scores=scores, names=names)

	f1_scores, f0_5_scores, sensitivity, specificity = get_scores(results=results)

	# create the figure
	fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(12,10))

	ax[0,0].boxplot(f1_scores, labels=names, showmeans=True)
	ax[0,0].set_ylabel('F1 Scores')

	ax[0,1].boxplot(f0_5_scores, labels=names, showmeans=True)
	ax[0,1].set_ylabel('F0.5 Scores')

	ax[1,0].boxplot(sensitivity, labels=names, showmeans=True)
	ax[1,0].set_ylabel('Sensitivity scores')

	ax[1,1].boxplot(specificity, labels=names, showmeans=True)
	ax[1,1].set_ylabel('Specificity scores')

	plt.tight_layout()
	plt.suptitle('Evaluation of Oversampling methods with Random Forest model', y=1.08)

	if show_plots:
	    plt.show()

	if (savefigure==True) and (figure_name==None):
	    raise TypeError('You must pass a name to save the figure')

	elif (savefigure==True) and (figure_name != None):
	    fig.savefig(figure_name, transparent=True, dpi=300)

	return f1_scores, f0_5_scores, sensitivity, specificity


from django.conf.urls import url

import apis.google_api
import apis.views
import apis.watson_api
from . import views

urlpatterns = [
    # development
    url(r'^reversegcdev$', views.reverseGeocoding, name='reversegcDev'),
    url(r'^poidev$', views.poi, name='poiDev'),
    url(r'^gpsdev$', views.gps, name='gpsDev'),

    # final prototypes
    url(r'^reversegc$', views.reverseGeocodingFinal, name='reversegc'),
    url(r'^poi$', views.poiFinal, name='poi'),
    url(r'^gps$', views.gpsFinal, name='gps'),

    # tools
    url(r'^$', views.index_html, name='index'),
    url(r'^whistory$', views.chat_with_history, name='w_history'),
    url(r'^speech$', views.speechrecognition02, name='speech'),
    url(r'^showcompass$', views.showCompass, name='showCompass'),
    url(r'^clicker$', views.mapClicker, name='clicker'),
    url(r'^navigate$', views.navigate, name='navigate'),
    url(r'^oldinterface$', views.navigateCurrentNaviterier, name='oldInterface'),
    url(r'^sb$', views.sandbox, name='sandbox'),

    # APIs
    url(r'^process$', views.processUserInput, name='process_request'),

]


import unittest
import numpy as np

from pricing.analytical.bonds import ZeroCouponBond

class TestPricingZeroCoupon(unittest.TestCase):

    def test_pricing_discrete(self) -> None:
        price = ZeroCouponBond(p=1_000, t=5).price(r=0.05, compounding='discrete')
        self.assertEqual(round(price, 9), 783.526166468)

    def test_pricing_continuous(self) -> None:
        price = ZeroCouponBond(p=1_000, t=5).price(r=0.05, compounding='continuous')
        self.assertEqual(round(price, 9), 778.800783071)

class TestYTMZeroCoupon(unittest.TestCase):

    def test_ytm(self) -> None:
        ytm = ZeroCouponBond(p=1_000, t=5).get_ytm(price=800)
        self.assertEqual(round(ytm, 9), 0.045639553)

    def test_ytm_matching(self) -> None:
        irr = 0.05
        theoretical_price = ZeroCouponBond(p=1_000, t=5).price(r=irr, compounding='discrete')
        ytm = ZeroCouponBond(p=1_000, t=5).get_ytm(price=theoretical_price)
        ytm_matching = np.isclose(ytm, irr)
        self.assertTrue(ytm_matching)

class TestImplementationZeroCoupon(unittest.TestCase):

    def test_string_casting(self) -> None:
        zc_bond = ZeroCouponBond(p=1_000, t=5)
        expected = "ZeroCouponBond object with parameters {'p': 1000, 't': 5}"
        self.assertEqual(str(zc_bond), expected)

    def test_change_existing_param_generic(self) -> None:
        zc_bond = ZeroCouponBond(p=1_000, t=5)
        zc_bond.t = 10
        self.assertTrue(zc_bond.t == 10)

    def test_change_existing_param_method(self) -> None:
        zc_bond = ZeroCouponBond(p=1_000, t=5)
        zc_bond.update_params(t=10)
        self.assertTrue(zc_bond.t == 10)

    def test_add_new_param_generic(self) -> None:
        zc_bond = ZeroCouponBond(p=1_000, t=5)
        try:
            zc_bond.not_existent = 5
            self.assertTrue(False)
        except ValueError as error:
            expected = ValueError("Attribute name <not_existent> is not recognized, use values in ['p', 't']")
            self.assertTrue(type(error) is type(expected) and error.args == expected.args)

    def test_add_new_param_method(self) -> None:
        zc_bond = ZeroCouponBond(p=1_000, t=5)
        try:
            zc_bond.update_params(not_existent=5)
            self.assertTrue(False)
        except ValueError as error:
            expected = ValueError("Attribute name <not_existent> is not recognized, use values in ['p', 't']")
            self.assertTrue(type(error) is type(expected) and error.args == expected.args)

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