import unittest
from typing import List, Tuple, Union  # noqa: F401

from ddt import data, ddt, unpack

from purplequery.binary_expression import BinaryExpression
from purplequery.bq_abstract_syntax_tree import (EMPTY_NODE, EvaluatableNode, Field,  # noqa: F401
                                                 _EmptyNode)
from purplequery.bq_types import BQScalarType
from purplequery.dataframe_node import DataSource, QueryExpression, Select, TableReference
from purplequery.evaluatable_node import (Case, Cast, Count, Exists, Extract, If, InCheck, Not,
                                          NullCheck, Selector, StarSelector, UnaryNegation, Value,
                                          _AggregatingFunctionCall)
from purplequery.grammar import (core_expression, data_source, post_expression, query_expression,
                                 select)

@ddt
class GrammarTest(unittest.TestCase):

    def test_query_expression(self):
        # type: () -> None
        ast, leftover = query_expression(
            ['SELECT', '*', 'FROM', '`my_project.my_dataset.my_table`'])
        self.assertEqual(leftover, [])

        assert isinstance(ast, QueryExpression)
        self.assertEqual(ast.base_query.__class__, Select)

    def test_select(self):
        # type: () -> None
        ast, leftover = select(['SELECT', '*', 'FROM', '`my_project.my_dataset.my_table`'])

        self.assertEqual(leftover, [])
        assert isinstance(ast, Select)
        self.assertEqual(ast.modifier, EMPTY_NODE)
        assert isinstance(ast.fields[0], StarSelector)
        self.assertEqual(ast.fields[0].expression, EMPTY_NODE)
        self.assertEqual(ast.fields[0].exception, EMPTY_NODE)
        self.assertEqual(ast.fields[0].replacement, EMPTY_NODE)
        assert isinstance(ast.from_, DataSource)
        assert isinstance(ast.from_.first_from[0], TableReference)
        self.assertEqual(ast.from_.first_from[0].path, ('my_project', 'my_dataset', 'my_table'))
        self.assertEqual(ast.from_.first_from[1], EMPTY_NODE)
        self.assertEqual(ast.from_.joins, [])
        self.assertEqual(ast.where, EMPTY_NODE)
        self.assertEqual(ast.group_by, EMPTY_NODE)
        self.assertEqual(ast.having, EMPTY_NODE)

    def test_select_as(self):
        # type: () -> None
        ast, leftover = select(['SELECT', '*', 'FROM', '`my_project.my_dataset.my_table`',
                                'AS', 'TableAlias'])

        self.assertEqual(leftover, [])
        assert isinstance(ast, Select)
        assert isinstance(ast.from_, DataSource)
        self.assertEqual(ast.from_.first_from[1], 'TableAlias')

    @data(
        dict(
            tokens=['`my_project.my_dataset.my_table`'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias=EMPTY_NODE,
            num_joins=0,
            join_type=EMPTY_NODE,
            join_table_path=EMPTY_NODE,
            join_table_alias=EMPTY_NODE,
            join_conditions=EMPTY_NODE
        ),
        dict(
            tokens=['`my_project.my_dataset.my_table`', 'JOIN',
                    '`my_project.my_dataset.my_table2`', 'ON',
                    'my_table', '.', 'a', '=', 'my_table2', '.', 'b'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias=EMPTY_NODE,
            num_joins=1,
            join_type=EMPTY_NODE,
            join_table_path=('my_project', 'my_dataset', 'my_table2'),
            join_table_alias=EMPTY_NODE,
            join_conditions=BinaryExpression(Field(('my_table', 'a')),
                                             '=',
                                             Field(('my_table2', 'b'))),
        ),
        dict(
            tokens=['`my_project.my_dataset.my_table`', 'JOIN',
                    '`my_project.my_dataset.my_table2`', 'USING', '(', 'a', ',', 'b', ')'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias=EMPTY_NODE,
            num_joins=1,
            join_type=EMPTY_NODE,
            join_table_path=('my_project', 'my_dataset', 'my_table2'),
            join_table_alias=EMPTY_NODE,
            join_conditions=('a', 'b')
        ),
        dict(
            tokens=['`my_project.my_dataset.my_table`', 'JOIN',
                    '`my_project.my_dataset.my_table2`', 'USING', '(', 'a', ')'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias=EMPTY_NODE,
            num_joins=1,
            join_type=EMPTY_NODE,
            join_table_path=('my_project', 'my_dataset', 'my_table2'),
            join_table_alias=EMPTY_NODE,
            join_conditions=('a',)
        ),
        dict(
            tokens=['`my_project.my_dataset.my_table`', 'AS', 'table1', 'JOIN',
                    '`my_project.my_dataset.my_table2`', 'AS', 'table2', 'USING', '(', 'a', ')'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias='table1',
            num_joins=1,
            join_type=EMPTY_NODE,
            join_table_path=('my_project', 'my_dataset', 'my_table2'),
            join_table_alias='table2',
            join_conditions=('a',)
        ),
        dict(
            tokens=['`my_project.my_dataset.my_table`', 'FULL', 'JOIN',
                    '`my_project.my_dataset.my_table2`', 'USING', '(', 'a', ')'],
            first_from_path=('my_project', 'my_dataset', 'my_table'),
            first_from_alias=EMPTY_NODE,
            num_joins=1,
            join_type='FULL',
            join_table_path=('my_project', 'my_dataset', 'my_table2'),
            join_table_alias=EMPTY_NODE,
            join_conditions=('a',)
        ),
    )
    @unpack
    def test_data_source(self, tokens,  # type: List[str]
                         first_from_path,  # type: Tuple[str, ...]
                         first_from_alias,  # type: Union[_EmptyNode, str]
                         num_joins,  # type: int
                         join_type,  # type: Union[_EmptyNode, str]
                         join_table_path,  # type: Union[_EmptyNode, Tuple[str, ...]]
                         join_table_alias,   # type: Union[_EmptyNode, str]
                         join_conditions  # type: Union[_EmptyNode, Tuple[str, ...], Tuple[Field, ...]]  # noqa: E501
                         ):
        # type: (...) -> None
        ast, leftover = data_source(tokens)

        assert isinstance(ast, DataSource)
        self.assertEqual(leftover, [])
        assert isinstance(ast.first_from[0], TableReference)
        self.assertEqual(ast.first_from[0].path, first_from_path)
        self.assertEqual(ast.first_from[1], first_from_alias)
        self.assertEqual(len(ast.joins), num_joins)
        if num_joins > 0:
            join = ast.joins[0]
            self.assertEqual(join[0], join_type)
            assert isinstance(join[1][0], TableReference)
            self.assertEqual(join[1][0].path, join_table_path)
            self.assertEqual(join[1][1], join_table_alias)
            self.assertEqual(repr(join[2]), repr(join_conditions))

    def test_core_expression(self):
        # type: () -> None
        ast, leftover = core_expression(['a'])

        self.assertEqual(leftover, [])
        assert isinstance(ast, Field)
        self.assertEqual(ast.path, ('a',))

    @data(
        (
            ['SELECT', 'a', 'FROM', '`my_project.my_dataset.my_table`'],
            ('a',)
        ),
        (
            ['SELECT', 'my_table', '.', 'a', 'FROM', '`my_project.my_dataset.my_table`'],
            ('my_table', 'a',)
        )
    )
    @unpack
    def test_select_field(self, tokens, path):
        # type: (List[str], Tuple[str, ...]) -> None
        ast, leftover = select(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Select)
        assert isinstance(ast.fields[0], Selector)
        field = ast.fields[0].children[0]
        assert isinstance(field, Field)
        self.assertEqual(field.path, path)

    def test_order_by(self):
        # type: () -> None
        ast, leftover = query_expression(['SELECT', '*', 'FROM', 'my_table',
                                          'ORDER', 'BY', 'a', 'ASC'])

        assert isinstance(ast, QueryExpression)
        self.assertEqual(leftover, [])
        assert not isinstance(ast.order_by, _EmptyNode)
        self.assertEqual(len(ast.order_by), 1)
        (field, direction) = ast.order_by[0]
        self.assertEqual(field.path, ('a',))
        self.assertEqual(direction, 'ASC')

    def test_limit_offset(self):
        # type: () -> None
        ast, leftover = query_expression(['SELECT', '*', 'FROM', 'my_table',
                                          'LIMIT', '5', 'OFFSET', '10'])
        assert isinstance(ast, QueryExpression)
        self.assertEqual(leftover, [])
        assert not isinstance(ast.limit, _EmptyNode)
        limit_expression, offset_expression = ast.limit
        assert isinstance(limit_expression, Value)
        self.assertEqual(limit_expression.value, 5)
        assert isinstance(offset_expression, Value)
        self.assertEqual(offset_expression.value, 10)

    def test_group_by(self):
        # type: () -> None
        ast, leftover = select(['SELECT', '*', 'FROM', 'my_table', 'GROUP', 'BY', 'a'])

        self.assertEqual(leftover, [])
        assert isinstance(ast, Select)
        assert not isinstance(ast.group_by, _EmptyNode)
        self.assertEqual(len(ast.group_by), 1)
        field = ast.group_by[0]
        assert isinstance(field, Field)
        self.assertEqual(field.path, ('a',))

    def test_selector_alias(self):
        # type: () -> None
        ast, leftover = select(['SELECT', 'a', 'AS', 'field_name', 'FROM', 'my_table'])

        self.assertEqual(leftover, [])
        assert isinstance(ast, Select)
        self.assertEqual(len(ast.fields), 1)
        selector = ast.fields[0]
        assert isinstance(selector, Selector)
        alias = selector.alias
        self.assertEqual(alias, 'field_name')

    @data(
        dict(tokens=['COUNT', '(', '*', ')'],
             countee=Value(1, BQScalarType.INTEGER),
             distinct=False),
        dict(tokens=['COUNT', '(', 'DISTINCT', 'a', ')'],
             countee=Field(('a',)),
             distinct=True),
        dict(tokens=['COUNT', '(', '1', ')'],
             countee=Value(1, BQScalarType.INTEGER),
             distinct=False),
    )
    @unpack
    def test_count(self, tokens,  # type: List[str]
                   countee,  # type: EvaluatableNode
                   distinct,
                   ):
        # type: (...) -> None
        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, _AggregatingFunctionCall)
        self.assertEqual(ast.children, [countee])
        assert isinstance(ast.function_info, Count)
        self.assertEqual(ast.function_info.name(), 'COUNT')
        self.assertEqual(ast.function_info.distinct, distinct)

    @data(
        (['a', 'IS', 'NULL'], Field(('a',)), True),
        (['b', 'IS', 'NOT', 'NULL'], Field(('b',)), False)
    )
    @unpack
    def test_null_check(self, tokens,  # type: List[str]
                        expression,  # type: Field
                        direction  # type: bool
                        ):
        # type: (...) -> None
        ast, leftover = post_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, NullCheck)
        self.assertEqual(ast.children[0], expression)
        self.assertEqual(ast.direction, direction)

    @data(
        (['IN'], True),
        (['NOT', 'IN'], False)
    )
    @unpack
    def test_in_check(self, direction,  # type: List[str]
                      bool_direction  # type: bool
                      ):
        # type: (...) -> None
        tokens = ['a'] + direction + ['(', '1', ',', '2', ')']
        expression = Field(('a',))
        elements = [Value(1, BQScalarType.INTEGER), Value(2, BQScalarType.INTEGER)]

        ast, leftover = post_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, InCheck)
        self.assertEqual(ast.children[0], expression)
        self.assertEqual(ast.direction, bool_direction)
        self.assertEqual(ast.children[1:], elements)

    def test_if(self):
        # type: () -> None
        # IF (3 < 5, 0, 1)
        tokens = ['IF', '(', '3', '<', '5', ',', '0', ',', '1', ')']

        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, If)
        condition, then, else_ = ast.children
        assert isinstance(condition, BinaryExpression)
        left, right = condition.children
        self.assertEqual(left, Value(3, BQScalarType.INTEGER))
        self.assertEqual(condition.operator_info.operator, '<')
        self.assertEqual(right, Value(5, BQScalarType.INTEGER))
        self.assertEqual(then, Value(0, BQScalarType.INTEGER))
        self.assertEqual(else_, Value(1, BQScalarType.INTEGER))

    def test_not(self):
        # type: () -> None
        tokens = ['NOT', '2', '=', '2']

        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Not)
        assert isinstance(ast.children[0], BinaryExpression)
        left, right = ast.children[0].children
        self.assertEqual(left, Value(2, BQScalarType.INTEGER))
        self.assertEqual(ast.children[0].operator_info.operator, '=')
        self.assertEqual(right, Value(2, BQScalarType.INTEGER))

    def test_unary_negation(self):
        # type: () -> None
        tokens = ['-', '2']

        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, UnaryNegation)
        self.assertEqual(ast.children[0], Value(2, BQScalarType.INTEGER))

    def test_case(self):
        # type: () -> None
        tokens = ['CASE', 'WHEN', 'a', '=', '1', 'THEN', '1',
                  'WHEN', 'a', '=', '2', 'THEN', '2',
                  'ELSE', '3', 'END']

        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Case)

        first_when, first_then, second_when, second_then, else_ = ast.children
        assert isinstance(first_when, BinaryExpression)
        self.assertEqual(first_when.children[0], Field(('a',)))
        self.assertEqual(first_when.operator_info.operator, '=')
        self.assertEqual(first_when.children[1], Value(1, BQScalarType.INTEGER))
        self.assertEqual(first_then, Value(1, BQScalarType.INTEGER))

        assert isinstance(second_when, BinaryExpression)
        self.assertEqual(second_when.children[0], Field(('a',)))
        self.assertEqual(second_when.operator_info.operator, '=')
        self.assertEqual(second_when.children[1], Value(2, BQScalarType.INTEGER))
        self.assertEqual(second_then, Value(2, BQScalarType.INTEGER))

        self.assertEqual(else_, Value(3, BQScalarType.INTEGER))

    def test_cast(self):
        # type: () -> None
        tokens = ['CAST', '(', '1', 'AS', 'STRING', ')']
        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Cast)
        self.assertEqual(ast.children[0], Value(1, BQScalarType.INTEGER))
        self.assertEqual(ast.type_, BQScalarType.STRING)

    def test_exists(self):
        # type: () -> None
        tokens = ['EXISTS', '(', 'SELECT', '*', 'FROM', 'Table', ')']
        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Exists)
        assert isinstance(ast.subquery, QueryExpression)
        assert isinstance(ast.subquery.base_query, Select)
        assert isinstance(ast.subquery.base_query.from_, DataSource)
        assert isinstance(ast.subquery.base_query.from_.first_from[0], TableReference)
        self.assertEqual(ast.subquery.base_query.from_.first_from[0].path, ('Table',))

    def test_extract(self):
        # type: () -> None
        tokens = ['EXTRACT', '(', 'DAY', 'FROM', 'date_field', ')']
        ast, leftover = core_expression(tokens)

        self.assertEqual(leftover, [])
        assert isinstance(ast, Extract)
        self.assertEqual(ast.part, 'DAY')
        assert isinstance(ast.children[0], Field)
        self.assertEqual(ast.children[0].path, ('date_field',))

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


