# Copyright 2011 Justin Santa Barbara
# Copyright 2012 Hewlett-Packard Development Company, L.P.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import errno
import glob
import os
import shutil
import tempfile
import testtools

import mock
from oslo_concurrency import processutils
from oslotest import base as test_base
import six

from ironic_python_agent import errors
from ironic_python_agent import utils

if six.PY2:
    OPEN_FUNCTION_NAME = '__builtin__.open'
else:
    OPEN_FUNCTION_NAME = 'builtins.open'

class ExecuteTestCase(testtools.TestCase):
    """This class is a copy of the same class in openstack/ironic."""

    def test_retry_on_failure(self):
        fd, tmpfilename = tempfile.mkstemp()
        _, tmpfilename2 = tempfile.mkstemp()
        try:
            fp = os.fdopen(fd, 'w+')
            fp.write('''#!/bin/sh
# If stdin fails to get passed during one of the runs, make a note.
if ! grep -q foo
then
    echo 'failure' > "$1"
fi
# If stdin has failed to get passed during this or a previous run, exit early.
if grep failure "$1"
then
    exit 1
fi
runs="$(cat $1)"
if [ -z "$runs" ]
then
    runs=0
fi
runs=$(($runs + 1))
echo $runs > "$1"
exit 1
''')
            fp.close()
            os.chmod(tmpfilename, 0o755)
            try:
                self.assertRaises(processutils.ProcessExecutionError,
                                  utils.execute,
                                  tmpfilename, tmpfilename2, attempts=10,
                                  process_input=b'foo',
                                  delay_on_retry=False)
            except OSError as e:
                if e.errno == errno.EACCES:
                    self.skipTest("Permissions error detected. "
                                  "Are you running with a noexec /tmp?")
                else:
                    raise
            fp = open(tmpfilename2, 'r')
            runs = fp.read()
            fp.close()
            self.assertNotEqual(runs.strip(), 'failure',
                                'stdin did not always get passed correctly')
            runs = int(runs.strip())
            self.assertEqual(10, runs,
                             'Ran %d times instead of 10.' % (runs,))
        finally:
            os.unlink(tmpfilename)
            os.unlink(tmpfilename2)

    def test_unknown_kwargs_raises_error(self):
        self.assertRaises(processutils.UnknownArgumentError,
                          utils.execute,
                          '/usr/bin/env', 'true',
                          this_is_not_a_valid_kwarg=True)

    def test_check_exit_code_boolean(self):
        utils.execute('/usr/bin/env', 'false', check_exit_code=False)
        self.assertRaises(processutils.ProcessExecutionError,
                          utils.execute,
                          '/usr/bin/env', 'false', check_exit_code=True)

    def test_no_retry_on_success(self):
        fd, tmpfilename = tempfile.mkstemp()
        _, tmpfilename2 = tempfile.mkstemp()
        try:
            fp = os.fdopen(fd, 'w+')
            fp.write('''#!/bin/sh
# If we've already run, bail out.
grep -q foo "$1" && exit 1
# Mark that we've run before.
echo foo > "$1"
# Check that stdin gets passed correctly.
grep foo
''')
            fp.close()
            os.chmod(tmpfilename, 0o755)
            try:
                utils.execute(tmpfilename,
                              tmpfilename2,
                              process_input=b'foo',
                              attempts=2)
            except OSError as e:
                if e.errno == errno.EACCES:
                    self.skipTest("Permissions error detected. "
                                  "Are you running with a noexec /tmp?")
                else:
                    raise
        finally:
            os.unlink(tmpfilename)
            os.unlink(tmpfilename2)