import torch
import torch.nn.functional as F
import numpy as np
import torchvision.datasets as datasets
import matplotlib.pyplot as plt
import cv2
from sklearn.metrics import confusion_matrix, accuracy_score

'''
********************************* Updates 2020/05/03 *********************************
This py file consist of train and test functions that can be imported locally.
I have decided to separate these functions from experimental py files, in order to improve
readability of my code for your users. I will make use of this functions from experiment 4.
Also, I will correct test results obtained for previous experiments, especially experiment 3.

Main updates:
1.  For calculation of sensitivity, specificity, NPV and PPV, I have adjusted to make use
    of confusion matrix from sklearn. They have been verified by comparing accuracy calculated
    from confusion matrix and accuracy obtained from sklearn.
2.  Previously, evaluation of validation and testing have been done using the same function
    called 'evaluate'. On this set up, evaluation of validation has been added to a function
    'train' and evaluation of testing can be performed by newly added function called 'test'.

********************************* Updates 2020/05/12 *********************************
Sampling of images are needed for qualitative analysis

Main updates:
1.  Introduce sampling functions for qualitative analysis

'''

class ImageFolderWithPaths(datasets.ImageFolder):
    """
    Jong, A. (2019, July 5). PyTorch Image File Paths With Dataset Dataloader. Retrieved from https://gist.github.com/andrewjong/6b02ff237533b3b2c554701fb53d5c4d.
    """

    # override the __getitem__ method. this is the method that dataloader calls
    def __getitem__(self, index):
        # this is what ImageFolder normally returns
        original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)
        # the image file path
        path = self.imgs[index][0]
        # make a new tuple that includes original and the path
        tuple_with_path = (original_tuple + (path,))
        return tuple_with_path

def sampling(paths, y, fx, preds, samples):

    i = 0
    for path in paths:
        if y[i].item() == preds[i].item():
            if preds[i].item() == 1:
                samples.append((path, 'TP', fx[i][preds[i]].item()))
            else:
                samples.append((path, 'TN', fx[i][preds[i]].item()))
        else:
            if preds[i].item() == 1:
                samples.append((path, 'FP', fx[i][preds[i]].item()))
            else:
                samples.append((path, 'FN', fx[i][preds[i]].item()))
        i += 1

    return samples

def save_samples(samples, save_dir):
    fig = 0
    count = 1
    plt.figure(figsize=(10, 12))

    for path, result, probability in samples:

        if count == 17:
            fig += 1
            plt.savefig('{}/{}'.format(save_dir, fig))
            plt.close()
            plt.figure(figsize=(10, 12))
            count = 1

        img = cv2.imread(path, cv2.COLOR_BGR2RGB)
        name = '{}_{}'.format(path.split('\\')[-2][0], path.split('\\')[-1][:-4])
        xlabel = '{0}, {1:0.5f}'.format(result, probability)

        ax = plt.subplot(4, 4, count)
        ax.set_title(name)
        ax.imshow(img)
        ax.set_xlabel(xlabel)
        ax.set_xticks([]), ax.set_yticks([])  # remove unnecessary numbers on both x and y axes
        count += 1

    if count != 17:
        plt.savefig('{}/{}'.format(save_dir, fig+1))
        plt.close()

def test_metrics(TN, FP, FN, TP):

    acc = (TP + TN) / (TN + FP + FN + TP)
    sensitivity = TP/(TP+FN)
    specificity = TN/(TN+FP)
    PPV = TP/(TP+FP)
    NPV = TN/(TN+FN)

    return acc, sensitivity, specificity, PPV, NPV

def get_n_params(model):
    pp = 0
    for p in list(model.parameters()):
        n = 1
        for s in list(p.size()):
            n = n*s
        pp += n
    return pp

def train(model, device, train_iterator, valid_iterator, optimizer, criterion):
    train_loss = []
    train_acc = []
    model.train()

    for train_x, train_y in train_iterator:
        train_x = train_x.to(device)
        train_y = train_y.to(device)

        optimizer.zero_grad()

        train_fx = F.softmax(model(train_x), dim=1)
        train_preds = train_fx.argmax(dim=1)

        # calculate loss and accuracy
        loss = criterion(train_fx, train_y)
        acc = accuracy_score(train_y.detach().cpu(), train_preds.detach().cpu())

        train_loss.append(loss.item())
        train_acc.append(acc)

        loss.backward()
        optimizer.step()

    val_loss = []
    val_acc = []
    model.eval()

    with torch.no_grad():
        for val_x, val_y in valid_iterator:
            val_x = val_x.to(device)
            val_y = val_y.to(device)

            val_fx = F.softmax(model(val_x), dim=1)
            val_preds = val_fx.argmax(dim=1)

            # calculate loss and accuracy
            loss = criterion(val_fx, val_y).item()
            acc = accuracy_score(val_y.detach().cpu(), val_preds.detach().cpu())

            val_loss.append(loss)
            val_acc.append(acc)

    return np.mean(train_loss), np.mean(train_acc), np.mean(val_loss), np.mean(val_acc)

def test(model, device, test_iterator, criterion):

    samples = []
    epoch_TN, epoch_FP, epoch_FN, epoch_TP = 0, 0, 0, 0
    test_loss = []

    model.eval()

    with torch.no_grad():
        for test_x, test_y, paths in test_iterator:
            test_x = test_x.to(device)
            test_y = test_y.to(device)

            test_fx = F.softmax(model(test_x), dim=1)
            test_preds = test_fx.argmax(dim=1)
            TN, FP, FN, TP = confusion_matrix(test_y.detach().cpu(), test_preds.detach().cpu(), labels=[0,1]).ravel()
            loss = criterion(test_fx, test_y).item()

            test_loss.append(loss)

            epoch_TN += TN
            epoch_FP += FP
            epoch_FN += FN
            epoch_TP += TP

            samples = sampling(paths, test_y, test_fx, test_preds, samples)

    test_acc, sensitivity, specificity, PPV, NPV = test_metrics(epoch_TN, epoch_FP, epoch_FN, epoch_TP)

    return np.mean(test_loss), test_acc, sensitivity, specificity, PPV, NPV, samples


'''
Este arquivo contém classes pydant para a validação doss dicionários de entrada
e de saido do modelo de previsão.
'''

from typing import Any, List
from pydantic import BaseModel
from modelo.processing.validacao import VarisPrevs_schemas

#classe para validação do imput do modelo
class MultipleInputs_schemas(BaseModel):
    inputs: List[VarisPrevs_schemas]

    class Config:
        schema_extra = {
            "example": {
                'inputs':[
                    {
                        "age": 57.0,
                        "heightCm": 148.0,
                        "weightKg": 54.0,
                        "bodyFat":33.6,
                        "diastolic":78.0,
                        "systolic":135.0,
                        "gripForce":27.4,
                        "sitBendCm":18.8,
                        "sitUpsCounts":16.0,
                        "broadJumpCm":137.0,
                        "gender": "F",
                    }
                ]
            }
        }


# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.python.keras import backend as k