class GetAgentParamsTestCase(test_base.BaseTestCase):

    @mock.patch('oslo_log.log.getLogger')
    @mock.patch(OPEN_FUNCTION_NAME)
    def test__read_params_from_file_fail(self, logger_mock, open_mock):
        open_mock.side_effect = Exception
        params = utils._read_params_from_file('file-path')
        self.assertEqual(params, {})

    @mock.patch(OPEN_FUNCTION_NAME)
    def test__read_params_from_file(self, open_mock):
        kernel_line = 'api-url=http://localhost:9999 baz foo=bar\n'
        open_mock.return_value.__enter__ = lambda s: s
        open_mock.return_value.__exit__ = mock.Mock()
        read_mock = open_mock.return_value.read
        read_mock.return_value = kernel_line
        params = utils._read_params_from_file('file-path')
        open_mock.assert_called_once_with('file-path')
        read_mock.assert_called_once_with()
        self.assertEqual(params['api-url'], 'http://localhost:9999')
        self.assertEqual(params['foo'], 'bar')
        self.assertFalse('baz' in params)

    @mock.patch.object(utils, '_set_cached_params')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(utils, '_get_cached_params')
    def test_get_agent_params_kernel_cmdline(self, get_cache_mock,
                                             read_params_mock,
                                             set_cache_mock):
        get_cache_mock.return_value = {}
        expected_params = {'a': 'b'}
        read_params_mock.return_value = expected_params
        returned_params = utils.get_agent_params()
        read_params_mock.assert_called_once_with('/proc/cmdline')
        self.assertEqual(expected_params, returned_params)
        set_cache_mock.assert_called_once_with(expected_params)

    @mock.patch.object(utils, '_set_cached_params')
    @mock.patch.object(utils, '_get_vmedia_params')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(utils, '_get_cached_params')
    def test_get_agent_params_vmedia(self, get_cache_mock,
                                     read_params_mock,
                                     get_vmedia_params_mock,
                                     set_cache_mock):
        get_cache_mock.return_value = {}
        kernel_params = {'boot_method': 'vmedia'}
        vmedia_params = {'a': 'b'}
        expected_params = dict(list(kernel_params.items()) +
                               list(vmedia_params.items()))
        read_params_mock.return_value = kernel_params
        get_vmedia_params_mock.return_value = vmedia_params

        returned_params = utils.get_agent_params()
        read_params_mock.assert_called_once_with('/proc/cmdline')
        self.assertEqual(expected_params, returned_params)
        # Make sure information is cached
        set_cache_mock.assert_called_once_with(expected_params)

    @mock.patch.object(utils, '_set_cached_params')
    @mock.patch.object(utils, '_get_cached_params')
    def test_get_agent_params_from_cache(self, get_cache_mock,
                                         set_cache_mock):
        get_cache_mock.return_value = {'a': 'b'}
        returned_params = utils.get_agent_params()
        expected_params = {'a': 'b'}
        self.assertEqual(expected_params, returned_params)
        self.assertEqual(0, set_cache_mock.call_count)

    @mock.patch(OPEN_FUNCTION_NAME)
    @mock.patch.object(glob, 'glob')
    def test__get_vmedia_device(self, glob_mock, open_mock):

        glob_mock.return_value = ['/sys/class/block/sda/device/model',
                                  '/sys/class/block/sdb/device/model',
                                  '/sys/class/block/sdc/device/model']
        fobj_mock = mock.MagicMock()
        mock_file_handle = mock.MagicMock()
        mock_file_handle.__enter__.return_value = fobj_mock
        open_mock.return_value = mock_file_handle

        fobj_mock.read.side_effect = ['scsi disk', Exception, 'Virtual Media']
        vmedia_device_returned = utils._get_vmedia_device()
        self.assertEqual('sdc', vmedia_device_returned)

    @mock.patch.object(shutil, 'rmtree', autospec=True)
    @mock.patch.object(tempfile, 'mkdtemp', autospec=True)
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(os.path, 'exists')
    @mock.patch.object(os, 'mkdir')
    @mock.patch.object(utils, 'execute')
    def test__get_vmedia_params_by_label(self, execute_mock, mkdir_mock,
                                         exists_mock, read_params_mock,
                                         mkdtemp_mock, rmtree_mock):
        mkdtemp_mock.return_value = "/tempdir"

        null_output = ["", ""]
        expected_params = {'a': 'b'}
        read_params_mock.return_value = expected_params
        exists_mock.return_value = True
        execute_mock.side_effect = [null_output, null_output]

        returned_params = utils._get_vmedia_params()

        execute_mock.assert_any_call('mount', "/dev/disk/by-label/ir-vfd-dev",
                                     "/tempdir")
        read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
        exists_mock.assert_called_once_with("/dev/disk/by-label/ir-vfd-dev")
        execute_mock.assert_any_call('umount', "/tempdir")
        self.assertEqual(expected_params, returned_params)
        mkdtemp_mock.assert_called_once_with()
        rmtree_mock.assert_called_once_with("/tempdir")

    @mock.patch.object(shutil, 'rmtree', autospec=True)
    @mock.patch.object(tempfile, 'mkdtemp', autospec=True)
    @mock.patch.object(utils, '_get_vmedia_device')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(os.path, 'exists')
    @mock.patch.object(os, 'mkdir')
    @mock.patch.object(utils, 'execute')
    def test__get_vmedia_params_by_device(self, execute_mock, mkdir_mock,
                                          exists_mock, read_params_mock,
                                          get_device_mock, mkdtemp_mock,
                                          rmtree_mock):
        mkdtemp_mock.return_value = "/tempdir"

        null_output = ["", ""]
        expected_params = {'a': 'b'}
        read_params_mock.return_value = expected_params
        exists_mock.return_value = False
        execute_mock.side_effect = [null_output, null_output]
        get_device_mock.return_value = "sda"

        returned_params = utils._get_vmedia_params()

        execute_mock.assert_any_call('mount', "/dev/sda",
                                     "/tempdir")
        read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
        execute_mock.assert_any_call('umount', "/tempdir")
        self.assertEqual(expected_params, returned_params)
        mkdtemp_mock.assert_called_once_with()
        rmtree_mock.assert_called_once_with("/tempdir")

    @mock.patch.object(utils, '_get_vmedia_device')
    @mock.patch.object(os.path, 'exists')
    def test__get_vmedia_params_cannot_find_dev(self, exists_mock,
                                                get_device_mock):
        get_device_mock.return_value = None
        exists_mock.return_value = False
        self.assertRaises(errors.VirtualMediaBootError,
                          utils._get_vmedia_params)

    @mock.patch.object(shutil, 'rmtree', autospec=True)
    @mock.patch.object(tempfile, 'mkdtemp', autospec=True)
    @mock.patch.object(utils, '_get_vmedia_device')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(os.path, 'exists')
    @mock.patch.object(os, 'mkdir')
    @mock.patch.object(utils, 'execute')
    def test__get_vmedia_params_mount_fails(self, execute_mock,
                                            mkdir_mock, exists_mock,
                                            read_params_mock,
                                            get_device_mock, mkdtemp_mock,
                                            rmtree_mock):
        mkdtemp_mock.return_value = "/tempdir"

        expected_params = {'a': 'b'}
        exists_mock.return_value = True
        read_params_mock.return_value = expected_params
        get_device_mock.return_value = "sda"

        execute_mock.side_effect = processutils.ProcessExecutionError()

        self.assertRaises(errors.VirtualMediaBootError,
                          utils._get_vmedia_params)

        execute_mock.assert_any_call('mount', "/dev/disk/by-label/ir-vfd-dev",
                                     "/tempdir")
        mkdtemp_mock.assert_called_once_with()
        rmtree_mock.assert_called_once_with("/tempdir")

    @mock.patch.object(shutil, 'rmtree', autospec=True)
    @mock.patch.object(tempfile, 'mkdtemp', autospec=True)
    @mock.patch.object(utils, '_get_vmedia_device')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(os.path, 'exists')
    @mock.patch.object(os, 'mkdir')
    @mock.patch.object(utils, 'execute')
    def test__get_vmedia_params_umount_fails(self, execute_mock, mkdir_mock,
                                             exists_mock, read_params_mock,
                                             get_device_mock, mkdtemp_mock,
                                             rmtree_mock):
        mkdtemp_mock.return_value = "/tempdir"

        null_output = ["", ""]
        expected_params = {'a': 'b'}
        exists_mock.return_value = True
        read_params_mock.return_value = expected_params
        get_device_mock.return_value = "sda"

        execute_mock.side_effect = [null_output,
                                    processutils.ProcessExecutionError()]

        returned_params = utils._get_vmedia_params()

        execute_mock.assert_any_call('mount', "/dev/disk/by-label/ir-vfd-dev",
                                     "/tempdir")
        read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
        execute_mock.assert_any_call('umount', "/tempdir")
        self.assertEqual(expected_params, returned_params)
        mkdtemp_mock.assert_called_once_with()
        rmtree_mock.assert_called_once_with("/tempdir")

    @mock.patch.object(shutil, 'rmtree', autospec=True)
    @mock.patch.object(tempfile, 'mkdtemp', autospec=True)
    @mock.patch.object(utils, '_get_vmedia_device')
    @mock.patch.object(utils, '_read_params_from_file')
    @mock.patch.object(os.path, 'exists')
    @mock.patch.object(os, 'mkdir')
    @mock.patch.object(utils, 'execute')
    def test__get_vmedia_params_rmtree_fails(self, execute_mock, mkdir_mock,
                                             exists_mock, read_params_mock,
                                             get_device_mock, mkdtemp_mock,
                                             rmtree_mock):
        mkdtemp_mock.return_value = "/tempdir"
        rmtree_mock.side_effect = Exception

        null_output = ["", ""]
        expected_params = {'a': 'b'}
        exists_mock.return_value = True
        read_params_mock.return_value = expected_params
        get_device_mock.return_value = "sda"

        execute_mock.return_value = null_output

        returned_params = utils._get_vmedia_params()

        execute_mock.assert_any_call('mount', "/dev/disk/by-label/ir-vfd-dev",
                                     "/tempdir")
        read_params_mock.assert_called_once_with("/tempdir/parameters.txt")
        execute_mock.assert_any_call('umount', "/tempdir")
        self.assertEqual(expected_params, returned_params)
        mkdtemp_mock.assert_called_once_with()
        rmtree_mock.assert_called_once_with("/tempdir")

    @mock.patch.object(utils, 'get_agent_params')
    def test_parse_root_device_hints(self, mock_get_params):
        mock_get_params.return_value = {
            'root_device': 'vendor=SpongeBob,model=Square%20Pants',
            'ipa-api-url': 'http://1.2.3.4:1234'
        }
        expected = {'vendor': 'spongebob', 'model': 'square pants'}
        result = utils.parse_root_device_hints()
        self.assertEqual(expected, result)

    @mock.patch.object(utils, 'get_agent_params')
    def test_parse_root_device_hints_no_hints(self, mock_get_params):
        mock_get_params.return_value = {
            'ipa-api-url': 'http://1.2.3.4:1234'
        }
        result = utils.parse_root_device_hints()
        self.assertEqual({}, result)

    @mock.patch.object(utils, 'get_agent_params')
    def test_parse_root_device_size(self, mock_get_params):
        mock_get_params.return_value = {
            'root_device': 'size=12345',
            'ipa-api-url': 'http://1.2.3.4:1234'
        }
        result = utils.parse_root_device_hints()
        self.assertEqual(12345, result['size'])

    @mock.patch.object(utils, 'get_agent_params')
    def test_parse_root_device_not_supported(self, mock_get_params):
        mock_get_params.return_value = {
            'root_device': 'foo=bar,size=12345',
            'ipa-api-url': 'http://1.2.3.4:1234'
        }
        self.assertRaises(errors.DeviceNotFound,
                          utils.parse_root_device_hints)

class TestFailures(testtools.TestCase):
    def test_get_error(self):
        f = utils.AccumulatedFailures()
        self.assertFalse(f)
        self.assertIsNone(f.get_error())

        f.add('foo')
        f.add('%s', 'bar')
        f.add(RuntimeError('baz'))
        self.assertTrue(f)

        exp = ('The following errors were encountered:\n* foo\n* bar\n* baz')
        self.assertEqual(exp, f.get_error())

    def test_raise(self):
        class FakeException(Exception):
            pass

        f = utils.AccumulatedFailures(exc_class=FakeException)
        self.assertIsNone(f.raise_if_needed())
        f.add('foo')
        self.assertRaisesRegexp(FakeException, 'foo', f.raise_if_needed)


#! /usr/bin/env python3

# Copyright 2021 Lassi Kortela
# SPDX-License-Identifier: ISC

import string

def is_whitespace_char(ch):
    return (ch == " ") or (ch == "\t") or (ch == "\n") or (ch == "\r")

def is_token_first_char(ch):
    if ch in string.digits:
        return True
    if ch in string.ascii_letters:
        return True
    return ch in "_$!?<=>+-*/"

def is_token_next_char(ch):
    return is_token_first_char(ch) or (ch in ".@~^%&")

class Symbol:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name  # TODO: vertical bars for complex symbols

    def __str__(self):
        return repr(self)

def parse_number_or_symbol(s):
    return Symbol(s)

class PoseSyntaxError(Exception):
    pass