class Encoder(tf.keras.Model):
    def __init__(self, kernel_size, out_channels):
        super(Encoder, self).__init__()
        self.conv = tf.keras.layers.Conv1D(kernel_size=kernel_size, filters=out_channels, use_bias=False,
                                           strides=kernel_size//2, padding="same")

    def call(self, inputs, training=None, mask=None):
        inputs = tf.nn.relu(self.conv(inputs))
        return inputs

class Decoder(tf.keras.Model):
    def __init__(self, kernel_size):
        super(Decoder, self).__init__()
        self.conv = tf.keras.layers.Conv1DTranspose(kernel_size=kernel_size, filters=1, use_bias=False,
                                                    strides=kernel_size//2, padding="same")

    def call(self, inputs, training=None, mask=None):
        return self.conv(inputs)

class ConvStem(tf.keras.Model):
    def __init__(self, hidden):
        super(ConvStem, self).__init__()
        self.forward = tf.keras.Sequential([tf.keras.layers.Conv1D(filters=hidden, kernel_size=1),
                                            tfa.layers.GroupNormalization(1),
                                            tf.keras.layers.PReLU(shared_axes=[1]),
                                            tf.keras.layers.Conv1D(filters=hidden, groups=hidden, kernel_size=5, strides=1, padding="same"),
                                            tfa.layers.GroupNormalization(1),
                                            tf.keras.layers.PReLU(shared_axes=[1])])

    def call(self, inputs, training=None, mask=None):
        return self.forward(inputs)

class ConvOut(tf.keras.Model):
    def __init__(self, outputp_channels):
        super(ConvOut, self).__init__()
        self.forwad = tf.keras.Sequential([tfa.layers.GroupNormalization(1),
                                           tf.keras.layers.PReLU(shared_axes=[1]),
                                           tf.keras.layers.Conv1D(filters=outputp_channels, kernel_size=1),
                                           tfa.layers.GroupNormalization(1)])
        self.activation = tf.keras.layers.PReLU(shared_axes=[1])

    def call(self, inputs, training=None, mask=None):
        inputs, res = inputs
        inputs = self.forwad(inputs)
        return self.activation(inputs+res)

class ConvSubSample(tf.keras.Model):
    def __init__(self, input_channels, kernel_size, stride=2):
        super(ConvSubSample, self).__init__()
        self.Convs = tf.keras.Sequential([tf.keras.layers.Conv1D(filters=input_channels,
                                                                 kernel_size=kernel_size,
                                                                 groups=input_channels,
                                                                 strides=stride, padding="same"),
                                          tfa.layers.GroupNormalization(1),
                                          tf.keras.layers.PReLU(shared_axes=[1])])

    def call(self, inputs, training=None, mask=None):
        inputs = self.Convs(inputs)
        return inputs

class Ublock(tf.keras.Model):
    def __init__(self, input_chs=128, u_hidden=512, sample_depth=4):
        super(Ublock, self).__init__()
        self.sample_depth = sample_depth
        self.stemlayer = ConvStem(hidden=u_hidden)
        self.Donwsamples = [ConvSubSample(input_channels=u_hidden,
                                          kernel_size=5,
                                          stride=2) for _ in range(sample_depth)]
        self.convoutput = ConvOut(outputp_channels=input_chs)

    def call(self, inputs, training=None, mask=None):
        outputs = [self.stemlayer(inputs)]
        for i in range(self.sample_depth):
            outputs.append(self.Donwsamples[i](outputs[-1]))
        temp = outputs.pop(-1)
        for i in range(self.sample_depth):
            temp = k.repeat_elements(temp, 2, axis=1) + outputs.pop(-1)
        temp = self.convoutput([temp, inputs])
        return temp

class Separator(tf.keras.Model):
    def __init__(self, enc_channels=512, hidden_channels=128, u_hidden=512, sample_depth=4, repeat=4):
        super(Separator, self).__init__()
        self.sample_depth = sample_depth
        self.forward = tf.keras.Sequential([tfa.layers.GroupNormalization(1),
                                            tf.keras.layers.Conv1D(filters=hidden_channels, kernel_size=1,
                                                                   use_bias=True)])
        for i in range(repeat):
            self.forward.add(Ublock(u_hidden=u_hidden, sample_depth=sample_depth))
        self.forward.add(tf.keras.layers.Conv1D(filters=enc_channels, kernel_size=1,
                                                use_bias=True, activation="relu"))
        self.pad_size = None

    def pad_data(self, x):
        if self.pad_size is None:
            assert x.shape[1] > 2 ** self.sample_depth, "tai duan le"
            self.pad_size = (2 ** self.sample_depth) - int(x.shape[1]) % (2 ** self.sample_depth)
        return tf.pad(x, ((0, 0), (self.pad_size, 0), (0, 0)))

    def call(self, inputs, training=None, mask=None):
        return self.forward(self.pad_data(inputs))[:, self.pad_size:]

class SEmodelM(tf.keras.Model):
    def __init__(self,
                 input_seq_len=16384,
                 kernel_size=21,
                 sample_depth=4,
                 enc_channels=512,
                 hidden_channels=128,
                 uhidden=512):
        super(SEmodelM, self).__init__()
        self.sample_depth = sample_depth
        self.kernel_size = kernel_size
        self.pad_size = (kernel_size//2)-input_seq_len % (kernel_size//2)
        self.pad = tf.keras.layers.ZeroPadding1D(padding=(0, self.pad_size))
        self.corp = tf.keras.layers.Cropping1D(cropping=(0, self.pad_size))
        self.stl = Encoder(kernel_size=kernel_size, out_channels=enc_channels)
        self.istl = Decoder(kernel_size=kernel_size)
        self.separator = Separator(enc_channels=enc_channels,
                                   hidden_channels=hidden_channels,
                                   sample_depth=self.sample_depth, u_hidden=uhidden)

    def call(self, inputs, training=None, mask=None):
        inputs = self.pad(inputs[..., None])
        e = self.stl(inputs)
        m = self.separator(e)
        inputs = self.istl(e*m)
        inputs = self.corp(inputs)
        return inputs[..., 0]

if __name__ == '__main__':
    test_inputs = tf.ones([1, 16384])
    mod = SEmodelM()
    mod(test_inputs)
    mod.separator.summary()


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

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('arbeitsplan', '0007_auto_20141201_2134'),
    ]

    operations = [
        migrations.AlterField(
            model_name='aufgabe',
            name='teamleader',
            field=models.ForeignKey(related_name='teamleader_set', blank=True, to=settings.AUTH_USER_MODEL, help_text=b'Ein optionaler Teamleader f\xc3\xbcr die Aufgabe (nicht notwendig Vorstand)', null=True, verbose_name=b'Team-Leader'),
            preserve_default=True,
        ),
    ]


from typing import List
import numpy as np

def get_groups_sorted_by_name(data) -> List[str]:
    keys = []
    values = []
    for key, group in data.items():
        if isinstance(key, int):
            keys.append(key)
            values.append(group.name)
    #print(values)
    isort = np.argsort(keys)
    group_names = list(np.array(values, dtype='object')[isort])
    #print(group_names)
    return group_names


import json
dotw = {
    "M":  [],
    "T":  [],
    "W":  [],
    "R":  [],
    "F":  [],
    "S":  [],
    "U":  [],
}

with open("db.json") as f:
    db = json.loads(json.load(f))
classes = ["15122", "21127", "21241"]

"""for course in classes:
    for day in db[course]['lec']['day']:
        for lec, starts in db[course]['lec']['time'].items():
            info = (course, lec, starts)
            dotw[day].append(info)
    for day in db[course]['sec']['day']:
        for sec, starts in db[course]['sec']['time'].items():
            info = (course, sec, starts)
            dotw[day].append(info)"""

for course in classes:
    for day in db[course]['lec']['day']:
        dotw[day].append((course, db[course]['lec']['time']))
    for day in db[course]['sec']['day']:
        dotw[day].append((course, db[course]['lec']['time']))
# print(dotw)
def generate(day, dotw):
    for (course, sched) in dotw[day]:
        if "Le" in sched:
            occurs = db[course]['lec']['day']
            for occur in occurs:
                print(occur)
                # dotw[occur].append()
        else:
            occurs = db[course]['sec']['day']
            for occur in occurs:
                print(occur)
                # dotw[occur].append()
generate("M", dotw)


import unittest
from docker.transport import ssladapter
import pytest

try:
    from backports.ssl_match_hostname import (
        match_hostname, CertificateError
    )
except ImportError:
    from ssl import (
        match_hostname, CertificateError
    )

try:
    from ssl import OP_NO_SSLv3, OP_NO_SSLv2, OP_NO_TLSv1
except ImportError:
    OP_NO_SSLv2 = 0x1000000
    OP_NO_SSLv3 = 0x2000000
    OP_NO_TLSv1 = 0x4000000

class SSLAdapterTest(unittest.TestCase):
    def test_only_uses_tls(self):
        ssl_context = ssladapter.urllib3.util.ssl_.create_urllib3_context()

        assert ssl_context.options & OP_NO_SSLv3
        # if OpenSSL is compiled without SSL2 support, OP_NO_SSLv2 will be 0
        assert not bool(OP_NO_SSLv2) or ssl_context.options & OP_NO_SSLv2
        assert not ssl_context.options & OP_NO_TLSv1

class MatchHostnameTest(unittest.TestCase):
    cert = {
        'issuer': (
            (('countryName', u'US'),),
            (('stateOrProvinceName', u'California'),),
            (('localityName', u'San Francisco'),),
            (('organizationName', u'Docker Inc'),),
            (('organizationalUnitName', u'Docker-Python'),),
            (('commonName', u'localhost'),),
            (('emailAddress', u'info@docker.com'),)
        ),
        'notAfter': 'Mar 25 23:08:23 2030 GMT',
        'notBefore': u'Mar 25 23:08:23 2016 GMT',
        'serialNumber': u'BD5F894C839C548F',
        'subject': (
            (('countryName', u'US'),),
            (('stateOrProvinceName', u'California'),),
            (('localityName', u'San Francisco'),),
            (('organizationName', u'Docker Inc'),),
            (('organizationalUnitName', u'Docker-Python'),),
            (('commonName', u'localhost'),),
            (('emailAddress', u'info@docker.com'),)
        ),
        'subjectAltName': (
            ('DNS', u'localhost'),
            ('DNS', u'*.gensokyo.jp'),
            ('IP Address', u'127.0.0.1'),
        ),
        'version': 3
    }

    def test_match_ip_address_success(self):
        assert match_hostname(self.cert, '127.0.0.1') is None

    def test_match_localhost_success(self):
        assert match_hostname(self.cert, 'localhost') is None

    def test_match_dns_success(self):
        assert match_hostname(self.cert, 'touhou.gensokyo.jp') is None

    def test_match_ip_address_failure(self):
        with pytest.raises(CertificateError):
            match_hostname(self.cert, '192.168.0.25')

    def test_match_dns_failure(self):
        with pytest.raises(CertificateError):
            match_hostname(self.cert, 'foobar.co.uk')


from langchain import LlamaCpp, PromptTemplate, LLMChain

llm = LlamaCpp(model_path='/Users/yangzy/Documents/model/Llama2-chat-13B-Chinese-50W/ggml-model-q4_0.gguf',
               max_tokens=1000,
               temperature=0.1,
               verbose=False,
               n_gpu_layers=0)

prompt = PromptTemplate(
    input_variables=["location"],
    template="我想去{location}旅行，我应该怎么办？",
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run('北京')
print(result)


"""Thermal continuum models."""

import numpy as np
import scipy.constants as sc

WIEN = sc.physical_constants['Wien frequency displacement law constant'][0]

def blackbody(variable, temp, model='planck', variable_type='frequency'):
    """Black body spectral radiance.

    Args:
        variable: frequency in [Hz] or wavelength in [m]
        temp: temperature in [K]
        model: black body model, either 'planck' or 'rj'
        variable_type: variable type, either 'frequency' or 'wavelength'

    Returns:
        spectral radiance

    """

    # Planck vs frequency
    if model.lower() == 'planck' and variable_type.lower() == 'frequency':
        term1 = 2 * sc.h * variable ** 3 / sc.c ** 2
        term2 = np.exp(sc.h * variable / (sc.k * temp)) - 1
        return term1 / term2

    # Planck vs wavelength
    if model.lower() == 'planck' and variable_type.lower() == 'wavelength':
        term1 = 2 * sc.h * sc.c ** 2 / variable ** 5
        term2 = np.exp(sc.h * sc.c / (variable * sc.k * temp)) - 1
        return term1 / term2

    # Rayleigh-Jeans vs frequency
    if model.lower() == 'rj' and variable_type.lower() == 'frequency':
        return 2 * variable ** 2 * sc.k * temp / sc.c ** 2

    # Rayleigh-Jeans vs wavelength
    if model.lower() == 'rj' and variable_type.lower() == 'wavelength':
        return 2 * sc.c * sc.k * temp / variable ** 4

def wien(temp):
    """Wien's displacement law.

    Args:
        temp: temperature in [K]

    Returns:
        frequency at which the blackbody curve peaks

    """

    return temp * WIEN

# def temp_cw(freq, tphys):

#     freq = float(freq)
#     tphys = float(tphys)

#     return sc.h * freq / 2 / sc.k / np.tanh(sc.h * freq / 2 / sc.k / tphys)


#!/bin/env python3
import asyncio
import math
import random
import tkinter as tk

from async_tkinter_loop import async_handler, async_mainloop

async def shoot_spark(x, y):
    direction = 2 * math.pi * random.random()
    vel = random.randint(5, 20)
    dx = math.cos(direction)
    dy = math.sin(direction)
    spark_len = 10

    spark = canvas.create_line(x, y, x + dx * spark_len, y + dy * spark_len, fill="yellow")

    for _ in range(5):
        await asyncio.sleep(0.05)
        x += dx * vel
        y += dy * vel
        canvas.coords(spark, x, y, x + dx * spark_len, y + dy * spark_len)

    canvas.delete(spark)

@async_handler
async def on_mouse_drag(event):
    x = event.x
    y = event.y
    await asyncio.wait([asyncio.create_task(shoot_spark(x, y)) for _ in range(5)])

root = tk.Tk()

canvas = tk.Canvas(root, bg="black", highlightthickness=0)
canvas.pack(expand=1, fill=tk.BOTH)

canvas.bind("<B1-Motion>", on_mouse_drag)

async_mainloop(root)


from PIL import Image
import os, random

def filter_img(train, validation, new_train, new_validation, min_greytone):
    count = 0

    if not os.path.exists(new_train):
        os.makedirs(new_train)

    for dir_name in os.listdir(train):
        sub_dir = train + '/' + dir_name

        if not os.path.exists(new_train + '/' + dir_name):
            os.makedirs(new_train + '/' + dir_name)

        for subdir_filename in os.listdir(sub_dir):
            im = Image.open(train + '/' + dir_name + '/' + subdir_filename)
            pixelMap = im.load()
            img = Image.new( im.mode, im.size)
            pixelsNew = img.load()

            for i in range(img.size[0]):
                for j in range(img.size[1]):
                    if pixelMap[i,j] < min_greytone:
                        pixelsNew[i,j] = 0
                    else:
                        pixelsNew[i,j] = 255

            img.save(new_train + '/' + dir_name + '/' + subdir_filename)

    if not os.path.exists(new_validation):
        os.makedirs(new_validation)

    for dir_name in os.listdir(validation):
        sub_dir = validation + '/' + dir_name

        if not os.path.exists(new_validation + '/' + dir_name):
            os.makedirs(new_validation + '/' + dir_name)

        for subdir_filename in os.listdir(sub_dir):
            im = Image.open(validation + '/' + dir_name + '/' + subdir_filename)
            pixelMap = im.load()
            img = Image.new( im.mode, im.size)
            pixelsNew = img.load()

            for i in range(img.size[0]):
                for j in range(img.size[1]):
                    if pixelMap[i,j] < min_greytone:
                        pixelsNew[i,j] = 0
                    else:
                        pixelsNew[i,j] = 255

            img.save(new_validation + '/' + dir_name + '/' + subdir_filename)

filter_img(os.getcwd() + '/unfiltered_training_data', os.getcwd() + '/unfiltered_validation_data', os.getcwd() + '/training_data', os.getcwd() + '/validation_data', 180)


from django.urls import path, re_path, include
from . import views
# 注册自定义路径转化器
from django.urls import register_converter
from . import converters
register_converter(converters.CustomYearConverter, 'yyyy')

app_name = 'demo'

urlpatterns01 = [
    # ''' 常用路径转化器 '''
    # path('', views.url_standard_number),  # number默认值
    # path('0/', views.url_standard_fix, name='url_standard_fix'),  # 固定路径
    # path('<int:number>/', views.url_standard_number),  # int型
    # path('<uuid:uuid>/', views.url_standard_uuid),  # uuid
    # path('<slug:slug>/', views.url_standard_slug),  # slug
    # path('<str:str>/', views.url_standard_str),  # str
    # path('<path:path>/', views.url_standard_path),  # path
    # ''' 自定义路径转化器 '''
    # re_path(r'^custom/re/(?P<year>[0-9]{4})/$', views.url_custom_year),
    # path('custom/<yyyy:year>/', views.url_custom_year),
    # redirect
    # path('redirect/', views.redirect)
]

urlpatterns02 = [
    # path('cbv/', views.Class_Base_View.as_view()),
    # path('index/', views.index, name='index'),
    # path('model/<int:pk>', views.get_model),
]

urlpatterns = [
    # path('url/', include(urlpatterns01)),
    # path('templates/', include(urlpatterns02)),
    path('index/', views.index, name='index'),
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout')
]


from pathlib import Path

from .cifar import convert_cifar
from .dwtc import convert_dwtc
from .religious_texts import convert_religions_texts
from .uci import import_uci
from ..models import Dataset
from ..config import db, logger, DATA_PATH

def import_test_datasets(data_path: Path = None):
    if data_path is None:
        data_path = DATA_PATH
    data_path.mkdir(parents=True, exist_ok=True)
    existing_dataset_names = [d.name for d in db.query(Dataset).all()]
    try:
        if "CIFAR" not in existing_dataset_names:
            convert_cifar(data_path)
    except Exception as e:
        error = e.message if hasattr(e, "message") else str(e)
        logger.warning("Could not import CIFAR dataset. Failed with message: " + error)
    try:
        if "DWTC" not in existing_dataset_names:
            convert_dwtc(data_path)
    except Exception as e:
        error = e.message if hasattr(e, "message") else str(e)
        logger.warning("Could not import dwtc dataset. Failed with message: " + error)

    try:
        if "Religions Texts" not in existing_dataset_names:
            convert_religions_texts(data_path)
    except Exception as e:
        error = e.message if hasattr(e, "message") else str(e)
        logger.warning(
            "Could not import religions_texts dataset. Failed with message: " + error
        )

    uci_datasets = [
        "glass",
        "zoo",
        "HABERMAN",
        "GERMAN",
        "parkinsons",
        "PLANNING",
        "ILPD",
        "flag",
        "DIABETES",
        "FERTILITY",
        "australian",
        "IONOSPHERE",
        "PIMA",
        "adult",
        "HEART",
        "wine",
        "BREAST",
        "abalone",
    ]

    for uci_dataset in uci_datasets:
        try:
            if uci_dataset not in existing_dataset_names:
                logger.info("import uci " + uci_dataset)
                import_uci(uci_dataset, data_path)
            else:
                logger.info("uci " + uci_dataset + " exists already")
        except Exception as e:
            error = e.message if hasattr(e, "message") else str(e)
            logger.warning(
                "Could not import uci dataset "
                + uci_dataset
                + ". Failed with message: "
                + error
            )

if __name__ == "__main__":
    import_test_datasets()


# Definition for a binary tree node.
from typing import List

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        def rec(arr):
            if len(postorder):
                value = postorder[-1]
                node = TreeNode(value)
                if value in arr:
                    pos = arr.index(value)
                    postorder.pop()
                    node.right = rec(arr[pos + 1 :])
                    node.left = rec(arr[:pos])
                    return node
                return None

        return rec(inorder)


import cv2
import math
import time

from JetsonCamera import Camera
from Focuser import Focuser

# nvarguscamera
cam_1 = cv2.VideoCapture("gst-launch-1.0 nvarguscamerasrc sensor_id=0 ! video/x-raw(memory:NVMM), width=1280, height=720, format=NV12, framerate=30/1 ! nvvidconv flip-method=0 ! video/x-raw, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink")
cam_2 = cv2.VideoCapture("gst-launch-1.0 nvarguscamerasrc sensor_id=1 ! video/x-raw(memory:NVMM), width=1920, height=1080, format=NV12, framerate=30/1 ! nvvidconv flip-method=0 ! video/x-raw, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink")

focuser_cam_1 = Focuser(7)
focuser_cam_2 = Focuser(8)
focuser_cam_1.set(Focuser.OPT_FOCUS, 150)
focuser_cam_2.set(Focuser.OPT_FOCUS, 150)

while True:
    res, frame = cam_2.read()
    # resize
    frame = cv2.resize(frame, (1280, 720))

    if not res:
        print("Ignoring empty camera frame.")
        continue

    # line to draw a square in the middle of the frame, square is 100 px to the right and have the size of 200x200
    cv2.rectangle(frame, (640, 360), (840, 560), (0, 255, 0), 2)

    cv2.imshow("Camera 1", frame)

    for detection in detections:
        # centroid coordinates
        x = int(detection.Center[0])
        y = int(detection.Center[1])
        # draw circle on centroid
        cv2.circle(resized, (x, y), 5, (0, 0, 255), -1)
        # draw bounding box
        cv2.rectangle(resized, (int(detection.Left), int(detection.Top)), (int(detection.Right), int(detection.Bottom)), (255, 0, 0), 2)
        # object class name and confidence
        cv2.putText(resized, "%s (%.1f%%)" % (detection.ClassID, detection.Confidence * 100), (int(detection.Left), int(detection.Top) - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
        # distance calculation from the camera
        distance = (net.GetNetworkHeight() * 0.5) / math.tan(detection.Height * 0.5 * math.pi / 180)
        # draw distance
        cv2.putText(resized, "Distance: %.1f" % distance, (int(detection.Left), int(detection.Top) - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
        print("Distance: %.1f" % distance)
        # if centroid coordinates is in the middlle of the line, drop payload
        if x >= int(resized.shape[1] / 2) - 200 and x <= int(resized.shape[1] / 2) + 200:
            # move forward a bit
            print("Moving forward a bit")
            # if distance is less than 200, drop payload
            if distance <= 120:
                # hover for 1 second
                # Move forward 1 meter
                # Drop payload
                print("Hovering for 1 second")
                print("Payload dropped")
                drop = True
                break
            # if centroid outside the line, adjust position
        else:
            # if centroid coordinates is in the right side of the resized, roll right
            if x >= int(resized.shape[1] / 2) + 200:
                print("Roll right")
            # if centroid coordinates is in the left side of the resized, roll left
            elif x <= int(resized.shape[1] / 2) - 200:
                print("Roll left")

    cv2.imshow("Camera 1", resized)

    if drop == True:
        print("Quitting...")
        break

cam_2.release()
cv2.destroyAllWindows()


import pickle
from typing import Tuple

from src.model import Piece, Board, State
from src.constant import ShapeConstant, GameConstant

def dump(obj, path):
    """
    [DESC]
        Function to dump Object
    [PARAMS]
        obj: Object -> objects you want dump
    """
    pickle.dump(obj, open(path, "wb"))

def is_out(board: Board, row: int, col: int) -> bool:
    """
    [DESC]
        Function to see if the piece (row, col) is outside of the board
    [PARAMS]
        board: Board -> current board
        row: int -> row to be checked
        col: int -> column to be checked
    [RETURN]
        True if outside board
        False if inside board
    """
    return row < 0 or row >= board.row or col < 0 or col >= board.col

def is_full(board: Board) -> bool:
    """
    [DESC]
        Function to see if current board is full of pieces
    [PARAMS]
        board: Board -> current board
    [RETURN]
        True if board is full
        False if board is not full
    """
    for row in range(board.row):
        for col in range(board.col):
            if board[row, col].shape == ShapeConstant.BLANK:
                return False
    return True

def check_streak(board: Board, row: int, col: int) -> Tuple[str, str, str]:
    """
    [DESC]
        Function to check streak from row, col in current board
    [PARAMS]
        board: Board -> current board
        row: int -> row
        col: int -> column
    [RETURN]
        None if the row, col in a board isn't filled with piece
        Tuple[prior, shape, color] match with player set if streak found and cause of win
    """
    piece = board[row, col]
    if piece.shape == ShapeConstant.BLANK:
        return None

    streak_way = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]

    for prior in GameConstant.WIN_PRIOR:
        mark = 0
        for row_ax, col_ax in streak_way:
            row_ = row + row_ax
            col_ = col + col_ax
            for _ in range(GameConstant.N_COMPONENT_STREAK - 1):
                if is_out(board, row_, col_):
                    mark = 0
                    break

                shape_condition = (
                    prior == GameConstant.SHAPE
                    and piece.shape != board[row_, col_].shape
                )
                color_condition = (
                    prior == GameConstant.COLOR
                    and piece.color != board[row_, col_].color
                )
                if shape_condition or color_condition:
                    mark = 0
                    break

                row_ += row_ax
                col_ += col_ax
                mark += 1

            if mark == GameConstant.N_COMPONENT_STREAK - 1:
                player_set = [
                    (GameConstant.PLAYER1_SHAPE, GameConstant.PLAYER1_COLOR),
                    (GameConstant.PLAYER2_SHAPE, GameConstant.PLAYER2_COLOR),
                ]
                for player in player_set:
                    if prior == GameConstant.SHAPE:
                        if piece.shape == player[0]:
                            return (prior, player)

                    elif prior == GameConstant.COLOR:
                        if piece.color == player[1]:
                            return (prior, player)

def is_win(board: Board) -> Tuple[str, str]:
    """
    [DESC]
        Function to check if player won
    [PARAMS]
        board: Board -> current board
    [RETURN]
        None if there is no streak
        Tuple[shape, color] match with player set if there is a streak
    """
    temp_win = None
    for row in range(board.row):
        for col in range(board.col):
            checked = check_streak(board, row, col)
            if checked:
                if checked[0] == GameConstant.WIN_PRIOR[0]:
                    return checked[1]
                else:
                    temp_win = checked[1]
    return temp_win

def place(state: State, n_player: int, shape: str, col: str) -> int:
    """
    [DESC]
        Function to place piece in board
    [PARAMS]
        state = current state in the game
        n_player = which player (player 1 or 2)
        shape = shape
        col = which col
    [RETURN]
        -1 if placement is invalid
        int(row) if placement is valid
    """
    if state.players[n_player].quota[shape] == 0:
        return -1

    for row in range(state.board.row - 1, -1, -1):
        if state.board[row, col].shape == ShapeConstant.BLANK:
            piece = Piece(shape, GameConstant.PLAYER_COLOR[n_player])
            state.board.set_piece(row, col, piece)
            state.players[n_player].quota[shape] -= 1
            return row

    return -1


from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator
from django.conf import settings
from django.contrib.auth.decorators import login_required

from .models import Post, Group, User
from .forms import PostForm

def pagination(post_list, request):
    paginator = Paginator(post_list, settings.QUANTITY_POSTS)
    return paginator.get_page(request.GET.get('page'))

def index(request):
    post_list = Post.objects.select_related('author', 'group')
    page_obj = pagination(post_list, request)

    context = {
        'page_obj': page_obj,
    }
    return render(request, 'posts/index.html', context)

def group_posts(request, slug):
    group = get_object_or_404(Group, slug=slug)
    posts = group.posts.select_related('author')
    page_obj = pagination(posts, request)
    context = {
        'group': group,
        'page_obj': page_obj,
        'group_list': True
    }
    return render(request, 'posts/group_list.html', context)

def profile(request, username):
    author = User.objects.get(username=username)
    post_list = author.posts.select_related('group')
    page_obj = pagination(post_list, request)

    context = {
        'page_obj': page_obj,
        'author': author,
        'profile': True
    }
    return render(request, 'posts/profile.html', context)

def post_detail(request, post_id):
    post = get_object_or_404(
        Post.objects.select_related('author', 'group'), pk=post_id
    )
    context = {
        'post': post,
        'post_count': post.author.posts.all(),
    }
    return render(request, 'posts/post_detail.html', context)

@login_required
def post_create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        form.instance.author = request.user
        form.save()
        return redirect('posts:profile', request.user.username)

    context = {
        'form': form,
        'is_edit': False
    }
    return render(request, 'posts/create_post.html', context)

@login_required
def post_edit(request, post_id):
    post = get_object_or_404(
        Post.objects.select_related('author', 'group'), pk=post_id
    )
    if request.user != post.author:
        return redirect('posts:post_detail', post.id)

    form = PostForm(request.POST or None, instance=post)

    if form.is_valid():
        form.save()
        return redirect('posts:post_detail', post.id)

    context = {
        'form': form,
        'is_edit': True
    }
    return render(request, 'posts/create_post.html', context)


from backend import db
from datetime import timedelta
from sqlalchemy.dialects.postgresql import ARRAY
from geoalchemy2 import Geometry
from flask import json

from backend.models.sql.enum import ChallengeStatus, TranslateEngine, FeatureStatus
from backend.models.sql.features import Feature
from backend.models.dtos.challenge_dto import (
    ChallengeDTO,
    ChallengeSummaryDTO,
    ChallengeStatsDTO,
)
from backend.services.utills import get_last_updated, to_strfdate, timestamp

class Challenge(db.Model):
    """Describes challenge"""

    __tablename__ = "challenge"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    description = db.Column(db.String, nullable=True)
    country = db.Column(db.String, nullable=True)
    status = db.Column(db.Integer, nullable=False)
    to_language = db.Column(db.String, nullable=False)

    bbox = db.Column(Geometry("POLYGON", srid=4326), nullable=True)
    centroid = db.Column(Geometry("POINT", srid=4326), nullable=True)
    overpass_query = db.Column(db.String, nullable=True)
    language_tags = db.Column(ARRAY(db.String), nullable=False)

    due_date = db.Column(
        db.DateTime, nullable=False, default=timestamp() + timedelta(days=30)
    )
    created = db.Column(db.DateTime, default=timestamp())
    last_updated = db.Column(db.DateTime, default=timestamp())
    features = db.relationship(
        Feature,
        backref="challenge",
        lazy="dynamic",
        cascade="all, delete, delete-orphan",
    )
    translate_engine = db.Column(db.Integer, nullable=True)
    api_key = db.Column(db.String, nullable=True)
    feature_instructions = db.Column(db.String(255), nullable=True)

    created_by = db.Column(
        db.BigInteger, db.ForeignKey("users.id", name="fk_users"), nullable=False
    )

    def create(self):
        """Create new entry"""
        db.session.add(self)
        db.session.commit()

    def update(self):
        """Save changes to db"""
        db.session.commit()

    def delete(self):
        """Delete entry from db"""
        db.session.delete(self)
        db.session.commit()

    def as_dto(self, stats=False):
        """Convert to dto"""
        challenge_dto = ChallengeDTO(
            id=self.id,
            name=self.name,
            status=ChallengeStatus(self.status).name,
            description=self.description,
            country=self.country,
            to_language=self.to_language,
            due_date=self.due_date,
            created=self.created,
            last_updated=self.last_updated,
            language_tags=", ".join(self.language_tags),
            translate_engine=TranslateEngine(self.translate_engine).name
            if self.translate_engine
            else None,
            feature_instructions=self.feature_instructions,
        )
        challenge_dto.bbox = json.loads(
            db.engine.execute(self.bbox.ST_AsGeoJSON()).scalar()
        )
        challenge_dto.centroid = json.loads(
            db.engine.execute(self.centroid.ST_AsGeoJSON()).scalar()
        )
        if stats:
            challenge_dto.stats = self.get_challenge_progress()
        return challenge_dto

    def as_dto_for_summary(self, stats):
        challenge_dto = ChallengeSummaryDTO(
            id=self.id,
            name=self.name,
            status=self.status,
            description=self.description,
            country=self.country,
            to_language=self.to_language,
            due_date=(self.due_date - timestamp()).days,
            last_updated=get_last_updated(self.last_updated),
            created=to_strfdate(self.created),
        )
        challenge_dto.centroid = json.loads(
            db.engine.execute(self.centroid.ST_AsGeoJSON()).scalar()
        )
        challenge_dto.bbox = json.loads(
            db.engine.execute(self.bbox.ST_AsGeoJSON()).scalar()
        )
        if stats:
            challenge_dto.stats = self.get_challenge_progress()
        return challenge_dto

    @staticmethod
    def get_by_id(challenge_id: int):
        """Get challenge by id"""
        return Challenge.query.get(challenge_id)

    @staticmethod
    def get_all():
        """Get all challenges"""
        return Challenge.query.all()

    @staticmethod
    def get_all_by_status(status: int):
        """Get all challenges by status"""
        return Challenge.query.filter_by(status=status).all()

    def get_challenge_progress(self):
        """Get challenge progress"""
        challenge_stats_dto = ChallengeStatsDTO(
            total=self.features.count(),
            localized=self.features.filter_by(
                status=FeatureStatus.LOCALIZED.value
            ).count(),
            skipped=self.features.filter_by(status=FeatureStatus.OTHER.value).count(),
            already_localized=self.features.filter_by(
                status=FeatureStatus.ALREADY_LOCALIZED.value
            ).count(),
            validated=self.features.filter_by(
                status=FeatureStatus.VALIDATED.value
            ).count(),
            too_hard=self.features.filter_by(
                status=FeatureStatus.TOO_HARD.value
            ).count(),
            invalid_data=self.features.filter_by(
                status=FeatureStatus.INVALID_DATA.value
            ).count(),
            to_localize=self.features.filter_by(
                status=FeatureStatus.TO_LOCALIZE.value
            ).count(),
        )

        return challenge_stats_dto


# -*- coding: utf-8 -*-
"""
Created on Wed Oct 24 22:34:27 2018

@author: Administrator
"""

import tensorflow as tf
import numpy as np

x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3

Weights=tf.Variable(tf.random_uniform([1],-1,1))
biases=tf.Variable(tf.zeros([1]))

y=Weights*x_data+biases

loss=tf.reduce_mean(tf.square(y-y_data))
optimizer=tf.train.GradientDescentOptimizer(0.5)
train=optimizer.minimize(loss)

init=tf.global_variables_initializer()

sess=tf.Session()
sess.run(init)
for step in range(201):
    sess.run(train)
    if step %20 ==0:
        print(step,sess.run(Weights),sess.run(biases))

###########placeholder
import tensorflow as tf

input1=tf.placeholder(tf.float32)
input2=tf.placeholder(tf.float32)

output=tf.multiply(input1,input2)

with tf.Session() as sess:
    print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))

##########定义网络层
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs,in_size,out_size,activation_function=None):
    Weights=tf.Variable(tf.random_normal([in_size,out_size]))
    biases=tf.Variable(tf.zeros([1,out_size])+0.1)
    Wx_plus_b=tf.matmul(inputs,Weights)+biases
    if activation_function is None:
        outputs=Wx_plus_b
    else:
        outputs=activation_function(Wx_plus_b)

    return outputs

x_data=np.linspace(-1,1,300)[:,np.newaxis]
noise=np.random.normal(0,0.05,x_data.shape)
y_data=np.square(x_data)-0.5+noise

xs=tf.placeholder(tf.float32,[None,1])
ys=tf.placeholder(tf.float32,[None,1])

l1=add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction=add_layer(l1,10,1,activation_function=None)

loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))

train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init=tf.global_variables_initializer()

sess=tf.Session()
sess.run(init)

hg=plt.figure()

for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if(i%50==0):
        print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))