class PoseReader:
    def __init__(self, stream):
        self.stream = stream
        self.lastchar = ""

    def peek_char(self):
        if self.lastchar == "":
            self.lastchar = self.stream.read(1)
        return self.lastchar

    def read_char(self):
        ch = self.peek_char()
        self.lastchar = ""
        return ch

    def skip_rest_of_line(self):
        while True:
            ch = self.read_char()
            if ch == "\n" or ch == "":
                break

    def skip_whitespace_and_comments(self):
        while True:
            ch = self.peek_char()
            if ch == "":
                break
            elif ch == ";":
                self.skip_rest_of_line()
            elif is_whitespace_char(ch):
                self.read_char()
            else:
                break

    def read_token_as_string(self):
        ch = self.read_char()
        if not is_token_first_char(ch):
            raise PoseSyntaxError("Not a token first char")
        s = ch
        while True:
            ch = self.peek_char()
            if ch == "" or not is_token_next_char(ch):
                break
            s += self.read_char()
        return s

    def read_sharpsign(self):
        ch = self.read_char()
        radix = {"b": 2, "o": 8, "x": 16}.get(ch)
        if radix is None:
            raise PoseSyntaxError("Unknown #")
        token = self.read_token_as_string()
        value = parse_integer(token, radix)
        if value is None:
            raise PoseSyntaxError("Cannot parse integer from token")
        return value

    def read_delimited_list(self, end_char):
        forms = []
        while True:
            self.skip_whitespace_and_comments()
            if self.peek_char() == end_char:
                self.read_char()
                break
            else:
                try:
                    forms.append(self.read())
                except EOFError:
                    raise PoseSyntaxError("Unterminated list")
        return forms

    def read_delimited_string(self, end_char):
        s = ""
        while True:
            ch = self.read_char()
            if ch == "":
                raise PoseSyntaxError("Unterminated string")
            elif ch == end_char:
                break
            elif ch == "\\":
                ch = self.read_char()
                if ch == "":
                    raise PoseSyntaxError("Unterminated string escape")
                else:
                    raw = {
                        '"': '"',
                        "|": "|",
                        "n": "\n",
                        "t": "\t",
                        "\\": "\\",
                    }.get(ch)
                    if raw is None:
                        raise PoseSyntaxError("Unknown string escape")
                    s += raw
            else:
                s += ch
        return s

    def read(self):
        self.skip_whitespace_and_comments()
        ch = self.peek_char()
        if ch == "":
            raise EOFError()
        elif is_token_first_char(ch):
            return parse_number_or_symbol(self.read_token_as_string())
        else:
            ch = self.read_char()
            if ch == "#":
                return self.read_sharpsign()
            elif ch == "|":
                return Symbol(self.read_delimited_string("|"))
            elif ch == '"':
                return self.read_delimited_string('"')
            elif ch == "(":
                return self.read_delimited_list(")")
            elif ch == ")":
                raise PoseSyntaxError("Stray closing parenthesis")
            else:
                raise PoseSyntaxError("Unknown character at top level")

    def read_all(self):
        forms = []
        try:
            while True:
                forms.append(self.read())
        except EOFError:
            return forms

if __name__ == "__main__":
    import sys

    for form in PoseReader(sys.stdin).read_all():
        print(repr(form))


import Gnuplot as Gnuplot
import Gnuplot, Gnuplot.funcutils
from numpy import *

def plotagematches(rows):
    xdm,ydm=[r.data[0] for r in rows if r.match==1],\
            [r.data[1] for r in rows if r.match==1]
    xdn,ydn=[r.data[0] for r in rows if r.match==0],\
            [r.data[1] for r in rows if r.match==0]
    listm=[]

    for fr in range(len(xdm)):
        dep=(xdm[fr],ydm[fr])
        listm.append(dep)

    listn=[]

    for fr in range(len(xdn)):
        dep=(xdn[fr],ydn[fr])
        listn.append(dep)

    g = Gnuplot.Gnuplot(debug=1)
    plot1 = Gnuplot.PlotItems.Data(listm, with_="points 1", title=None)
    plot2 = Gnuplot.PlotItems.Data(listn, with_="points 3", title=None)  # No title
    g.title('plotage matches')
    g.plot(plot1,plot2)
    wait=raw_input('Press <ENTER> to continue')


"""
https://leetcode.com/problems/design-an-ordered-stream/

Use a pre-defined array to store pairs. Then do as described.

Time complexity: O(N)
"""
class  OrderedStream:
    def __init__(self, n: int):
        self.vals = [''] * (n + 1)
        self.pt = 1

    def insert(self, id: int, value: str) -> List[str]:
        ans = []
        self.vals[id] = value
        if self.pt == id:
            while self.pt < len(self.vals) and self.vals[self.pt] != '':
                ans.append(self.vals[self.pt])
                self.pt += 1
        return ans


# -*- coding: utf-8 -*-
__author__ = 'Lin'

import socket, time

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1", 8888))  # sock.connect(("localhost", 8888))

    time.sleep(3)
    data = '1'
    sock.send(data.encode())
    print(sock.recv(1024).decode())

    sock.close()

if __name__ == "__main__":
    main()


# coding=utf-8
# Copyright 2019 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""lm Problem."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import tarfile
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.layers import modalities
from tensor2tensor.utils import registry
import json
#import tensorflow.compat.v1 as tf

import tensorflow as tf

flags = tf.flags
FLAGS = flags.FLAGS
datapath='./corpus'
#datapath=FLAGS.corpus_dir

class encoder_abstr(object):
  def __init__(self,dictpath='vocabx.txt'):
    reader = open(os.path.join(datapath, dictpath))
    self.str2id = {}
    self.id2str = {}
    for line in reader.readlines():
      line = line.strip()
      if line:
        if line in self.str2id: continue
        self.str2id[line] = len(self.str2id)

    ###
    self.id2str = dict(zip(list(self.str2id.values()), list(self.str2id.keys())))
  def encode(self,s): # list input
    ll=[]
    for w in s:
      w=w if w in self.str2id else 'UNK'
      ll.append(self.str2id[w])

    return ll

  def decode(self,ids):
    ll=[]
    for id in ids:
      id = id if id in self.id2str else 2
      ll.append(self.id2str[id])
    return ll

  @property
  def vocab_size(self):
    return len(self.str2id)

@registry.register_problem
class class_lm_douban(text_problems.Text2SelfProblem):
  @property
  def is_generate_per_split(self):
    return True

  def line_generator(self,fname): #
    fpath = os.path.join(datapath, fname)
    with tf.gfile.Open(fpath) as imdb_f:
        for line in imdb_f.readlines():
          line=line.strip()
          if line:
            yield line
  # def line_generator(self,fname):
  #   fpath=os.path.join(datapath,fname)
  #   with tf.gfile.Open(fpath) as imdb_f:
  #     for line in imdb_f.readlines():
  #       line=line.strip()
  #       if line:
  #         wll=json.loads(line)
  #         xll=[w['char'] for w in wll]
  #         yll=[w['y'] for w in wll]
  #         yield xll,yll

  def generate_samples(self, data_dir, tmp_dir, dataset_split):
    # """Generate examples."""
    # # Download and extract
    # compressed_filename = os.path.basename(self.URL)
    # download_path = generator_utils.maybe_download(tmp_dir, compressed_filename,
    #                                                self.URL)
    # imdb_dir = os.path.join(tmp_dir, "aclImdb")
    # if not tf.gfile.Exists(imdb_dir):
    #   with tarfile.open(download_path, "r:gz") as tar:
    #     tar.extractall(tmp_dir)
    #
    # # Generate examples
    train = dataset_split == problem.DatasetSplit.TRAIN
    dataset = "train.txt" if train else "test.txt"
    #for doc, label in self.doc_generator(imdb_dir, dataset, include_label=True):
    for line in self.line_generator(dataset):
      yield {
          #"input": xll, #wordll
          "target": line,
      }

  #############
  # customized
  # def generate_text_for_vocab(self, data_dir, tmp_dir):
  #   for i, sample in enumerate(
  #       self.generate_samples(data_dir, tmp_dir, problem.DatasetSplit.TRAIN)):
  #     yield sample["inputs"]
      # if self.max_samples_for_vocab and (i + 1) >= self.max_samples_for_vocab:
      #   break

  def get_or_create_vocab(self,data_dir=None, tmp_dir=None,force_get=True):
    #self.input_encoder=encoder_abstr('vocabx.txt')
    self.target_encoder=encoder_abstr('vocab.txt')
    return self.target_encoder

  def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
    generator = self.generate_samples(data_dir, tmp_dir, dataset_split)
    encoder = self.get_or_create_vocab(data_dir, tmp_dir)
    for sample in generator:

      target = encoder.encode(sample["target"])+[1] # EOS

      print (' '.join(sample["target"]))
      yield {"targets": target}

  def feature_encoders(self, data_dir):
    encoder = self.get_or_create_vocab(data_dir, None, force_get=True)
    encoders = {"targets": encoder}
    if self.has_inputs:
      encoders["inputs"] = encoder
    return encoders

  def hparams(self, defaults, unused_model_hparams):
    p = defaults
    p.stop_at_eos = int(True)

    p.modality = {"targets": modalities.ModalityType.SYMBOL}
    p.vocab_size = {"targets": self.target_encoder.vocab_size}

    if self.has_inputs:
      p.modality["inputs"] = modalities.ModalityType.SYMBOL
      p.vocab_size["inputs"] = self.input_encoder.vocab_size

    # p.modality = {"inputs": modalities.ModalityType.SYMBOL,
    #               "targets": modalities.ModalityType.SYMBOL}
    # p.vocab_size = {#"inputs": self._encoders["inputs"].vocab_size,
    #                 "inputs":self.input_encoder.vocab_size,
    #                 "targets": self.input_encoder.vocab_size}  #  应该是target_encoder


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