#########################minist分类
# from tensorflow.examples.tutorials.mnist import input_data
# mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
#
# xs = tf.placeholder(tf.float32,[None,784])
# ys = tf.placeholder(tf.float32,[None,10])
# prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)
# cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
#
# train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# sess=tf.Session()
#
#
# sess.run(tf.global_variables_initializer())
#
# batch_xs,batch_ys=mnist.train.next_batch(100)
# sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
#
# def compute_accuracy(v_xs,v_ys):
#     global prediction
#     y_pre=sess.run(prediction,feed_dict={xs:v_xs})
#     correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
#     accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#     result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
#     return result
# for i in range(1000):
#     sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
#     if (i%50==0):
#         print(compute_accuracy(mnist.test.images,mnist.test.lables)
#
#
# ################dropout
# from sklearn.datasets import load_digits
# from sklearn.cross_validation import train_test_split
# from sklearn.preprocessing import LabelBinarizer
#
# keep_prob=tf.placeholder(tf.float32)
#
#


import numpy as np
import tensorflow as tf
from PIL import Image
import json
import argparse
import tensorflow as tf
import tensorflow_hub as hub

batch_size = 64

# setting
parser = argparse.ArgumentParser()
parser.add_argument(action='store', dest='image_path',
                    default='./test_images/cautleya_spicata.jpg')