# coding: utf-8

"""
    Airflow API (Stable)

    Apache Airflow management API.  # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Contact: dev@airflow.apache.org
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from airflow_client.configuration import Configuration

class ListTaskInstanceForm(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'dag_ids': 'list[str]',
        'execution_date_gte': 'datetime',
        'execution_date_lte': 'datetime',
        'start_date_gte': 'datetime',
        'start_date_lte': 'datetime',
        'end_date_gte': 'datetime',
        'end_date_lte': 'datetime',
        'duration_gte': 'float',
        'duration_lte': 'float',
        'state': 'list[str]',
        'pool': 'list[str]',
        'queue': 'list[str]'
    }

    attribute_map = {
        'dag_ids': 'dag_ids',
        'execution_date_gte': 'execution_date_gte',
        'execution_date_lte': 'execution_date_lte',
        'start_date_gte': 'start_date_gte',
        'start_date_lte': 'start_date_lte',
        'end_date_gte': 'end_date_gte',
        'end_date_lte': 'end_date_lte',
        'duration_gte': 'duration_gte',
        'duration_lte': 'duration_lte',
        'state': 'State',
        'pool': 'Pool',
        'queue': 'Queue'
    }

    def __init__(self, dag_ids=None, execution_date_gte=None, execution_date_lte=None, start_date_gte=None, start_date_lte=None, end_date_gte=None, end_date_lte=None, duration_gte=None, duration_lte=None, state=None, pool=None, queue=None, local_vars_configuration=None):  # noqa: E501
        """ListTaskInstanceForm - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._dag_ids = None
        self._execution_date_gte = None
        self._execution_date_lte = None
        self._start_date_gte = None
        self._start_date_lte = None
        self._end_date_gte = None
        self._end_date_lte = None
        self._duration_gte = None
        self._duration_lte = None
        self._state = None
        self._pool = None
        self._queue = None
        self.discriminator = None

        if dag_ids is not None:
            self.dag_ids = dag_ids
        if execution_date_gte is not None:
            self.execution_date_gte = execution_date_gte
        if execution_date_lte is not None:
            self.execution_date_lte = execution_date_lte
        if start_date_gte is not None:
            self.start_date_gte = start_date_gte
        if start_date_lte is not None:
            self.start_date_lte = start_date_lte
        if end_date_gte is not None:
            self.end_date_gte = end_date_gte
        if end_date_lte is not None:
            self.end_date_lte = end_date_lte
        if duration_gte is not None:
            self.duration_gte = duration_gte
        if duration_lte is not None:
            self.duration_lte = duration_lte
        if state is not None:
            self.state = state
        if pool is not None:
            self.pool = pool
        if queue is not None:
            self.queue = queue

    @property
    def dag_ids(self):
        """Gets the dag_ids of this ListTaskInstanceForm.  # noqa: E501

        Return objects with specific DAG IDs. The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :return: The dag_ids of this ListTaskInstanceForm.  # noqa: E501
        :rtype: list[str]
        """
        return self._dag_ids

    @dag_ids.setter
    def dag_ids(self, dag_ids):
        """Sets the dag_ids of this ListTaskInstanceForm.

        Return objects with specific DAG IDs. The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :param dag_ids: The dag_ids of this ListTaskInstanceForm.  # noqa: E501
        :type: list[str]
        """

        self._dag_ids = dag_ids

    @property
    def execution_date_gte(self):
        """Gets the execution_date_gte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects greater or equal to the specified date. This can be combined with execution_date_lte parameter to receive only the selected period.   # noqa: E501

        :return: The execution_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._execution_date_gte

    @execution_date_gte.setter
    def execution_date_gte(self, execution_date_gte):
        """Sets the execution_date_gte of this ListTaskInstanceForm.

        Returns objects greater or equal to the specified date. This can be combined with execution_date_lte parameter to receive only the selected period.   # noqa: E501

        :param execution_date_gte: The execution_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._execution_date_gte = execution_date_gte

    @property
    def execution_date_lte(self):
        """Gets the execution_date_lte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects less than or equal to the specified date. This can be combined with execution_date_gte parameter to receive only the selected period.   # noqa: E501

        :return: The execution_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._execution_date_lte

    @execution_date_lte.setter
    def execution_date_lte(self, execution_date_lte):
        """Sets the execution_date_lte of this ListTaskInstanceForm.

        Returns objects less than or equal to the specified date. This can be combined with execution_date_gte parameter to receive only the selected period.   # noqa: E501

        :param execution_date_lte: The execution_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._execution_date_lte = execution_date_lte

    @property
    def start_date_gte(self):
        """Gets the start_date_gte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects greater or equal the specified date. This can be combined with startd_ate_lte parameter to receive only the selected period.   # noqa: E501

        :return: The start_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._start_date_gte

    @start_date_gte.setter
    def start_date_gte(self, start_date_gte):
        """Sets the start_date_gte of this ListTaskInstanceForm.

        Returns objects greater or equal the specified date. This can be combined with startd_ate_lte parameter to receive only the selected period.   # noqa: E501

        :param start_date_gte: The start_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._start_date_gte = start_date_gte

    @property
    def start_date_lte(self):
        """Gets the start_date_lte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects less or equal the specified date. This can be combined with start_date_gte parameter to receive only the selected period.   # noqa: E501

        :return: The start_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._start_date_lte

    @start_date_lte.setter
    def start_date_lte(self, start_date_lte):
        """Sets the start_date_lte of this ListTaskInstanceForm.

        Returns objects less or equal the specified date. This can be combined with start_date_gte parameter to receive only the selected period.   # noqa: E501

        :param start_date_lte: The start_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._start_date_lte = start_date_lte

    @property
    def end_date_gte(self):
        """Gets the end_date_gte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects greater or equal the specified date. This can be combined with start_date_lte parameter to receive only the selected period.   # noqa: E501

        :return: The end_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._end_date_gte

    @end_date_gte.setter
    def end_date_gte(self, end_date_gte):
        """Sets the end_date_gte of this ListTaskInstanceForm.

        Returns objects greater or equal the specified date. This can be combined with start_date_lte parameter to receive only the selected period.   # noqa: E501

        :param end_date_gte: The end_date_gte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._end_date_gte = end_date_gte

    @property
    def end_date_lte(self):
        """Gets the end_date_lte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects less than or equal to the specified date. This can be combined with start_date_gte parameter to receive only the selected period.   # noqa: E501

        :return: The end_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: datetime
        """
        return self._end_date_lte

    @end_date_lte.setter
    def end_date_lte(self, end_date_lte):
        """Sets the end_date_lte of this ListTaskInstanceForm.

        Returns objects less than or equal to the specified date. This can be combined with start_date_gte parameter to receive only the selected period.   # noqa: E501

        :param end_date_lte: The end_date_lte of this ListTaskInstanceForm.  # noqa: E501
        :type: datetime
        """

        self._end_date_lte = end_date_lte

    @property
    def duration_gte(self):
        """Gets the duration_gte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects greater than or equal to the specified values. This can be combined with duration_lte parameter to receive only the selected period.   # noqa: E501

        :return: The duration_gte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: float
        """
        return self._duration_gte

    @duration_gte.setter
    def duration_gte(self, duration_gte):
        """Sets the duration_gte of this ListTaskInstanceForm.

        Returns objects greater than or equal to the specified values. This can be combined with duration_lte parameter to receive only the selected period.   # noqa: E501

        :param duration_gte: The duration_gte of this ListTaskInstanceForm.  # noqa: E501
        :type: float
        """

        self._duration_gte = duration_gte

    @property
    def duration_lte(self):
        """Gets the duration_lte of this ListTaskInstanceForm.  # noqa: E501

        Returns objects less than or equal to the specified values. This can be combined with duration_gte parameter to receive only the selected range.   # noqa: E501

        :return: The duration_lte of this ListTaskInstanceForm.  # noqa: E501
        :rtype: float
        """
        return self._duration_lte

    @duration_lte.setter
    def duration_lte(self, duration_lte):
        """Sets the duration_lte of this ListTaskInstanceForm.

        Returns objects less than or equal to the specified values. This can be combined with duration_gte parameter to receive only the selected range.   # noqa: E501

        :param duration_lte: The duration_lte of this ListTaskInstanceForm.  # noqa: E501
        :type: float
        """

        self._duration_lte = duration_lte

    @property
    def state(self):
        """Gets the state of this ListTaskInstanceForm.  # noqa: E501

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :return: The state of this ListTaskInstanceForm.  # noqa: E501
        :rtype: list[str]
        """
        return self._state

    @state.setter
    def state(self, state):
        """Sets the state of this ListTaskInstanceForm.

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :param state: The state of this ListTaskInstanceForm.  # noqa: E501
        :type: list[str]
        """

        self._state = state

    @property
    def pool(self):
        """Gets the pool of this ListTaskInstanceForm.  # noqa: E501

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :return: The pool of this ListTaskInstanceForm.  # noqa: E501
        :rtype: list[str]
        """
        return self._pool

    @pool.setter
    def pool(self, pool):
        """Sets the pool of this ListTaskInstanceForm.

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :param pool: The pool of this ListTaskInstanceForm.  # noqa: E501
        :type: list[str]
        """

        self._pool = pool

    @property
    def queue(self):
        """Gets the queue of this ListTaskInstanceForm.  # noqa: E501

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :return: The queue of this ListTaskInstanceForm.  # noqa: E501
        :rtype: list[str]
        """
        return self._queue

    @queue.setter
    def queue(self, queue):
        """Sets the queue of this ListTaskInstanceForm.

        The value can be repeated to retrieve multiple matching values (OR condition).  # noqa: E501

        :param queue: The queue of this ListTaskInstanceForm.  # noqa: E501
        :type: list[str]
        """

        self._queue = queue

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, ListTaskInstanceForm):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, ListTaskInstanceForm):
            return True

        return self.to_dict() != other.to_dict()