parser.add_argument(action='store', dest='model_dir',
                    default='my_model.h5')

parser.add_argument('--top_k', action='store', dest='top_k',
                    default=1)

parser.add_argument('--category_names', action='store',
                    dest='category_names', default='label_map.json')

args = parser.parse_args()

# load the model
save_dir = args.model_dir
model = tf.keras.experimental.load_from_saved_model(
    save_dir, custom_objects={'KerasLayer': hub.KerasLayer})

# load the image
image = Image.open(args.image_path)

# process the image
image = np.array(image)
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (224, 224))
image /= 255
image = np.expand_dims(image, axis=0)

# make prediction
probs = model.predict(image).flatten().tolist()

# open class_names file
with open(args.category_names, 'r') as f:
    class_names = json.load(f)

# Get the probability and the predicted class
for i in range(int(args.top_k)):
    prob = max(probs)
    index = probs.index(prob) + 1
    cls = class_names[str(index)]
    # Print the probability and the predicted class
    print(prob)
    print(cls)
    probs.remove(prob)
    i += 1


import unittest
import os
import tempfile

from .git import Git, Shell

class GitApiTestCase(unittest.TestCase):

    def setUp(self):
        super().setUp()
        self.git_repo = tempfile.TemporaryDirectory()
        self.shell = Shell(working_directory=self.git_repo.name)

    def tearDown(self):
        self.git_repo.cleanup()
        super().tearDown()