#Partially completed with consultation & help of solutions posted on design.engsci.utoronto.ca

from ex_4 import *

class tree:
   def __init__(self,x):
      self.store = [x,[]]

   def AddSuccessor(self,x):
      self.store[1] = self.store[1] + [x]
      return True

   def Print_DepthFirst(self):
      self.Print_DF_Help('')
      return True

   def Print_DF_Help(self, pf):
      print (pf, self.store[0])
      for i in self.store[1]:
         i.Print_DF_Help(pf + " ")

   def Get_LevelOrder(self):
      x = Queue()
      for i in self.store:
          x.enqueue(i)
      #print("1 x.check()")
      #x.check()

      accum = []

      r = x.dequeue()
      #print("first r", r)

      accum += [r]
      #print("first accum", accum)

      while len(x.lst) != 0:
         r = x.dequeue()
         #print("r", r)
         #print("type(r)", r)
         if type(r) == list:
            for i in r:
               x.enqueue(i)
         else:
            #print(r.store[0])
            accum += [r.store[0]]
            #print(r.store[1])
            for i in r.store[1]:
               x.enqueue(i)
      # print("accum final:",accum)
      return accum

   def ConvertToBinaryTree(self, Sibs):
      Root = self.store[0]

      #Check for successors and their siblings
      if len(self.store[1]) == 0:
         L = []
      else:
         if len(self.store[1]) == 1:
            LSibs = []
         else:
            LSibs = self.store[1][1:]
         L = self.store[1][0].ConvertToBinaryTree(LSibs)

      #Check for siblings and their siblings
      if Sibs == []:
         R = []
      else:
         if len(Sibs) == 1:
            RSibs = []
         else:
            RSibs = Sibs[1:]
         R = Sibs[0].ConvertToBinaryTree(RSibs)

      #Make the Tree
      btree = binary_tree(Root)
      if L != []:
         btree.AddLeft(L)
      if R != []:
         btree.AddRight(R)
      return btree

class binary_tree:
   def __init__(self,x):
      self.store = [x]

   def AddLeft(self,x):
      self.store += [x]
      return True

   def AddRight(self,x):
      self.store += [x]
      return True

   def Get_LevelOrder(self):
      x = Queue()
      for i in self.store:
         x.enqueue(i)

      acc = []
      r = x.dequeue()
      acc += [r]

      while len(x.lst) != 0:
         r = x.dequeue()
         acc += [r.store[0]]
         if len(r.store) > 1:
            for i in r.store[1:]:
               x.enqueue(i)
      return acc

   def ConvertToTree(self):
      return self.store

'''
x=tree(1000)
y=tree(2000)
z=tree(3000)
x.AddSuccessor(y)
x.AddSuccessor(z)
c=tree(5)
z.AddSuccessor(c)
#x.Print_DepthFirst()
print(x.Get_LevelOrder())

x=binary_tree(1)
#print(x.store)
x.AddLeft(binary_tree(2))
#print(x.store[1])
y=binary_tree(3)
#print(y.store)
y.AddLeft(binary_tree(4))
#print(y.store)
y.AddRight(binary_tree(5))
#print(y.store)
x.AddRight(y)
x.Get_LevelOrder()
'''


from PIL import Image
import math
im = Image.open("sample_image.jpg")
circumRadius = 17
cr = circumRadius
oR = round(cr / math.cos(math.radians(30)))

f = open("sample_image.svg", "w+")
f.truncate()
f.write('<?xml version="1.0" standalone="yes"?>' + '\n')
f.write('<parent xmlns="http://example.org" xmlns:svg="http://www.w3.org/2000/svg">' + '\n')
f.write('<svg:svg width="' + str(im.size[0]) + '" height="' + str(im.size[1]) + '" version="1.1">' + '\n')

def paintHexShape(cX, cY, cr, colour):
    points = [
        str(round(cX - cr / 2)) + ',' + str(cY - cr),
        str(round(cX + cr / 2)) + ',' + str(cY - cr),
        str(cX + oR) + ',' + str(cY),
        str(round(cX + cr / 2)) + ',' + str(cY + cr),
        str(round(cX - cr / 2)) + ',' + str(cY + cr),
        str(cX - oR) + ',' + str(cY)
    ]
    s = ' '
    pointsString = s.join(points)
    f.write('<svg:polygon fill="'  + colour + '" points="' + pointsString + '" />' + '\n')

def getAvgHexColour(x, y, cr):
    widthsTopHalf = [j * cr for j in range(1, cr + 1)]
    for i in range(cr):
        widthsTopHalf[i] += i
    widthsBotHalf = widthsTopHalf[::-1]
    allWidths = widthsTopHalf + widthsBotHalf
    colours = list()
    for i in range(cr * 2):
        tX = x - allWidths[i] / 2
        tY = y - cr + i
        ti = im.crop((tX, tY, tX + allWidths[i], tY + 1)).resize((1, 1))
        colours.append(ti.getpixel((0,0)))
    widthWeight = [i / allWidths[cr] for i in allWidths]
    returnColour = [0, 0, 0]
    for j in range(3):
        returnColour[j] = round(sum([colours[i][j] * widthWeight[i] for i in range(len(colours))]) / (cr * 2))
    tuple(returnColour)
    return '#{:02x}{:02x}{:02x}'.format(*returnColour)

def hexShapes(im, cr):
    startPointsX = [i for i in range(0, im.size[0] +  cr, round(oR + (cr / 2)) - 1)]
    startPointsY = [j for j in range(0, im.size[1] +  cr, 2 * cr - 1)]

    oddRow = True
    for i in startPointsX:
        for j in startPointsY:
            colour = getAvgHexColour(i, j, cr)
            if(oddRow):
                paintHexShape(i, j, cr, colour)
            else:
                paintHexShape(i, j - cr, cr, colour)
            print("Hexagon at " + str(i) + ',' + str(j) + " created")
        oddRow = not oddRow

hexShapes(im, cr)

f.write('</svg:svg>' + '\n')
f.write('</parent>')


# encoding:utf-8
import random
# 开区间、闭区间

# 随机数
#[x, y]
#random.randint(x, y)

# 范围
# [x, y]
# "a"[x:y:步长]

# 数据类型，是可变，还是不可变
# 不可变的
# in float bool str 元组

# 可变的
# 列表 字典

# 公共方法
# 运算符 +
# 列表  注意顺序
my_list1 = [1, 2]
my_list2 = [3, 5]
ret1 = my_list1 + my_list2
print(ret1)
# 字符串
name = "熊明"
# 占位符
print("我叫%s" % name)
ret = "我叫" + name
ret1 = "我叫s%" + name
print(ret)
print(ret1)

# 类型不统一，使用str()转类型
name = "小红"
age = 18
ret2 = "我叫" + name + ",年龄" + str(age)
print(ret2)

# 元组
ret3 = (1, 4) + (3, 6)
print(ret3)

# 运算符 *
# 字符串
my_str = "=="*20
print(my_str)

# 列表
my_list = ["hello", "world!"]*10
print(my_list)

# 元组
my_tuple = (11,)*5
print(my_tuple)

# in
my_name = "world"
if "l" in my_name:
    print("存在！！！")

# 元组
my_tuple = (1, 2, 3)
if 2 in my_tuple:
    print("真的存在吗？")

# 字典
my_dict = {"name": "小红", "age": 22, "no": "009"}
# 使用in 在字典中其实判断是key存不存在
if "age" in my_dict:
    print("真真的存在·！")
if "小红" in my_dict:
    print("应该是不存在的。")

# del 用法总结
# 可以配合列表使用
my_list = [1, 2, 4, 5]
del my_list[1]
print(my_list)

# 可以配合字典使用
my_dict = {"name": "小花", "age": 22, "no": "009"}
del my_dict["no"]
print(my_dict)

# 可以提前销毁一个对象
num = 10
# 在程序么有结束的时候，程序员提前杀死了这个对象，提前释放内存
# NameError: name 'num' is not defined
# del num
# print(num)
# # 组织程序结束
# input()
# 监听当程序结束后 python会执行一个方法 del num 告知系统回收内存

其他版本/第三天/04-公共方法和总结.py

04-公共方法和总结.py


"""
Printing Longest Common Subsequence
Given two sequences, print the longest subsequence present in both of them.

Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
"""
def print_lcs(str1,str2):
    if not str1 or not str2 :
        return
    else :
        m = len(str1)
        n = len(str2)
        lps = [[0 for x in range(m+1)] for x in range(n+1)]

        for i in range(m+1):
            for j in range(n+1):
                if i==0 or j ==0  :
                    lps[i][j] = 0
                elif str1[i-1] == str2[j-1] :
                    lps[i][j] = lps[i-1][j-1] + 1
                else :
                    lps[i][j] = max(lps[i-1][j],lps[i][j-1])
        index = lps[m][n]
        i = m
        j = n
        out = ['0']*index
        while i> 0 and j > 0 :
            if str1[i-1]==str2[j-1] :
                index -= 1
                out[index] = str2[j-1]
                i -= 1
                j -=1
            elif lps[i-1][j] > lps[i][j-1] :
                i -= 1
            else :
                j -=1
        return ''.join(out)

if __name__=='__main__':
    str1 = 'ABCDGH'
    str2 = 'AEDFHR'
    print(print_lcs(list(str1),list(str2)))


"""
Controls right now (proof of concept):
J/K to control money
Up/Down Arrows to control Hearts
Space to control Current Weapon
M to hide/show map
Click on the Gear button in the top right corner to make the popup menu appear
    --> only resume and quit are available currently
"""

from pygame import *
#from link import person
import os
from imageload import imageload
from shopp import shopclass
os.environ['SDL_VIDEO_WINDOW_POS'] = "10,30"
screen = display.set_mode((800,740))
screenx,screeny = screen.get_size()

class player(object):
    def __init__(self,speed=3):
        self.speed = speed
        self.playermovement = "None"
        self.movex = 0
        self.movey = 0
        self.playersprite = image.load("images/People/player.png").convert()
        self.playersprite.set_colorkey((255,255,255))
        self.playersprite = transform.scale(self.playersprite,(20,20))
        self.rect = self.playersprite.get_rect()
    def keys(self):
        keys = key.get_pressed()
        if keys[K_w]:
            self.rect.y-=self.speed
            self.playermovement = "Up"
        if keys[K_a]:
            self.rect.x-=self.speed
            self.playermovement = "Left"
        if keys[K_s]:
            self.rect.y+=self.speed
            self.playermovement = "Down"
        if keys[K_d]:
            self.rect.x+=self.speed
            self.playermovement = "Right"
        if not keys[K_w] and not keys[K_a] and not keys[K_s] and not keys[K_d]:
            self.playermovement = None

player = player()
player.rect.x,player.rect.y = 100,75

ui = screen.subsurface(Rect(0,0,screenx,screeny))

heart = image.load('images/UI/heart.png').convert()
heart.set_colorkey((0,0,0))

##rupee = image.load('images/UI/rupee.png').convert()
##rupee.set_colorkey((255,255,255))

gear = image.load('images/UI/settings.png').convert()
gear.set_colorkey((255,255,255))

gearhover = image.load('images/UI/settingshover.png').convert()
gearhover.set_colorkey((255,255,255))

Exit = image.load('images/UI/Exit.png').convert()
Exit.set_colorkey((255,255,255))

ExitHover = image.load('images/UI/ExitHover.png').convert()
ExitHover.set_colorkey((255,255,255))

Resume = image.load('images/UI/Resume.png').convert()
ResumeHover = image.load('images/UI/ResumeHover.png').convert()

sword = image.load('images/UI/sword.png').convert()
sword.set_colorkey((255,255,255))

boomerang = image.load('images/UI/boomerang.png').convert()
boomerang.set_colorkey((0,0,0))

bow = image.load('images/UI/bow.png').convert()
bow.set_colorkey((255,255,255))

mapimg = image.load('images/map1.png').convert()

minmap = transform.scale(mapimg,(200,205))
heart = transform.scale(heart,(20,20))
##rupee = transform.scale(rupee,(35,35))
gear = transform.scale(gear,(35,35))
gearhover = transform.scale(gearhover,(35,35))
Exit = transform.scale(Exit,(130,55))
ExitHover = transform.scale(ExitHover,(130,55))
##gearmask = mask.from_surface(gear)
Resume = transform.scale(Resume,(130,55))
ResumeHover = transform.scale(ResumeHover,(130,55))
sword = transform.scale(sword,(75,75))
boomerang = transform.scale(boomerang,(75,75))
bow = transform.scale(bow,(75,75))

ExitRect = Exit.get_rect()
ExitRect.center = screenx//2,395##screeny//2
ResumeRect = Resume.get_rect()
ResumeRect.center = screenx//2,325
SettingsMenuRect = Rect(0,0,150,298-10-ExitRect.bottomright[1]+ExitRect[1]-55-45+10)
SettingsMenuRect.midtop = screenx//2,298-10

done = False

def drawminmap():
    minmaprect = minmap.get_rect()
    draw.rect(ui,(255,215,0),(screenx-205,screeny-205,minmaprect[2]+5,minmaprect[3]))
    ui.blit(minmap,(screenx-200,screeny-200))
def updatehearts(heartstatus=3,distapart=20):
    x,y = 3,0
    if heartstatus>0:
        for pos in range(heartstatus):
            ui.blit(heart,(x+distapart*pos,y))
def settings():
    ui.blit(gear,(755,10))
    if gear_rect.collidepoint(mx,my):
        ui.blit(gearhover,(755,10))
def settingsmenu(menuwallpadding=5):
    """
    add code to pause game here
    """
    draw.rect(ui,(255,215,0),SettingsMenuRect)#(ResumeRect[0]-menuwallpadding,ResumeRect[1]-menuwallpadding,ExitRect.bottomright[0]-ResumeRect.topleft[0]+15+menuwallpadding,ExitRect.bottomright[1]-ResumeRect.topleft[1]+15+menuwallpadding))
    ui.blit(Resume,ResumeRect)
    if ResumeRect.collidepoint(mx,my):
        ui.blit(ResumeHover,ResumeRect)
    ui.blit(Exit,ExitRect)
    if ExitRect.collidepoint(mx,my):
        ui.blit(ExitHover,ExitRect)

settingsbool = False
hearts,maxhearts = 3,10
gear_rect = Rect(755,10,35,35)
minmaptoggle = 1

"""
screen size in this demo has been adjusted to 800x740
    --> before, it was 800x800
    --> changing resolution should be fine since most things are positioned
        relative to the screen size

Everything below this is the updated ui/shop code, NOT COUNTING:
from shop import shop
"""

Fairies,Keys = 0,0

def showammo():
    draw.rect(ui,(255,215,0),(0,screeny-100,55,80))
    draw.rect(ui,(100,100,100),(0,screeny-95,50,70))
    ui.blit(bomb,(5,screeny-90))
    ui.blit(arrow,(5,screeny-50))
    if bombtot:
        bombstock = shop.hylian.render('%i'% bombtot,False,(173,214,198))
        ui.blit(bombstock,(40,screeny-90))
    else:
        bombstock = shop.hylian.render('0',False,(173,214,198))
        ui.blit(bombstock,(40,screeny-90))
    if arrowtot:
        arrowstock = shop.hylian.render('%i'% arrowtot,False,(173,214,198))
        ui.blit(arrowstock,(40,screeny-50))
    else:
        arrowstock = shop.hylian.render('0',False,(173,214,198))
        ui.blit(arrowstock,(40,screeny-50))