class TestShell(GitApiTestCase):

    def setUp(self):
        super().setUp()
        repo_name = os.path.abspath(self.git_repo.name)
        open(os.path.join(repo_name, 'file-01'), 'a').close()
        open(os.path.join(repo_name, 'file-02'), 'a').close()
        open(os.path.join(repo_name, 'file-03'), 'a').close()

    def test_ls(self):
        out = self.shell.run('ls')
        expected = (True, 'file-01\nfile-02\nfile-03\n')
        self.assertEqual(out, expected, msg='Expected %s, found %s' % (expected, out))

    def test_touch(self):
        expected = (True, '')
        out = self.shell.run('touch file-04')
        self.assertEqual(out, expected, msg='Expected %s, found %s' % (expected, out))
        expected = (True, 'file-01\nfile-02\nfile-03\nfile-04\n')
        out = self.shell.run('ls')
        self.assertEqual(out, expected, msg='Expected %s, found %s' % (expected, out))

class TestGit(GitApiTestCase):

    def setUp(self):
        super().setUp()
        repo_name = os.path.abspath(self.git_repo.name)
        open(os.path.join(repo_name, 'file-01'), 'a').close()
        open(os.path.join(repo_name, 'file-02'), 'a').close()
        open(os.path.join(repo_name, 'file-03'), 'a').close()
        self.shell.run('git init')
        self.shell.run('git add *')
        self.shell.run('git commit -m "Initial commit"')
        self.shell.run('git checkout -b branch-01')
        self.shell.run('git checkout -b branch-02')
        self.shell.run('git checkout -b branch-03')
        self.shell.run('git checkout master')

        self.git = Git(self.shell)

    def test_branch(self):
        expected = ['master', 'branch-01', 'branch-02', 'branch-03']
        out = self.git.branch()
        self.assertEqual(expected, out, 'Expected %s, but found %s.' % (expected, out))

    def test_checkout_existing_branch(self):
        self.git.checkout('branch-02')
        expected = ['branch-02', 'branch-01', 'branch-03', 'master']
        out = self.git.branch()
        self.assertEqual(expected, out, 'Expected %s, but found %s.' % (expected, out))

    def test_checkout_new_branch(self):
        self.git.checkout('branch-04')
        expected = ['branch-04', 'branch-01', 'branch-02' 'branch-03', 'master']
        out = self.git.branch()
        self.assertEqual(expected, out, 'Expected %s, but found %s.' % (expected, out))

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