bomb = imageload("images/UI/bomb.png",0.1,False,(255,255,255))
arrow = imageload("images/UI/Arrow.png",0.175,False,(255,255,255))
bombtot,arrowtot = 0,0
shop = shopclass(screen)

rupee = imageload("images/UI/rupee.png",0.175,False,(255,255,255))
rupeecolon = shop.hylian.render(":",False,(205,255,0))

clock = time.Clock()
while not done:
    mx,my = mouse.get_pos()
    mb = mouse.get_pressed()
    for e in event.get():
        if e.type==QUIT or e.type==MOUSEBUTTONUP and ExitRect.collidepoint(mx,my) and settingsbool:
            done = True
        if e.type==MOUSEBUTTONUP:
            if ResumeRect.collidepoint(mx,my):
                settingsbool = False
            if gear_rect.collidepoint(mx,my):
                settingsbool = True
            if shop.ExitRect.collidepoint(mx,my):
                shop.ui.blit(shop.ExitHover,shop.ExitRect)
                shop.shopbool = False
            if shop.tabbool==1:
                for q in range(len(shop.Qs)):
                    if shop.Qs[q].collidepoint(mx,my):
                        if q%2!=0 and shop.cost+shop.QVals[q]<=shop.rupeenum and shop.QStock[q] and shop.held[q//2]+1<=shop.QStock[q]:
                            shop.cost+=shop.QVals[q]
                            shop.QStock[q]-=1
                            shop.OldQStock = q
                            shop.held[q//2]+=1
                            shop.amt[q//2] = shop.hylian.render('%i'% shop.held[q//2],False,(173,214,198))
                        elif q%2==0 and shop.cost-shop.QVals[q]<=shop.rupeenum and shop.cost-shop.QVals[q]>=0 and shop.held[q//2]-1>=0:
                            shop.cost-=shop.QVals[q]
                            shop.QStock[shop.OldQStock]+=1
                            shop.held[q//2]-=1
                            shop.amt[q//2] = shop.hylian.render('%i'% shop.held[q//2],False,(173,214,198))
                        print("Current Cost: $",shop.cost)
                        print("Stocks:",shop.held)
            if shop.tabbool==-1:
                for q in range(len(shop.itemQs)):
                    if shop.itemQs[q].collidepoint(mx,my):
                        if q%2!=0 and shop.cost+shop.itemQVals[q]<=shop.rupeenum and shop.itemQStock[q] and shop.itemheld[q//2]+1<=shop.itemQStock[q]:
                            shop.cost+=shop.itemQVals[q]
                            shop.itemQStock[q]-=1
                            shop.itemOldQStock = q
                            shop.itemheld[q//2]+=1
                            shop.amt[4+q//2] = shop.hylian.render('%i'% shop.itemheld[q//2],False,(173,214,198))
                        elif q%2==0 and shop.cost-shop.itemQVals[q]<=shop.rupeenum and shop.cost-shop.itemQVals[q]>=0 and shop.itemheld[q//2]-1>=0:
                            shop.cost-=shop.itemQVals[q]
                            shop.itemQStock[shop.itemOldQStock]+=1
                            shop.itemheld[q//2]-=1
                            shop.amt[4+q//2] = shop.hylian.render('%i'% shop.itemheld[q//2],False,(173,214,198))
                        print("Current Cost: $",shop.cost)
                        print("Stocks:",shop.held)
            if shop.buyrect.collidepoint(mx,my) and shop.cost<=shop.rupeenum and shop.cost!=0:
                shop.rupeenum-=shop.cost
                if hearts<maxhearts and shop.amt[4] and shop.itemheld[0]:
                    hearts+=shop.itemheld[0]
                if shop.amt[5] and shop.amt[5] and shop.itemheld[1]:
                    Fairies+=shop.itemheld[1]
                if shop.amt[6] and shop.amt[6] and shop.itemheld[2]:
                    shop.hasmap = True
                if shop.amt[7] and shop.amt[7] and shop.itemheld[3]:
                    Keys+=shop.itemheld[3]
                bombtot+=shop.held[0]
                arrowtot+=shop.held[2]
                shop.amt[0],shop.amt[1],shop.amt[2],shop.amt[4],shop.amt[5],shop.amt[6],shop.amt[7] = shop.amt0,shop.amt1,shop.amt2,shop.amt4,shop.amt5,shop.amt6,shop.amt7
                print("Spent $",shop.cost)
                shop.held,shop.itemheld,shop.cost = [0,0,0,0],[0,0,0,0],0
            if shop.toggleTabRect.collidepoint(mx,my):
                shop.tabbool*=-1
        if e.type==KEYUP:
            if e.key==K_UP and hearts<maxhearts:
                hearts+=1
            if e.key==K_DOWN and hearts>0:
                hearts-=1
            if e.key==K_j:
                shop.rupeenum+=1
            if e.key==K_k and shop.rupeenum>0:
                shop.rupeenum-=1
            if shop.ShopKeeperRect.colliderect(player.rect) and e.key==K_SPACE and not shop.shopbool:
                shop.shopbool = True
            if e.key==K_m and shop.hasmap:
                minmaptoggle*=-1
    if not shop.shopbool:
        player.keys()
    screen.fill((175,175,175))
    screen.blit(player.playersprite,(player.rect.x,player.rect.y))
    shop.settingsmenu(mx,my)
    if shop.shopbool:
        if shop.tabbool==1:
            ui.blit(shop.amt[0],shop.amt0rect)
            ui.blit(shop.amt[1],shop.amt1rect)
            ui.blit(shop.amt[2],shop.amt2rect)
        else:
            ui.blit(shop.amt[4],shop.amt4rect)
            ui.blit(shop.amt[5],shop.amt5rect)
            ui.blit(shop.amt[6],shop.amt6rect)
            ui.blit(shop.amt[7],shop.amt7rect)
    shop.rupeehandling()
    ui.blit(rupee,(0,25))
    ui.blit(rupeecolon,(35,32.5))
    settings()
    if settingsbool:
        settingsmenu()
    updatehearts(hearts)
    if minmaptoggle==1 and shop.hasmap:
        drawminmap()
    showammo()
    clock.tick(60)
    display.flip()
quit()


import lasagne
from lasagne.layers import DenseLayer, NonlinearityLayer

from ..utils.format import check_list
from ..utils.layers import clip_grads, add, mul
from ..memory.gate import GateLayer

# Vanilla RNN cell

def RNNCell(prev_state,
            input_or_inputs=tuple(),
            nonlinearity=lasagne.nonlinearities.sigmoid,
            num_units=None,
            name="YetAnotherRNNLayer",
            grad_clipping=5.):
    """

    Implements a one-step recurrent neural network (RNN) with arbitrary number of units.

    parameters:
        prev_state: input that denotes previous state (shape must be (None, n_units) )
        input_or_inputs: a single layer or a list/tuple of layers that go as inputs
        nonlinearity: which nonlinearity to use
        num_units: how many recurrent cells to use. None means "as in prev_state"
        grad_clipping: maximum gradient absolute value. 0 or None means "no clipping"

    for developers:
        Works by stacking DenseLayers with ElemwiseSumLayer.
        is a function mock, not actual class.

    """

    assert len(prev_state.output_shape) == 2
    # if needed, infer num_units
    if num_units is None:
        num_units = prev_state.output_shape[1]
    # else check it
    assert num_units == prev_state.output_shape[1]

    inputs = check_list(input_or_inputs)

    if grad_clipping:
        prev_state = clip_grads(prev_state, grad_clipping)
        inputs = [clip_grads(lyr, grad_clipping) for lyr in inputs]

    # from prev state to current state (with bias)
    hid_to_hid = DenseLayer(prev_state,
                            num_units=num_units,
                            nonlinearity=None,
                            name=name + ".hid_to_hid")

    # from inputs to current state (without bias)
    inputs_to_hid = [DenseLayer(input_layer,
                                num_units=num_units,
                                nonlinearity=None,
                                b=None,  # Cruicial! This disables additional bias layers
                                name=name + ".input%i_to_hid" % (i))
                     for i, input_layer in enumerate(inputs)]

    # stack them
    elwise_sum = add(*([hid_to_hid] + inputs_to_hid), name=name + ".sum")

    # finally, apply nonlinearity

    new_hid = NonlinearityLayer(elwise_sum,
                                nonlinearity,
                                name=name + ".new_state")

    return new_hid

def GRUCell(prev_state,
            input_or_inputs=tuple(),
            num_units=None,
            forgetgate_nonlinearity=lasagne.nonlinearities.sigmoid,
            updategate_nonlinearity=lasagne.nonlinearities.sigmoid,
            hidden_update_nonlinearity=lasagne.nonlinearities.tanh,
            name="YetAnotherGRULayer",
            grad_clipping=5.
            ):
    """

    Implements a one-step gated recurrent unit (GRU) with arbitrary number of units.

    parameters:
        prev_state: input that denotes previous state (shape must be (None, n_units) )
        input_or_inputs: a single layer or a list/tuple of layers that go as inputs
        *_nonlinearity: which nonlinearity to use for a particular gate
        num_units: how many recurrent cells to use. None means "as in prev_state"
        grad_clipping: maximum gradient absolute value. 0 or None means "no clipping"

    for developers:
        Works by stacking other lasagne layers;
        is a function mock, not actual class.

    """

    assert len(prev_state.output_shape) == 2
    # if required, infer num_units
    if num_units is None:
        num_units = prev_state.output_shape[1]
    # else check it
    assert num_units == prev_state.output_shape[1]

    inputs = check_list(input_or_inputs)

    # hidden to gates
    hid_to_gates = GateLayer(prev_state, [num_units] * 3,
                             gate_nonlinearities=None,
                             bias_init=None,
                             name=name + ".hidden_to_gates_stacked")

    hid_forget, hid_update, hidden_update_hid = hid_to_gates.values()

    # clip grads #1
    if grad_clipping:
        inputs = [clip_grads(lyr, grad_clipping) for lyr in inputs]
        hid_forget, hid_update, hidden_update_hid = [clip_grads(lyr, grad_clipping) for lyr in
                                                     [hid_forget, hid_update, hidden_update_hid]]

    # input to gates
    inp_to_gates = GateLayer(inputs, [num_units] * 3,
                             gate_nonlinearities=None,
                             name=name + ".input_to_gates_stacked")
    inp_forget, inp_update, hidden_update_in = inp_to_gates.values()

    # compute forget and update gates
    forgetgate = NonlinearityLayer(
        add(inp_forget, hid_forget),
        forgetgate_nonlinearity,
        name="forgetgate"
    )
    updategate = NonlinearityLayer(
        add(inp_update, hid_update),
        updategate_nonlinearity,
        name="updategate"
    )

    inv_updategate = NonlinearityLayer(updategate,
                               lambda x: 1 - x,
                               name="1 - updategate")

    # compute hidden update
    hidden_update = add(
        hidden_update_in,
        mul(forgetgate, hidden_update_hid),
        name="hid_update"
    )

    # clip grads #2
    if grad_clipping:
        hidden_update = clip_grads(hidden_update,
                                   grad_clipping)

    hidden_update = NonlinearityLayer(hidden_update,
                                      hidden_update_nonlinearity)

    # compute new hidden values
    new_hid = add(
        mul(inv_updategate, prev_state),
        mul(updategate, hidden_update),
        name=name
    )

    return new_hid


import geopandas as gpd
from loguru import logger

from dublin_building_stock.spatial_operations import (
    get_geometries_within,
)

def create_dublin_small_area_boundaries(data_dir, dublin_boundary):

    filenames = [
        "Census2011_Small_Areas_generalised20m",
        "Small_Areas_Ungeneralised_-_OSi_National_Statistical_Boundaries_-_2015-shp",
    ]
    filepaths = [data_dir / filename for filename in filenames]
    for filepath in filepaths:
        use_columns = ["SMALL_AREA", "EDNAME", "geometry"]
        ireland_small_area_boundaries = gpd.read_file(filepath)[use_columns]
        dublin_small_area_boundaries = get_geometries_within(
            ireland_small_area_boundaries.to_crs(epsg=2157),
            dublin_boundary.to_crs(epsg=2157),
        )
        output_filepath = filepath.parent / ("Dublin_" + filepath.stem)
        dublin_small_area_boundaries.to_file(output_filepath)


from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from six.moves import xrange

import numpy as np

from keras import backend as K
from . import backend_addons as K2

from ..hyp_defs import float_keras

log2pi=np.log(2*np.pi).astype(float_keras())
one=np.exp(0).astype(float_keras())

def bernoulli(y_true, y_pred):
    return K.sum(K.binary_crossentropy(y_pred, y_true), axis=-1)

def diag_normal(y_true, y_pred):
    y_mean, y_logvar = y_pred
    y_var = K.exp(y_logvar)
    dist2=K.square(y_true-y_mean)/y_var
    return 0.5*K.sum(log2pi+y_logvar+dist2, axis=-1)

def normal_1chol(y_true, y_pred):
    y_mean, y_logvar, y_chol = y_pred

    isigma = K.exp(-y_logvar/2)
    iy_chol = K2.matrix_inverse(y_chol)

    distn  = K.dot(y_true-y_mean, iy_chol) * isigma
    dist2 = K.square(distn)
    return 0.5*K.sum(log2pi+y_logvar+dist2, axis=-1)

def normal(y_true, y_pred):
    y_mean, y_logvar, y_chol = y_pred

    isigma = K.exp(-y_logvar/2)
    f = lambda x: K2.matrix_inverse(x)
    iy_chol = K.map_fn(f, y_chol)

    dist  = y_true-y_mean
    distn = K.batch_dot(dist, iy_chol, axes=(1, 1)) * isigma
    dist2 = K.square(distn)
    return 0.5*K.sum(log2pi+y_logvar+dist2, axis=-1)

def normal_3d(y_true, y_pred):
    y_mean, y_logvar, y_chol = y_pred

    x_dim = K.cast(K.shape(y_mean)[-1], 'int32')
    seq_length = K.cast(K.shape(y_mean)[-2], 'int32')

    y_chol = K.reshape(y_chol, (-1, x_dim, x_dim))

    isigma = K.exp(-y_logvar/2)
    f = lambda x: K2.matrix_inverse(x)
    iy_chol = K.map_fn(f, y_chol)

    dist = y_true-y_mean
    dist = K.reshape(dist, (-1, x_dim))
    distn = K.batch_dot(dist, iy_chol, axes=(1, 1))
    distn = K.reshape(distn, (-1, seq_length, x_dim)) * isigma
    dist2 = K.square(distn)
    return 0.5*K.sum(log2pi+y_logvar+dist2, axis=-1)

def normal_1chol_3d(y_true, y_pred):
    y_mean, y_logvar, y_chol = y_pred

    x_dim = K.cast(K.shape(y_mean)[-1], 'int32')
    seq_length = K.cast(K.shape(y_mean)[-2], 'int32')

    isigma = K.exp(-y_logvar/2)
    iy_chol = K2.matrix_inverse(y_chol)

    dist = y_true-y_mean
    #dist = K.reshape(dist, (-1, x_dim))
    distn  = K.dot(dist, iy_chol) * isigma
    #distn = K.reshape(distn, (-1, seq_length, x_dim))
    dist2 = K.square(distn)
    return 0.5*K.sum(log2pi+y_logvar+dist2, axis=-1)

def kl_normal_vs_std_normal(qy, beta=one):
    y_mean, y_logvar = qy[:2]
    T = one/beta
    return -0.5*K.sum((T-one) * log2pi + T + T * y_logvar
                      - K.square(y_mean) - K.exp(y_logvar), axis=-1)

def kl_normal_vs_diag_normal(qy1, qy2, beta=one):
    y1_mean, y1_logvar = qy1[:2]
    y2_mean, y2_logvar = qy2[:2]
    T = one/beta
    v1 = K.exp(y1_logvar)
    v2 = K.exp(y2_logvar)
    return -0.5*K.sum((T-one) * log2pi + T + T * y1_logvar - y2_logvar
                      - (K.square(y1_mean-y2_mean)+v1)/v2, axis=-1)

def kl_normal_commonvar2(qy1, qy2, beta=one):
    y1_mean, y1_logvar, y1_chol = qy1
    y2_mean, y2_logvar, y2_chol = qy2

    dim=K.shape(y1_mean)[-1]

    iy2_chol = K2.matrix_inverse(y2_chol)
    iy2_chol*= iy_chol * K.exp(-y2_logvar/2)

    dist  = y1_mean-y2_mean
    distn = K.batch_dot(dist, iy2_chol, axes=(2, 0))
    dist2 = K.square(distn)

    iy2_var = K.reshape(np.dot(iy2_chol, iy2_chol.T), shape=(-1))
    y1_chol *= K.exp(y1_logvar/2)
    f = lambda x: K.reshape(K.dot(x.T, x), shape=(-1, dim**2))
    y1_var = K.map_fh(f, y1_chol)

    tr = K.dot(y1_var, iy2_var)

    T = one/beta
    v1 = K.exp(y1_logvar)
    v2 = K.exp(y2_logvar)
    return -0.5*K.sum((T-1)*log2pi + T + T*y1_logvar - y2_logvar
                      - dist2 - tr, axis=-1)