# Model
# Import All Dependencies
from bs4 import BeautifulSoup
from splinter import Browser
import os
import pandas as pd
from selenium import webdriver

def init_browser():
    executable_path = {"executable_path": "/Users/BohuCyn/Anaconda/pkgs/selenium-chromedriver-2.27-0/Library/bin/chromedriver"}
    return Browser("chrome", **executable_path, headless=False)

def scrape():
    browser = init_browser()
    project_mars = {}

    # ** 1. Scrapping latest news about mars from nasa **
    url = 'https://mars.nasa.gov/news/'
    browser.visit(url)

    # Scrape page into Soup
    html = browser.html
    soup = BeautifulSoup(html, "html.parser")

    news_title = soup.find("div",class_="content_title").text
    news_paragraph = soup.find('div', class_='article_teaser_body').text

    project_mars['news_title'] = news_title
    project_mars['news_paragraph'] = news_paragraph

    #return project_mars

    # ** 2. Scraping featured image **
    image_url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=featured#submit'
    browser.visit(image_url)

    # Pass the url to BeautifulSoup
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')

    results = soup.find_all("li", class_='slide')

    for result in results:
        link = result.a['data-fancybox-href']
        break

    base_url = 'https://www.jpl.nasa.gov'

    featured_image_url = base_url + link

    project_mars["featured_image_url"] = featured_image_url

   # ** 3. Scraping Mars Weather **

    # Set url to visit with splinter
    weather_url = 'https://twitter.com/marswxreport?lang=en'
    browser.visit(weather_url)

    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')

    mars_weather = soup.find("p",class_="TweetTextSize TweetTextSize--normal js-tweet-text tweet-text").text

    project_mars["mars_weather"] = mars_weather

    # ** 4. Scraping Mars Facts Table **

    url_facts = "https://space-facts.com/mars/"
    tables = pd.read_html(url_facts)
    df = tables[0]

    mars_facts_table = df.to_html(buf=None, columns=None, col_space=None, header=False, index=False, \
                    na_rep='NaN', index_names=False, justify='right', bold_rows=True, classes=None, \
                    escape=True, max_rows=None, max_cols=None, show_dimensions=False, \
                    notebook=False, decimal='.', border=1)

    project_mars["mars_facts_table"] = mars_facts_table

    # ** 5. Scraping Mars # Mars Hemispheres **

    # URL general
    hemispheres_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
    browser.visit(hemispheres_url)

    html_hemispheres = browser.html

    # Use Beautiful Soup
    soup = BeautifulSoup(html_hemispheres, 'html.parser')

    # Obtain hemispheres box
    items = soup.find_all('div', class_='item')

    hemisphere_image_urls = []

# URL base
    main_url = 'https://astrogeology.usgs.gov'

    # For loop to go through the items
    for item in items:
        # Hemisphere Title
        title = item.find('h3').text

        # URL with relative path for full sized image
        href = item.find('a', class_='itemLink product-item')['href']

        # Visit the link that contains the full image website
        browser.visit(main_url + href)

        # HTML Object of individual hemisphere information website
        partial_img_html = browser.html

        # Parse HTML with Beautiful Soup for every individual hemisphere information website
        soup = BeautifulSoup( partial_img_html, 'html.parser')

        # Obtain full image url
        img_url = main_url + soup.find('img', class_='wide-image')['src']

        # Append the information into a list of dictionaries
        hemisphere_image_urls.append({"title" : title, "img_url" : img_url})

    project_mars['hemisphere_image_urls'] = hemisphere_image_urls

        # Return dictionary of scraped values we created
    return project_mars

# For debugging
if __name__ == "__main__":
    project_mars = scrape()
    print(project_mars)

APP (scrape, flask and more)/scrape_mars.py


import os
from torchvision.transforms import functional as tr
from PIL import Image
# import os.path
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
import numpy as np
from random import randrange

# ImageNet mean and standard deviation. All images
# passed to a PyTorch pre-trained model (e.g. AlexNet) must be
# normalized by these quantities, because that is how they were trained.
imagenet_mean = (0.485, 0.456, 0.406)
imagenet_std = (0.229, 0.224, 0.225)

def compute_features(model, conditionsPath, resolutionval = 224,cropval=256,WordInf =[],paddingval=0,padding_mode='constant'):
    #takes model and loads the features for that image, needs path to of files in directory

    conditions = listdir(conditionsPath)
    # print(conditions)

    if WordInf != np.array([]):
        new_conditions = []
        for c in conditions:
            w = c.split('/')[-1]
            if w in WordInf:
                new_conditions.append(c)
        conditions = new_conditions

    condition_features = {}
    for c in tqdm(conditions):
        c_name = c.split('/')[-1]

        stimuli = listdir(c)
        #resize according to resolution and square the image
        stimuli = [image_to_tensor(s, resolution=resolutionval,cropval = cropval,paddingval=paddingval,padding_mode = padding_mode) for s in stimuli]
        # print(stimuli)
        stimuli = torch.stack(stimuli)
        # print(stimuli)
        if torch.cuda.is_available():
            stimuli = stimuli.cuda()
        with torch.no_grad():
            #average across the same category
            feats = model(stimuli).mean(dim=0).cpu().numpy()
        condition_features[c_name] = feats
    return condition_features

def plot_tensor_example(conditionsPath, resolution,paddingval,cropval,padding_mode='constant'):
    #takes model and loads the features for that image, needs path to of files in directory
    conditions = listdir(conditionsPath)
    x = randrange(len(conditions))
    c_name = conditions[x].split('/')[-1]
    stimuli = listdir(conditions[x])
    s = stimuli[0]
    #resize according to resolution and square the image
    tensor_image = image_to_tensor(s, resolution=resolution,cropval = cropval, paddingval = paddingval,padding_mode = padding_mode)
    # #convert image back to Height,Width,Channels
    img = np.transpose(tensor_image.numpy(), (1,2,0))
    # #show the image
    print('Plotting Image ' + stimuli[0].split('/')[-1])
    plt.imshow(img)
    plt.show()
    # return condition_features

def listdir(dir, path=True):
    files = os.listdir(dir)
    files = [f for f in files if f != '.DS_Store']
    files = [f for f in files if f != '.ipynb_checkpoints']
    files = sorted(files)
    if path:
        files = [os.path.join(dir, f) for f in files]
    return files

def image_to_tensor(image, resolution=None, cropval = None,paddingval=None,padding_mode = 'constant', do_imagenet_norm=True, do_padding = True):
    if isinstance(image, str):
        image = Image.open(image).convert('RGB')
    if image.width != image.height:     # if not square image, crop the long side's edges to make it square
        r = min(image.width, image.height)
        image = tr.center_crop(image, (r, r))
    if do_padding:     # if not square image, crop the long side's edges to make it square
        image = tr.pad(image, padding=paddingval, padding_mode=padding_mode, fill=0)
        # image = tr.pad(input=data, mode='reflect', value=0)
    if resolution is not None:#f size is an int, smaller edge of the image will be matched to this number
        image = tr.resize(image, resolution)
    if cropval is not None:     # if not square image, crop the long side's edges to make it square
        image = tr.center_crop(image, (cropval, cropval))
    image = tr.to_tensor(image)
    if do_imagenet_norm:
        image = imagenet_norm(image)
    return image

def imagenet_norm(image):
    dims = len(image.shape)
    if dims < 4:
        image = [image]
    image = [tr.normalize(img, mean=imagenet_mean, std=imagenet_std) for img in image]
    image = torch.stack(image, dim=0)
    if dims < 4:
        image = image.squeeze(0)
    return image