import sys
from usando_qtdesigner148.design import *
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog
from PyQt5.QtGui import QPixmap

class Redimensionamento(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        super().setupUi(self)  # para que ele execute a instancia dessa classe
        self.btnEscolheArq.clicked.connect(self.abrir_imagem)
        self.btnRedim.clicked.connect(self.redimensionar)
        self.btnSalvar.clicked.connect(self.salvar)

    def abrir_imagem(self):
        image, _ = QFileDialog.getOpenFileName(
            self.centralwidget,
            'Abrir imagem'
            '/home/adriana/Downloads/',
            # options=QFileDialog.DontUseNativeDialog  #se nao funcionar a janela, descomentar essa parte

        )
        self.inputArquivo.setText(image)
        self.original_img = QPixmap(image)
        self.labelImg.setPixmap(self.original_img)
        self.inputLargura.setText(str(self.original_img.width()))
        self.inputAltura.setText(str(self.original_img.height()))

    def redimensionar(self):
        largura = int(self.inputLargura.text())
        self.nova_imagem = self.original_img.scaledToWidth(largura)  # calcula a altura automaticamente
        self.labelImg.setPixmap(self.nova_imagem)
        self.inputLargura.setText(str(self.nova_imagem.width()))
        self.inputAltura.setText(str(self.nova_imagem.height()))

    def salvar(self):
        image, _ = QFileDialog.getSaveFileName(
            self.centralwidget,
            'Salvar imagem'
            '/home/adriana/',
        )
        self.nova_imagem.save(image)

if __name__ == '__main__':
    qt = QApplication(sys.argv)
    novo = Redimensionamento()
    novo.show()
    qt.exec_()

5 - interface grafica/usando_qtdesigner148/novo.py


from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from time import perf_counter
from typing import Any, Callable, Mapping, Optional

import pytest
from packaging.version import Version

from check_shapes import Shape
from check_shapes import check_shape as cs
from check_shapes import check_shapes, disable_check_shapes, inherit_check_shapes
from check_shapes.config import ShapeCheckingState
from check_shapes.exceptions import ShapeMismatchError

from ..utils import assert_has_shape

try:
    import numpy as np
    import tensorflow as tf

    requires_tf = lambda f: f
except ImportError:
    from unittest.mock import MagicMock

    np = MagicMock()
    tf = MagicMock()

    requires_tf = pytest.mark.skip("TensorFlow not installed.")

@requires_tf
@pytest.mark.parametrize(
    "shaped,expected_shape",
    [
        (tf.Variable(np.zeros(())), ()),
        (tf.Variable(np.zeros((2, 4))), (2, 4)),
        # pylint: disable=unexpected-keyword-arg
        (tf.Variable(np.zeros((2, 4)), shape=[2, None]), (2, None)),
        (tf.Variable(np.zeros((2, 4)), shape=tf.TensorShape(None)), None),
    ],
)
def test_get_shape(shaped: Any, expected_shape: Shape) -> None:
    assert_has_shape(shaped, expected_shape)

@requires_tf
@pytest.mark.parametrize(
    "state,eager_expected,compiled_expected",
    [
        (ShapeCheckingState.ENABLED, True, True),
        (ShapeCheckingState.EAGER_MODE_ONLY, True, False),
        (ShapeCheckingState.DISABLED, False, False),
    ],
)
def test_shape_checking_state__bool(
    state: ShapeCheckingState, eager_expected: bool, compiled_expected: bool
) -> None:
    enabled = None

    def run() -> None:
        nonlocal enabled
        enabled = bool(state)

    run()
    assert eager_expected == enabled

    tf.function(run)()  # pylint: disable=no-member
    assert compiled_expected == enabled

@requires_tf
def test_check_shapes() -> None:
    N_FEATURES = 10
    N_TRAINING_ROWS = 1_000
    N_TEST_ROWS = 100

    N_ITERATIONS = 1_000
    LEARNING_RATE = 1e-2

    class Model(ABC):
        @abstractmethod
        @check_shapes(
            "training_features: [n_rows, n_features]",
            "training_targets: [n_rows, 1]",
        )
        def train(self, training_features: tf.Tensor, training_targets: tf.Tensor) -> None:
            ...

        @abstractmethod
        @check_shapes(
            "test_features: [n_rows, n_features]",
            "return: [n_rows, 1]",
        )
        def predict(self, test_features: tf.Tensor) -> tf.Tensor:
            ...

    class LinearModel(Model):
        def __init__(self) -> None:
            self._weights: Optional[tf.Tensor] = None  # [n_features]

        @check_shapes(
            "weights: [n_features]",
        )
        def set_weights(self, weights: tf.Tensor) -> None:
            self._weights = weights

        @inherit_check_shapes
        def train(self, training_features: tf.Tensor, training_targets: tf.Tensor) -> None:
            # We intentionally split this into a few more functions than might technically be
            # needed, so that we have something to annotate with type checks:

            @check_shapes(
                "weights: [n_features]",
                "return: []",
            )
            def loss(weights: tf.Tensor) -> tf.Tensor:
                pred = cs(self._predict(weights, training_features), "[n_rows, 1]")
                err = cs(pred - training_targets, "[n_rows, 1]")
                return tf.reduce_mean(err ** 2)

            @tf.function  # type: ignore
            @check_shapes(
                "weights: [n_features]",
                "return: [n_features]",
            )
            def step(weights: tf.Tensor) -> tf.Tensor:
                with tf.GradientTape() as g:
                    g.watch(weights)
                    l = cs(loss(weights), "[]")
                loss_grads = cs(g.gradient(l, weights), "[n_features]")
                return weights - LEARNING_RATE * loss_grads

            n_features = training_features.shape[-1]
            weights = tf.Variable(tf.zeros((n_features,)))
            for _ in range(N_ITERATIONS):
                weights.assign(step(weights))

            self._weights = tf.constant(weights)

        @inherit_check_shapes
        def predict(self, test_features: tf.Tensor) -> tf.Tensor:
            assert self._weights is not None
            return self._predict(self._weights, test_features)

        @staticmethod
        @check_shapes(
            "weights: [n_features]",
            "test_features: [n_rows, n_features]",
            "return: [n_rows, 1]",
        )
        def _predict(weights: tf.Tensor, test_features: tf.Tensor) -> tf.Tensor:
            return test_features @ weights[:, None]

    @dataclass
    class TestData:
        training_features: tf.Tensor
        training_targets: tf.Tensor
        test_features: tf.Tensor
        test_targets: tf.Tensor

        @check_shapes(
            "self.training_features: [n_training_rows, n_features]",
            "self.training_targets: [n_training_rows, 1]",
            "self.test_features: [n_test_rows, n_features]",
            "self.test_targets: [n_test_rows, 1]",
        )
        def __post_init__(self) -> None:
            pass

    def create_data() -> TestData:
        tf.random.set_seed(42)
        model = LinearModel()
        model.set_weights(tf.range(N_FEATURES, dtype=tf.float32))
        training_features = tf.random.uniform([N_TRAINING_ROWS, N_FEATURES], 0.0, 1.0)
        training_targets = model.predict(training_features) + tf.random.normal(
            [N_TRAINING_ROWS, 1], 0.0, 1.0
        )
        test_features = tf.random.uniform([N_TEST_ROWS, N_FEATURES], 0.0, 1.0)
        test_targets = model.predict(test_features)
        return TestData(training_features, training_targets, test_features, test_targets)

    def evaluate(model: Model, data: TestData) -> Mapping[str, float]:
        test_predictions = model.predict(data.test_features)
        err = data.test_targets - test_predictions
        result = {}
        result["rmse"] = tf.sqrt(tf.reduce_mean(err ** 2)).numpy()
        return result

    def main() -> None:
        before = perf_counter()
        data = create_data()
        model = LinearModel()
        model.train(data.training_features, data.training_targets)
        metrics = dict(evaluate(model, data))
        after = perf_counter()
        metrics["time (s)"] = after - before
        for key, value in metrics.items():
            print(key, value)

    main()

@requires_tf
def test_check_shapes__keras() -> None:
    # pylint: disable=arguments-differ,abstract-method,no-value-for-parameter,unexpected-keyword-arg

    @check_shapes(
        "x: [*]",
        "return: [*]",
    )
    def f(x: tf.Tensor) -> tf.Tensor:
        return x + 3

    class SuperLayer(tf.keras.layers.Layer):  # type: ignore[misc]
        def __init__(self) -> None:
            super().__init__()
            self._b = tf.Variable(0.0)

        @check_shapes(
            "x: [batch, input_dim]",
            "y: [batch, 1]",
            "return: [batch, input_dim]",
            tf_decorator=True,
        )
        def call(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:
            return f(x) + y + self._b

    class SubLayer(SuperLayer):
        @inherit_check_shapes
        def call(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:
            return x - y + self._b

    class MyModel(tf.keras.Model):  # type: ignore[misc]
        def __init__(self, join: SuperLayer) -> None:
            super().__init__()
            self._join = join

        @check_shapes(
            "xy: [batch, input_dim_plus_one]",
            "return: [batch, input_dim]",
            tf_decorator=True,
        )
        def call(self, xy: tf.Tensor) -> tf.Tensor:
            x = cs(xy[:, :-1], "[batch, input_dim]")
            y = cs(xy[:, -1:], "[batch, 1]")
            return self._join(x, y)

    x = tf.ones((32, 3))
    y = tf.zeros((32, 1))
    xy = tf.concat([x, y], axis=1)
    y_bad = tf.zeros((32, 2))
    targets = tf.ones((32, 3))

    def test_layer(join: SuperLayer) -> None:
        join(x, y)

        with pytest.raises(ShapeMismatchError):
            join(x, y_bad)

        model = MyModel(join)
        model.compile(
            optimizer=tf.keras.optimizers.SGD(learning_rate=0.25),
            loss="mean_squared_error",
        )
        model.fit(x=xy, y=targets)

    test_layer(SuperLayer())
    test_layer(SubLayer())

_Err = Callable[[tf.Tensor, tf.Tensor], tf.Tensor]
_Loss = Callable[[], tf.Tensor]

_ID_WRAPPER = lambda x: x
_TF_FUNCTION = tf.function
_SHAPED_TF_FUNCTION_ERR = tf.function(
    input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.float64),
        tf.TensorSpec(shape=[], dtype=tf.float64),
    ]
)

_SHAPED_TF_FUNCTION_LOSS = tf.function(input_signature=[])
_UNSHAPED_TF_FUNCTION_ERR = tf.function(
    input_signature=[
        tf.TensorSpec(shape=None, dtype=tf.float64),
        tf.TensorSpec(shape=None, dtype=tf.float64),
    ]
)
_UNSHAPED_TF_FUNCTION_LOSS = tf.function(input_signature=[])
_RELAXED_TF_FUNCTION = tf.function(experimental_relax_shapes=True)

_NONE_SHAPE = None
_TARGET_SHAPE = tf.TensorShape([])
_V_SHAPE = tf.TensorShape([50])
_UNKNOWN_SHAPE = tf.TensorShape(None)

@requires_tf
@pytest.mark.parametrize(
    "err_wrapper,loss_wrapper",
    [
        (_ID_WRAPPER, _ID_WRAPPER),
        (_TF_FUNCTION, _TF_FUNCTION),
        (_SHAPED_TF_FUNCTION_ERR, _SHAPED_TF_FUNCTION_LOSS),
        (_UNSHAPED_TF_FUNCTION_ERR, _UNSHAPED_TF_FUNCTION_LOSS),
        (_RELAXED_TF_FUNCTION, _RELAXED_TF_FUNCTION),
    ],
)
@pytest.mark.parametrize("target_shape", [_NONE_SHAPE, _TARGET_SHAPE, _UNKNOWN_SHAPE])
@pytest.mark.parametrize("v_shape", [_NONE_SHAPE, _V_SHAPE, _UNKNOWN_SHAPE])
def test_check_shapes_compilation(
    err_wrapper: Callable[[_Err], _Err],
    loss_wrapper: Callable[[_Loss], _Loss],
    target_shape: Optional[tf.TensorShape],
    v_shape: Optional[tf.TensorShape],
) -> None:
    # Yeah, this test seems to be pushing the limits of TensorFlow compilation (which is probably
    # good), but a bunch of this is fragile.
    tf_version = Version(tf.__version__)

    if (target_shape is _UNKNOWN_SHAPE) or (v_shape is _UNKNOWN_SHAPE):
        if (err_wrapper is _TF_FUNCTION) or (err_wrapper is _RELAXED_TF_FUNCTION):
            if Version("2.7.0") <= tf_version < Version("2.8.0"):
                pytest.skip("TensorFlow 2.7.* segfaults when trying to compile this.")
            if Version("2.8.0") <= tf_version < Version("2.9.0"):
                pytest.skip("TensorFlow 2.8.* is missing a TraceType(?) when trying compile this.")

    # See: https://github.com/tensorflow/tensorflow/issues/56414
    if err_wrapper is _RELAXED_TF_FUNCTION:
        if Version("2.9.0") <= tf_version < Version("2.11.0"):
            err_wrapper = _TF_FUNCTION

    if Version(tf.__version__) < Version("2.5.0"):
        # TensorFlow < 2.5.0 doesn't like the optional `z` argument:

        class SqErr:
            @check_shapes(
                "x: [broadcast n...]",
                "y: [broadcast n...]",
                "return: [n...]",
            )
            def __call__(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:
                return (x - y) ** 2

    else:

        class SqErr:  # type: ignore[no-redef]
            @check_shapes(
                "x: [broadcast n...]",
                "y: [broadcast n...]",
                "z: [broadcast n...]",
                "return: [n...]",
            )
            def __call__(
                self, x: tf.Tensor, y: tf.Tensor, z: Optional[tf.Tensor] = None
            ) -> tf.Tensor:
                # z only declared to test the case of `None` arguments.
                return (x - y) ** 2

    sq_err = err_wrapper(SqErr())

    dtype = np.float64
    target = tf.Variable(0.5, dtype=dtype, shape=target_shape)
    v = tf.Variable(np.linspace(0.0, 1.0), dtype=dtype, shape=v_shape)

    @loss_wrapper
    @check_shapes(
        "return: [1]",
    )
    def loss() -> tf.Tensor:
        # keepdims is just to add an extra dimension to make the check more interesting.
        return tf.reduce_sum(sq_err(v, target), keepdims=True)

    optimiser = tf.keras.optimizers.SGD(learning_rate=0.25)
    for _ in range(10):
        optimiser.minimize(loss, var_list=[v])

    np.testing.assert_allclose(target, v.numpy(), atol=0.01)

@requires_tf
@pytest.mark.parametrize("func_wrapper", [lambda x: x, tf.function], ids=["none", "tf.function"])
def test_check_shapes__disable__speed(func_wrapper: Callable[[Any], Any]) -> None:
    if func_wrapper is tf.function:
        pytest.skip(
            "This test is super flaky with tf.function, because the overhead of compiling"
            " seems to dominate any difference caused by check_shapes. However we probably"
            " do want some kind of test of the speed with tf.function, so we keep this"
            " skipped test around to remind us."
        )

    x = tf.zeros((3, 4, 5))
    y = tf.ones((3, 4, 5))

    def time_no_checks() -> float:
        before = perf_counter()

        def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:
            return a + b

        f = func_wrapper(f)
        for _ in range(10):
            f(x, y)

        after = perf_counter()
        return after - before

    def time_disabled_checks() -> float:
        with disable_check_shapes():
            before = perf_counter()

            @check_shapes(
                "a: [d...]",
                "b: [d...]",
                "return: [d...]",
            )
            def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:
                return a + b

            f = func_wrapper(f)
            for _ in range(10):
                f(x, y)

            after = perf_counter()
            return after - before

    def time_with_checks() -> float:
        before = perf_counter()

        @check_shapes(
            "a: [d...]",
            "b: [d...]",
            "return: [d...]",
        )
        def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:
            return a + b

        f = func_wrapper(f)
        for _ in range(10):
            f(x, y)

        after = perf_counter()
        return after - before

    time_no_checks()  # Warm-up.
    t_no_checks = time_no_checks()

    time_disabled_checks()  # Warm-up.
    t_disabled_checks = time_disabled_checks()

    time_with_checks()  # Warm-up.
    t_with_checks = time_with_checks()

    assert t_no_checks < t_with_checks
    assert t_disabled_checks < t_with_checks

@requires_tf
def test_issue_1864() -> None:
    @tf.function
    @check_shapes(
        "x: [*]",
        "return: [*]",
    )
    def f(x: tf.Tensor) -> tf.Tensor:
        for _ in tf.range(3):
            x = x + 1.0
        return x

    x = tf.constant(7.0)
    f(x)

@requires_tf
def test_issue_1936() -> None:
    @tf.function
    @check_shapes(
        "x: [*]",
        "return: [*]",
    )
    def f_if(x: tf.Tensor) -> tf.Tensor:
        if tf.size(x) == 0:
            return x
        else:
            return x + x

    @tf.function
    @check_shapes(
        "x: [*]",
        "return: [*]",
    )
    def f_tf_cond(x: tf.Tensor) -> tf.Tensor:
        return tf.cond(tf.size(x) == 0, lambda: x, lambda: x + x)

    x = tf.constant(7.0)
    f_tf_cond(x)
    f_if(x)

@requires_tf
@pytest.mark.parametrize("model_type", ["SuperModel", "SubModel"])
def test_tf_saved_model(model_type: str, tmp_path: Path) -> None:
    class SuperModel:
        @check_shapes(
            "x: [any...]",
            "return: [any...]",
        )
        def f(self, x: tf.Tensor) -> tf.Tensor:
            return x

    class SubModel(SuperModel):
        @inherit_check_shapes
        def f(self, x: tf.Tensor) -> tf.Tensor:
            return x + 1

    x = np.arange(5)
    model = {
        "SuperModel": SuperModel,
        "SubModel": SubModel,
    }[model_type]()
    out_module = tf.Module()
    out_module.f = tf.function(
        model.f,
        input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float64)],
    )
    tf.saved_model.save(out_module, str(tmp_path))

    in_module = tf.saved_model.load(str(tmp_path))

    np.testing.assert_allclose(
        model.f(x),
        in_module.f(x),
    )


import numpy as np
import pandas as pd
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
import string

## getting training data

df = pd.read_csv("0000000000002747_training_twitter_x_y_train.csv")
y = list(df["airline_sentiment"])
text = list(df["text"])

## training documents
documents = []
for i in range(len(y)):
    documents.append((text[i].split(" "),y[i]))
documents[0:5] ## in the form of tuple with 1st element as a list of words and second as the sentiment, ie positive, negative or neutral

## processing the words:

## making a list of stopwords and punctuations to be removed from the tweets

stop = stopwords.words("english")
punctuations = list(string.punctuation)
stop = stop + punctuations ## to remove punctuations

## using nltk library

from nltk.corpus import wordnet

## fucntion to get pos_tag of a word
def get_simple_pos(tag):
    if tag.startswith('J'):
        return wordnet.ADJ
    elif tag.startswith('V'):
        return wordnet.VERB
    elif tag.startswith('N'):
        return wordnet.NOUN
    elif tag.startswith('R'):
        return wordnet.ADV
    else:
        return wordnet.NOUN

from nltk import pos_tag
from nltk.stem import WordNetLemmatizer
lt = WordNetLemmatizer()

## fucntion to clean the words in the text
## removing stop words and punctuations
## performing lemmatization to get better insight on the meaning of the words

def clean_review(words):
    output_words = []
    for w in words:
        if w.lower() not in stop:
            try:
                pos = pos_tag([w])
                clean_word = lt.lemmatize(w,pos = get_simple_pos(pos[0][1]))
                output_words.append(clean_word.lower())
            except:
                continue
    return output_words

documents = [(clean_review(i),category) for i,category in documents]

y_train = [category for words,category in documents]
x_train = [" ".join(words) for words, categories in documents]

## using tfidf Vectorizer to remove words which do not hold much importance during classification

from sklearn.feature_extraction.text import TfidfVectorizer
token_vec = TfidfVectorizer(max_features = 3000, ngram_range = (1,3))
x_train_t = token_vec.fit_transform(x_train) ## we can use the sparse matrix directyly as training and testing data in our sklearn classifiers

## forming x_test

df = pd.read_csv("0000000000002747_test_twitter_x_test.csv")
text = list(df["text"])
x_test = []
for i in range(len(text)):
    x_test.append(text[i])
x_test

x_test_t = token_vec.transform(x_test) ## we can use the sparse matrix directyly as training and testing data in our sklearn classifiers

## both training and testing data now ready
from sklearn.model_selection import train_test_split
x_train, x_val, y_train, y_val = train_test_split(x_train_t, y_train)
## classification using MultiNomial Naive Bayes
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB()
clf.fit(x_train, y_train)
print(clf.score(x_val, y_val)) ## checking the score on the validation data

## saving the predictions in a csv file
y_pred = clf.predict(x_test_t)
predictions = np.array(y_pred)
pd.DataFrame(predictions).to_csv("finall.csv") ## saving file


from turtle import Turtle

ALIGNMENT = "center"
FONT = ("Arial", 20, "normal")

class ScoreBoard(Turtle):

    def __init__(self, place):
        super().__init__()
        self.penup()
        self.color("white")
        self.shape("square")
        self.shapesize(stretch_wid=0.5, stretch_len=0.5)
        self.hideturtle()
        self.score = 0
        self.goto(place)
        self.show_score()

    def increase_score(self):
        self.score += 1
        self.clear()
        self.show_score()

    def show_score(self):
        self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)


import asyncio
import logging
import threading
from time import sleep
from typing import Optional

from aleph_message.models import ItemHash
from schedule import Job, Scheduler

from aleph.vm.conf import settings
from aleph.vm.orchestrator.models import VmExecution

from .snapshots import CompressedDiskVolumeSnapshot

logger = logging.getLogger(__name__)

def wrap_async_snapshot(execution):
    asyncio.run(do_execution_snapshot(execution))

def run_threaded_snapshot(execution):
    job_thread = threading.Thread(target=wrap_async_snapshot, args=(execution,))
    job_thread.start()

async def do_execution_snapshot(execution: VmExecution) -> CompressedDiskVolumeSnapshot:
    try:
        logger.debug(f"Starting new snapshot for VM {execution.vm_hash}")
        assert execution.vm, "VM execution not set"

        snapshot = await execution.vm.create_snapshot()
        await snapshot.upload()

        logger.debug(f"New snapshots for VM {execution.vm_hash} created in {snapshot.path}")
        return snapshot
    except ValueError:
        msg = "Something failed taking an snapshot"
        raise ValueError(msg)

def infinite_run_scheduler_jobs(scheduler: Scheduler) -> None:
    while True:
        scheduler.run_pending()
        sleep(1)

class SnapshotExecution:
    vm_hash: ItemHash
    execution: VmExecution
    frequency: int
    _scheduler: Scheduler
    _job: Job

    def __init__(
        self,
        scheduler: Scheduler,
        vm_hash: ItemHash,
        execution: VmExecution,
        frequency: int,
    ):
        self.vm_hash = vm_hash
        self.execution = execution
        self.frequency = frequency
        self._scheduler = scheduler

    async def start(self) -> None:
        logger.debug(f"Starting snapshots for VM {self.vm_hash} every {self.frequency} minutes")
        job = self._scheduler.every(self.frequency).minutes.do(run_threaded_snapshot, self.execution)
        self._job = job

    async def stop(self) -> None:
        logger.debug(f"Stopping snapshots for VM {self.vm_hash}")
        self._scheduler.cancel_job(self._job)

class SnapshotManager:
    """
    Manage VM snapshots.
    """

    executions: dict[ItemHash, SnapshotExecution]
    _scheduler: Scheduler

    def __init__(self):
        self.executions = {}
        self._scheduler = Scheduler()

    def run_snapshots(self) -> None:
        job_thread = threading.Thread(
            target=infinite_run_scheduler_jobs,
            args=[self._scheduler],
            daemon=True,
            name="SnapshotManager",
        )
        job_thread.start()

    async def start_for(self, execution: VmExecution, frequency: Optional[int] = None) -> None:
        if not execution.is_instance:
            msg = "Snapshots are not implemented for programs."
            raise NotImplementedError(msg)

        default_frequency = frequency or settings.SNAPSHOT_FREQUENCY

        vm_hash = execution.vm_hash
        snapshot_execution = SnapshotExecution(
            scheduler=self._scheduler,
            vm_hash=vm_hash,
            execution=execution,
            frequency=default_frequency,
        )
        self.executions[vm_hash] = snapshot_execution
        await snapshot_execution.start()

    async def stop_for(self, vm_hash: ItemHash) -> None:
        try:
            snapshot_execution = self.executions.pop(vm_hash)
        except KeyError:
            logger.warning("Could not find snapshot task for instance %s", vm_hash)
            return

        await snapshot_execution.stop()

    async def stop_all(self) -> None:
        await asyncio.gather(*(self.stop_for(vm_hash) for vm_hash, execution in self.executions))


import json, time, datetime

class Colors:
    """Contains general stdout colors."""
    cyan = '\033[96m'
    red = '\033[91m'
    green = '\033[92m'
    end = '\033[0m'

class IsoBankManager():
    def __init__(self, db_path:str, auth_db:str):
        self.db_path = db_path
        self.auth_db = auth_db
        with open(db_path, 'r') as f:
            global accounts
            accounts = json.load(f)
        with open(auth_db, 'r') as f:
            global auth
            auth = json.load(f)
        print(f"[Framework/Loader] {Colors.green}IsoBank Account Manager initialized.{Colors.end}")

    def save(self):
        with open(self.db_path, 'w+') as f: json.dump(accounts, indent=4)

    def deposit(self, account_id:int, discord_id:int, amount:int):
        if discord_id not in auth[str(account_id)]["discord_ids"]: return "Failed to authorize user"
        accounts["deposited"] += amount
        save()
        return f"Deposited {amount} coins to #{account_id} IsoBank account"

    def withdraw(self, account_id:int, discord_id:int, amount:int):
        if discord_id not in auth[str(account_id)]["discord_ids"]: return "Failed to authorize user"
        accounts["deposited"] -= amount
        save()
        return f"Withdrawn {amount} coins from #{account_id} IsoBank account"


"""Helpers for the embodyserial interface."""

import logging
import struct
import time
from datetime import datetime
from datetime import timezone
from typing import Optional

from embodycodec import attributes
from embodycodec import codec
from embodycodec import types

from embodyserial.embodyserial import EmbodySender
from embodyserial.exceptions import MissingResponseError
from embodyserial.exceptions import NackError

class EmbodySendHelper:
    """Facade to make send/receive more protocol agnostic with simple get/set methods."""

    def __init__(self, sender: EmbodySender, timeout: Optional[int] = 30) -> None:
        self.__sender = sender
        self.__send_timeout = timeout

    def get_current_time(self) -> datetime:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.CurrentTimeAttribute.attribute_id
        )
        return datetime.fromtimestamp(response_attribute.value / 1000, tz=timezone.utc)

    def get_serial_no(self) -> str:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.SerialNoAttribute.attribute_id
        )
        response = response_attribute.formatted_value()
        assert response
        return response

    def get_vendor(self) -> str:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.VendorAttribute.attribute_id
        )
        response = response_attribute.formatted_value()
        assert response
        return response

    def get_model(self) -> str:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.ModelAttribute.attribute_id
        )
        response = response_attribute.formatted_value()
        assert response
        return response

    def get_bluetooth_mac(self) -> str:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.BluetoothMacAttribute.attribute_id
        )
        response = response_attribute.formatted_value()
        assert response
        return response

    def get_battery_level(self) -> int:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.BatteryLevelAttribute.attribute_id
        )
        return response_attribute.value

    def get_heart_rate(self) -> int:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.HeartrateAttribute.attribute_id
        )
        return response_attribute.value

    def get_charge_state(self) -> bool:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.ChargeStateAttribute.attribute_id
        )
        return response_attribute.value

    def get_temperature(self) -> float:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.TemperatureAttribute.attribute_id
        )
        assert isinstance(response_attribute, attributes.TemperatureAttribute)
        return response_attribute.temp_celsius()

    def get_firmware_version(self) -> str:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.FirmwareVersionAttribute.attribute_id
        )
        response = response_attribute.formatted_value()
        assert response
        return response

    def get_on_body_state(self) -> bool:
        response_attribute = self.__do_send_get_attribute_request(
            attributes.BeltOnBodyStateAttribute.attribute_id
        )
        return response_attribute.value

    def get_files(self) -> list[tuple[str, int]]:
        """Get a list of tuples with file name and file size."""
        response = self.__sender.send(msg=codec.ListFiles(), timeout=120)
        if not response:
            raise MissingResponseError
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        assert isinstance(response, codec.ListFilesResponse)

        files: list[tuple[str, int]] = list()
        if len(response.files) == 0:
            return files
        else:
            for file in response.files:
                files.append((str(file.file_name), file.file_size))
            return files

    def delete_file(self, file_name: str) -> bool:
        response = self.__sender.send(
            msg=codec.DeleteFile(types.File(file_name)), timeout=self.__send_timeout
        )
        if not response:
            raise MissingResponseError()
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        assert isinstance(response, codec.DeleteFileResponse)
        return True

    def delete_file_with_retries(
        self, file_name: str, retries=3, timeout_seconds_per_retry=0.5
    ) -> bool:
        for retry in range(1, retries + 1):
            try:
                if self.delete_file(file_name):
                    logging.info(f"Deleted file on device: {file_name}")
                    return True
                logging.warn(f"Delete failed for {file_name} (attempt: {retry})")
                time.sleep(timeout_seconds_per_retry)
                continue
            except Exception as e:
                logging.warn(f"Delete failed for {file_name} (attempt: {retry}): {e}")
                time.sleep(timeout_seconds_per_retry)
                continue
        return False

    def set_current_timestamp(self) -> bool:
        return self.set_timestamp(datetime.now(timezone.utc))

    def set_timestamp(self, time: datetime) -> bool:
        attr = attributes.CurrentTimeAttribute(int(time.timestamp() * 1000))
        return self.__do_send_set_attribute_request(attr)

    def set_trace_level(self, level: int) -> bool:
        attr = attributes.TraceLevelAttribute(level)
        return self.__do_send_set_attribute_request(attr)

    def reformat_disk(self) -> bool:
        response = self.__sender.send(
            msg=codec.ReformatDisk(), timeout=self.__send_timeout
        )
        if not response:
            raise MissingResponseError()
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        assert isinstance(response, codec.ReformatDiskResponse)
        return True

    def reset_device(self) -> bool:
        self.__sender.send_async(
            msg=codec.ExecuteCommand(
                command_id=codec.ExecuteCommand.RESET_DEVICE, value=b""
            )
        )
        return True

    def reboot_device(self) -> bool:
        self.__sender.send_async(
            msg=codec.ExecuteCommand(
                command_id=codec.ExecuteCommand.REBOOT_DEVICE, value=b""
            )
        )
        return True

    def click_button(self, click_count: int, click_duration_ms: int) -> bool:
        self.__sender.send_async(
            msg=codec.ExecuteCommand(
                command_id=types.ExecuteCommandType.PRESS_BUTTON.value,
                value=struct.pack(">BH", click_count, click_duration_ms),
            )
        )
        return True

    def delete_all_files(self) -> bool:
        response = self.__sender.send(
            msg=codec.DeleteAllFiles(), timeout=self.__send_timeout
        )
        if not response:
            raise MissingResponseError()
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        assert isinstance(response, codec.DeleteAllFilesResponse)
        return True

    def __do_send_get_attribute_request(
        self, attribute_id: int
    ) -> attributes.Attribute:
        response = self.__sender.send(
            msg=codec.GetAttribute(attribute_id), timeout=self.__send_timeout
        )
        if not response:
            raise MissingResponseError()
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        assert isinstance(response, codec.GetAttributeResponse)
        return response.value

    def __do_send_set_attribute_request(self, attr: attributes.Attribute) -> bool:
        response = self.__sender.send(
            msg=codec.SetAttribute(attribute_id=attr.attribute_id, value=attr),
            timeout=self.__send_timeout,
        )
        if not response:
            raise MissingResponseError()
        if isinstance(response, codec.NackResponse):
            raise NackError(response)
        return isinstance(response, codec.SetAttributeResponse)


import json
from tinydb import TinyDB

class Joueur:
    """
    Classe servant a créer une instance de joueur, et regroupant divers methodes pour la recuperation de data.
    type d'arguments : arguments nommés, str, int
    """

    def __init__(self, nom="", prenom="", date_de_naissance="", sexe="", classement=0):
        self.nom = nom
        self.prenom = prenom
        self.date_de_naissance = date_de_naissance
        self.sexe = sexe
        self.classement = classement

    def serialiser_instance_joueur(self):
        """
        Methode servant à serialiser une instance de joueur.
        type d'arguments : str
        """
        serialized_player = {
            'nom': self.nom,
            'prenom': self.prenom,
            'date de naissance': self.date_de_naissance,
            'sexe': self.sexe,
            'classement': self.classement
        }
        db = TinyDB('data/joueurs.json')
        table_joueurs = db.table('Joueur')
        table_joueurs.insert(serialized_player)

    def joueurs_alpha():
        """
        Methode servant a trier les joueurs par ordre alphabetique.
        return : tulpe nom prenom des joueurs
        rtype : tulpe
        """
        with open('data/joueurs.json', 'r') as joueurs_data:
            data_dict = json.load(joueurs_data)
            nom_list = []
            nom = ''
            prenom = ''
            for joueur in data_dict.values():
                for num_joueur in joueur.values():
                    for cle, valeur in num_joueur.items():
                        if cle == 'nom':
                            nom = valeur
                        if cle == 'prenom':
                            prenom = valeur
                    nom_prenom = nom + ' ' + prenom + '\n'
                    nom_list.append(nom_prenom)
                    nom_list.sort()
            if len(nom_list) < 2:
                return 0
            if len(nom_list) >= 2:
                del nom_list[0]
                return nom_list

    def joueurs_classement():
        """
        Methode servant a trier les joueurs par ordre de classement.
        return : tulpe classement nom prenom des joueurs
        rtype : tulpe
        """
        with open('data/joueurs.json', 'r') as joueurs_data:
            data_dict = json.load(joueurs_data)
            classement_nom_list = []
            nom = ''
            prenom = ''
            classement = ''
            for joueur in data_dict.values():
                for num_joueur in joueur.values():
                    for cle, valeur in num_joueur.items():
                        if cle == 'nom':
                            nom = valeur
                        if cle == 'prenom':
                            prenom = valeur
                        if cle == 'classement':
                            classement = 'Classement : ' + str(valeur)
                    nom_prenom_classement = classement + '\n    ' + nom + ' ' + prenom + '\n'
                    classement_nom_list.append(nom_prenom_classement)
                    classement_nom_list.sort()
            if len(classement_nom_list) < 2:
                return 0
            if len(classement_nom_list) >= 2:
                del classement_nom_list[0]
                return classement_nom_list

    def joueurs_tournoi():
        """
        Methode servant a regroupant les joueurs.
        return : tulpe indice nom prenom classement des joueurs
        rtype : tulpe
        """
        with open('data/joueurs.json', 'r') as joueurs_data:
            data_dict = json.load(joueurs_data)
            classement_nom_list = []
            indice_joueur = 0
            nom = ''
            prenom = ''
            classement = ''
            for joueur in data_dict.values():
                for num_joueur in joueur.values():
                    for cle, valeur in num_joueur.items():
                        if cle == 'nom':
                            nom = valeur
                        if cle == 'prenom':
                            prenom = valeur
                        if cle == 'classement':
                            classement = 'Classement : ' + str(valeur)
                    indice_nom_prenom_classement = 'Indice joueur : ' + str(indice_joueur) + '\n   ' + nom + \
                        ' ' + prenom + '\n   ' + classement + '\n'
                    classement_nom_list.append(indice_nom_prenom_classement)
                    indice_joueur += 1
            if len(classement_nom_list) < 9:
                return 0
            if len(classement_nom_list) >= 9:
                del classement_nom_list[0]
                return classement_nom_list

    def get_joueurs_tournoi(liste_indice_selection, liste_nom_joueurs):
        """
        Methode servant récuperer des joueurs selectionnés par leur indice.
        type d'arguments : int, tulpe
        return : tulpe nom prenom des joueurs
        rtype : tulpe
        """
        liste_nom_joueurs_selection = []
        liste_nom_joueurs_new = []
        for arg in liste_nom_joueurs:
            arg = str(arg).replace("\n", "")
            liste_nom_joueurs_new.append(arg)
        for indice in liste_indice_selection:
            liste_nom_joueurs_selection.append(liste_nom_joueurs_new[indice-1])
        return liste_nom_joueurs_selection

    def get_classement_joueur(joueur_selecion):
        """
        Methode servant a récuperer le classement d'un joueur.
        type d'argument : str
        return : classement
        rtype : int
        """
        with open('data/joueurs.json', 'r') as joueurs_data:
            data_dict = json.load(joueurs_data)
            for joueurs in data_dict.values():
                for num_joueurs in joueurs.values():
                    for cle, valeur in num_joueurs.items():
                        if cle == "nom":
                            nom = valeur
                        if cle == "prenom":
                            prenom = valeur
                    nom_prenom = nom + " " + prenom
                    if nom_prenom == joueur_selecion:
                        for cle, valeur in num_joueurs.items():
                            if cle == "classement":
                                joueur_selecion = valeur
                                return joueur_selecion


# 원본   이미지 flist 경로: ./flist/room_flist.flist
# 지워진 이미지 flist 경로: ./flist/input_flist.flist
# 마스크 이미지 flist 경로: ./flist/mask_flist.flist
import os
import glob

image_path_list = ['./datasets/train/', './datasets/val/', './datasets/test/']                               # 이미지 파일 경로 리스트
flist_path_list = ['./datasets/train.flist', './datasets/val.flist', './datasets/test.flist']                # flist 파일 경로 리스트

class FlistGenerator():
    def __init__(self, image_path_list, flist_path_list):
        self.image_path_list = image_path_list
        self.flist_path_list = flist_path_list

        for i in range(3):
            with open(flist_path_list[i], 'w') as f:                                                                # flist 파일 쓰기모드로 열기
                file_name_list = [os.path.basename(k) for k in glob.glob(image_path_list[i]+'*')]                   # 이미지 파일 경로 리스트로 만들기
                file_len = len(file_name_list)                                                                      # 파일 개수

                for j in range(file_len):
                    data = os.path.join(image_path_list[i], file_name_list[j]) + '\n'                               # 이미지 파일 경로\n
                    f.write(data)                                                                                # flist 파일에 이미지 파일 경로\n 쓰기

flist_generator = FlistGenerator(image_path_list, flist_path_list)
#flist_generator._generate_flist()


# Pre-work Question 1
def hello_name(user_name):
    return f"Hello {user_name}!"

print(hello_name("Ashley"))

# Pre-work Question 2
def first_odds(number):
    for x in range(number):
        if number % 2 != 0:
            print(x)
        return None

print(first_odds(100))

# Pre-Work Question 3
def max_num_in_list(a_list):
    x = sorted(a_list, reverse=True)
    return x[0]

print(max_num_in_list([10,1,32,63,46,100]))

# Pre-Work Question 4
def is_leap_year(year):
    if year % 4 == 0 and year % 100 != 0:
        return True
    else:
        return False

print(is_leap_year(2028))

# Pre-work Question 5
def is_consecutive(a_list):
    prior = 0
    for i in a_list:
        if i-prior ==1:
            print("worked")

        else:
            print("nope")
        prior = i

is_consecutive([1, 2, 4, 5, 6])


#!/usr/bin/python
# coding=utf-8

import numpy as np
from pyspark import SparkContext, SparkConf

def intToBase(n):
        if n==1: return "A"
        if n==2: return "C"
        if n==3: return "G"
        return "T"

def generateString(length):
        ints=np.random.random_integers(1,4,length)
        result="".join(list(map(lambda x: intToBase(x),ints)))
        return result

if __name__ == "__main__":
	conf = SparkConf().setAppName("ACGTGenerator").setMaster("local[8]")
	sc=SparkContext.getOrCreate(conf=conf)

	dataset=sc.parallelize(range(40)).map(lambda x:generateString(1000))
	dataset.saveAsTextFile("dataset.txt")

	sc.stop()


import torch
import torch.nn as nn
from models.lebert import LEBertModel
from models.cnn import MaskCNN
from transformers import BertPreTrainedModel, BertModel

class NestLEBertForNer(BertPreTrainedModel):
    def __init__(self, config):
        super(NestLEBertForNer, self).__init__(config)
        self.word_embeddings = nn.Embedding(config.word_vocab_size, config.word_embed_dim)
        self.bert = LEBertModel(config)
        self.biaffine_size = 200
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.inner_dim = int(self.config.hidden_size / self.config.num_attention_heads)
        self.fc = torch.nn.Linear(self.config.hidden_size, self.biaffine_size * self.inner_dim * 2)
        self.down_fc = torch.nn.Linear(self.biaffine_size, self.config.num_labels)

        if config.use_cnn:
            self.cnn_dim=200
            self.cnn_fc = nn.Linear(self.config.num_labels, self.cnn_dim)
            self.cnn_fc2 = nn.Linear(self.cnn_dim, self.config.num_labels)
            self.cnn = MaskCNN(self.cnn_dim, self.cnn_dim, kernel_size=3, depth=3)

        self.init_weights()

    def sinusoidal_position_embedding(self, batch_size, seq_len, output_dim):
        position_ids = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(-1)
        indices = torch.arange(0, output_dim // 2, dtype=torch.float)
        indices = torch.pow(10000, -2 * indices / output_dim)
        embeddings = position_ids * indices
        embeddings = torch.stack([torch.sin(embeddings), torch.cos(embeddings)],
                                 dim=-1)
        embeddings = embeddings.repeat(
            (batch_size, *([1] * len(embeddings.shape))))
        embeddings = torch.reshape(embeddings, (batch_size, seq_len, output_dim))
        embeddings = embeddings.to('cuda')
        return embeddings

    def get_table(self, input_ids, attention_mask, token_type_ids, word_ids, word_mask):
        word_embeddings = self.word_embeddings(word_ids)
        outputs = self.bert(
            input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids,
            word_embeddings=word_embeddings, word_mask=word_mask
        )
        encoded_layers = outputs[0]

        batch_size, seq_len = encoded_layers.size(0), encoded_layers.size(1)
        encoded_layers = self.dropout(encoded_layers)

        outputs = self.fc(encoded_layers)
        outputs = torch.split(outputs, self.inner_dim * 2,
                              dim=-1)
        outputs = torch.stack(outputs, dim=-2)
        qw, kw = outputs[..., :self.inner_dim], outputs[...,
                                                self.inner_dim:]

        pos_emb = self.sinusoidal_position_embedding(batch_size, seq_len,
                                                     self.inner_dim)

        cos_pos = pos_emb[..., None, 1::2].repeat_interleave(2,
                                                             dim=-1)
        sin_pos = pos_emb[..., None, ::2].repeat_interleave(2, dim=-1)
        qw2 = torch.stack([-qw[..., 1::2], qw[..., ::2]], -1)
        qw2 = qw2.reshape(qw.shape)
        qw = qw * cos_pos + qw2 * sin_pos
        kw2 = torch.stack([-kw[..., 1::2], kw[..., ::2]], -1)
        kw2 = kw2.reshape(kw.shape)
        kw = kw * cos_pos + kw2 * sin_pos

        logits = torch.einsum('bmhd,bnhd->bhmn', qw, kw)
        pad_mask = attention_mask.unsqueeze(1).unsqueeze(1).expand(batch_size, self.biaffine_size, seq_len, seq_len)

        if hasattr(self, 'cnn'):
            cnn_logits = logits
            biaffine_logits = logits
            cnn_logits = self.cnn(cnn_logits, pad_mask)
            logits = biaffine_logits + cnn_logits
            logits = logits * pad_mask - (1 - pad_mask) * 1e12

        else:
            logits = logits * pad_mask - (1 - pad_mask) * 1e12

            mask = torch.tril(torch.ones_like(logits), -1)
            logits -= mask * 1e12

        logits = self.down_fc(logits.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)

        return logits / self.inner_dim ** 0.5

    def forward(self, input_ids, attention_mask, token_type_ids, word_ids, word_mask, labels=None):

        logits = self.get_table(input_ids, attention_mask, token_type_ids, word_ids, word_mask)
        outputs = (logits,)
        if labels is not None:
            loss = self.compute_loss(logits, labels)
            outputs = (loss,) + outputs
        return outputs

    def compute_loss(self, pred, labels):
        batch_size, num_labels = labels.shape[:2]
        y_true = labels.reshape(batch_size * num_labels, -1)
        y_pred = pred.reshape(batch_size * num_labels, -1)
        loss = self.multilabel_categorical_crossentropy(y_pred, y_true)
        return loss

    def multilabel_categorical_crossentropy(self, y_pred, y_true):
        y_pred = (1 - 2 * y_true) * y_pred
        y_pred_neg = y_pred - y_true * 1e12
        y_pred_pos = y_pred - (1 - y_true) * 1e12
        zeros = torch.zeros_like(y_pred[..., :1])
        y_pred_neg = torch.cat([y_pred_neg, zeros], dim=-1)
        y_pred_pos = torch.cat([y_pred_pos, zeros], dim=-1)
        neg_loss = torch.logsumexp(y_pred_neg, dim=-1)
        pos_loss = torch.logsumexp(y_pred_pos, dim=-1)
        return (neg_loss + pos_loss).mean()


import random
import time
import numpy as np
class random_search:
    def min_largest_distance(self, vertices, k, iterations):
        start_time = time.time()
        final_vertices = None
        min_largest_distance = float('inf')
        basic_ops = 0

        for i in range(iterations):
            random_vertices = random.sample(vertices, k)

            distances = []
            for vertex in vertices:
                closest_distance = float('inf')
                for chosen_vertex in random_vertices:
                    distance = np.linalg.norm(np.array(vertex) - np.array(chosen_vertex))
                    basic_ops += 1
                    if distance < closest_distance:
                        closest_distance = distance
                distances.append(closest_distance)
            largest_distance = max(distances)
            if largest_distance < min_largest_distance:
                min_largest_distance = largest_distance
                final_vertices = random_vertices
        return final_vertices, basic_ops, time.time() - start_time, iterations


import unittest
import calc

class TestCalc(unittest.TestCase):

    def setUp(self):
        # define test variables to be used in every test, for example:
        self.emp_1 = Employee('Tom','Davids', 5000)
        self.emp_2 = Employee('Carol','Richards', 5000)

    def tearDown(self):
        pass

    def test_add(self): #only functions that start with 'test' will run
        result = calc.add(10,5)
        self.assertEqual(result,15)
        self.assertEqual(calc.add(-1,1),0)
        self.assertEqual(calc.add(-1,-1),-2)

    def test_multiply(self):
        result = calc.multiply(10,5)
        self.assertEqual(result,50)
        self.assertEqual(calc.multiply(-1,1),-1)
        self.assertEqual(calc.multiply(-1,-1),1)

    def test_divide(self):
        result = calc.divide(10,5)
        self.assertEqual(result,2)
        self.assertEqual(calc.divide(-1,1),-1)
        self.assertEqual(calc.divide(-1,-1),1)

# in order to run it directly, otherwise:
# 'python -m unittest test_calc.py'
if __name__ == '__main__':
    unittest.main()


from django.conf.urls import url

from keywords import views

app_name = "keywords"

urlpatterns = [
    url(r'^$',
        views.keyword_list,
        name="keyword_list"),

    url(r'^(?P<keyword_slug>[-\w]*)/$',
        views.keyword_detail,
        name="keyword_detail"),
]


from django.shortcuts import render, redirect

from recipes.app.forms import RecipeForm, DeleteRecipeForm
from recipes.app.models import Recipe

def show_home(request):
    recipes = Recipe.objects.all()
    return render(request, 'index.html', {'recipes': recipes})

def create_recipe(request):
    if request.method == 'GET':
        form = RecipeForm()
        return render(request, 'create.html', {'form': form})
    else:
        form = RecipeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
        else:
            return render(request, 'create.html', {'form': form})

def edit_recipe(request, pk):
    recipe = Recipe.objects.get(pk=pk)
    if request.method == 'GET':
        form = RecipeForm(instance=recipe)
        return render(request, 'edit.html', {'form': form})
    else:
        form = RecipeForm(request.POST, instance=recipe)
        if form.is_valid():
            form.save()
            return redirect('home')
        else:
            return render(request, 'edit.html', {'form': form})

def delete_recipe(request, pk):
    recipe = Recipe.objects.get(pk=pk)
    if request.method == 'GET':
        form = DeleteRecipeForm(instance=recipe)
        return render(request, 'delete.html', {'form': form})
    else:
        recipe.delete()
        return redirect('home')

def recipe_details(request, pk):
    recipe = Recipe.objects.get(pk=pk)
    ingredients = recipe.ingredients.split(', ')
    return render(request, 'details.html', {'recipe': recipe, 'ingredients': ingredients})


# Baekjoon01149_RGBDistance.py
# https://acmicpc.net/problem/1149
import sys
sys.setrecursionlimit(99999)

time = int(sys.stdin.readline())
colorCost = [ ]
for _ in range( time ):
	colorCost.append( list( map( int, sys.stdin.readline().split() ) ) )

table = { }
def CalDistance( n: int, prevColor: int ) -> int:
	if n in table and prevColor in table[n]:
		return table[n][prevColor]
	if n:
		costs = [ ]
		for c in range( 3 ):
			if c != prevColor:
				costs.append( CalDistance( n - 1, c ) + colorCost[n - 1][prevColor] )
		minCosts = min(costs)
		if n not in table:
			table[n] = { prevColor : minCosts }
		else:
			table[n][prevColor] = minCosts

		return minCosts
	else:
		return 0

costs = [ ]
for i in range( 3 ):
	costs.append( CalDistance( time, i ) )
print( min(costs) )


class Yuumi:
    from configLoader import fileLoader
    import numpy as np
    import cv2
    from PIL import ImageGrab
    import pyautogui
    from imageManipulation import imageRec

    cfg = fileLoader("config.cfg")

    cfg.readConfig()

    cfgData = cfg.cfg
    print(cfgData)

    cfg.close()

    imgrec = imageRec()

    # variables:
    # cfg is object
    # cfgDict is dictionary of cfg data

    init = True

    while True:
        img = ImageGrab.grab(cfgData[0]) #BGR not RGB
        img_np = np.array(img)
        mapFrame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)

        hudImg = ImageGrab.grab(cfgData[1])
        hudImg_np = np.array(hudImg)
        hudFrame = cv2.cvtColor(hudImg_np, cv2.COLOR_BGR2RGB)

        champImg = ImageGrab.grab(cfgData[8])
        champImg_np = np.array(champImg)
        champFrame = cv2.cvtColor(champImg_np, cv2.COLOR_BGR2RGB)

        cv2.imshow("f1", mapFrame)
        cv2.imshow("f2", hudFrame)
        cv2.imshow("f3", champFrame)
        #print(pyautogui.position())
        imgrec.getHealthValue(cfgData[9][0], cfgData[9][1], cfgData[9][2], cfgData[9][3])

        if init:
            cv2.moveWindow("f1",cfgData[2],cfgData[3])
            cv2.moveWindow("f2",cfgData[4],cfgData[5])
            cv2.moveWindow("f3",cfgData[6],cfgData[7])
            init = False

        if cv2.waitKey(1) == 27:
            break

    cv2.destroyAllWindows()


import os
import pickle

from collections import defaultdict
from Bio.Blast import NCBIXML
import numpy as np
import pandas as pd

def getEggNOG_homologousNameUnSortedPP_COG2PP_reversedPP_dict(record):

    CurrentSpe_ID,max_level,EggNOG_groupPath,homologous_COG2PP_path=record

    EggNOG_homologousPP_COG2PP_CurrentSpe_dict_file=homologous_COG2PP_path+"EggNogMaxLevel"+max_level+"_"+CurrentSpe_ID+'_HomologousCOG2PP_NameUnSorted_dict.pickle'

    if not os.path.exists(EggNOG_homologousPP_COG2PP_CurrentSpe_dict_file): # this is not working in nextflow but useful when run seperately
        EggNOG_group_level2=pd.read_csv(EggNOG_groupPath+max_level+".tsv",
                                        header=None,index_col=None,sep="\t")

        EggNOG_group_level2_speID=EggNOG_group_level2.iloc[:,2].values.tolist()
        EggNOG_group_level2_speID=[str(sid) for sid in EggNOG_group_level2_speID]

        EggNOG_group_level2_idx=[idx for idx,sid in  enumerate(EggNOG_group_level2_speID) if (sid==CurrentSpe_ID)]
        EggNOG_group_level2=EggNOG_group_level2.iloc[EggNOG_group_level2_idx,:]
        EggNOG_group_level2=EggNOG_group_level2.sort_values(by=1)

        # create a dictiontionay whose key is eggnog group id/name and keys are speceis and protein belong to this eggnog group
        EggNOG_group_level2_groupDict=defaultdict(list)

        EggNOG_group_level2_list=EggNOG_group_level2.values.tolist()

        for _,group_id,sid,pname in EggNOG_group_level2_list:
            EggNOG_group_level2_groupDict[group_id].append((str(sid),pname))

        print(CurrentSpe_ID,"EggNOG_group_level2_groupDict",len(EggNOG_group_level2_groupDict))

        # for all  eggnog group pairs , get homologous protein pairs belong to these eggnog group pairs
        # and creat two dictinoary to store such information for query and Query species

        # here have to order eggnog group. so each eggnog group pair, only one recored remained
        EggNOG_group_level2_uniqueGroups=sorted(list(EggNOG_group_level2_groupDict.keys()))
        EggNOG_homologousPP_COG2PP_CurrentSpe_dict=defaultdict(list)

        for ig in range(len(EggNOG_group_level2_uniqueGroups)-1):
            ig_eggnogID=EggNOG_group_level2_uniqueGroups[ig]
            ig_values = EggNOG_group_level2_groupDict[ig_eggnogID]
            for jg  in range(ig+1,len(EggNOG_group_level2_uniqueGroups)):
                jg_eggnogID=EggNOG_group_level2_uniqueGroups[jg]
                jg_values = EggNOG_group_level2_groupDict[jg_eggnogID]
                for ig_sid, ig_pname in ig_values:
                    for jg_sid,jg_pname in jg_values:
                        #if (ig_sid == jg_sid):  # actually this step is not neceeeay as of course they are from all species
                        # because we order COG groups before
                        # there we make sure both (protein1, protein2 ) and (protein2, protein1 )  have records
                        EggNOG_homologousPP_COG2PP_CurrentSpe_dict[(ig_eggnogID,jg_eggnogID)].append((ig_pname,jg_pname))
                        EggNOG_homologousPP_COG2PP_CurrentSpe_dict[(jg_eggnogID,ig_eggnogID)].append((jg_pname,ig_pname))
        print("len(EggNOG_homologousPP_COG2PP_CurrentSpe_dict:",len(EggNOG_homologousPP_COG2PP_CurrentSpe_dict))

        #notice even for nextlfow , the folder homologous_COG2PP_path is temperory, it need to be creaed before to avoid file not exist problem
        with open(EggNOG_homologousPP_COG2PP_CurrentSpe_dict_file, 'wb') as handle:
            pickle.dump(EggNOG_homologousPP_COG2PP_CurrentSpe_dict, handle)

def allQuery2SubjectPPIMapping_getNameUnSorted_COGasLink(Query_tuple,Subject_tupleList,PPIInfoBeforeCoEvoComp_csv,homologous_COG2PP_path):

    # use  postive and negative ppi to only use pp that have large Nf90 value, and after removing deep homologs
    currentSpe_allPPIs_beforeCoEvoComp_frame = pd.read_csv(PPIInfoBeforeCoEvoComp_csv,header=0,index_col=None,sep="\t")
    print("currentSpe_allPPIs_beforeCoEvoComp_frame.shape:",currentSpe_allPPIs_beforeCoEvoComp_frame.shape)
    currentSpe_allPPIs_beforeCoEvoComp_info=currentSpe_allPPIs_beforeCoEvoComp_frame.values.tolist()
    allPPIs=[(p1,p2) for p1, p2,_ in currentSpe_allPPIs_beforeCoEvoComp_info]
    print("len(allPPIs):",len(allPPIs))
    Query_allPPI_allInfo_dict={pp:1 for pp in allPPIs}
    print("len(Query_allPPI_allInfo_dict)",len(Query_allPPI_allInfo_dict))

   # this is cog to pp relationship in eggnot level 2 despite spceis
    Query_EggNOG_homologousPP_COG2PP_dict_file=homologous_COG2PP_path+"EggNogMaxLevel2_"+Query_tuple[1]+'_HomologousCOG2PP_NameUnSorted_dict.pickle'
    with open(Query_EggNOG_homologousPP_COG2PP_dict_file, 'rb') as handle:
            Query_EggNOG_homologousPP_COG2PP_dict=pickle.load(handle)
    print("len(Query_EggNOG_homologousPP_COG2PP_dict):",len(Query_EggNOG_homologousPP_COG2PP_dict))

    Query_EggNOG_homologousPP_PP2COG_dict=defaultdict(list)
    for k, vs in Query_EggNOG_homologousPP_COG2PP_dict.items():
        for v in vs:
            Query_EggNOG_homologousPP_PP2COG_dict[v].append(k)
    print(len(Query_EggNOG_homologousPP_PP2COG_dict))

    #keep in mind here "PP2COG_dict" is already contain reversed records
    # here filter cog to pp relation by only keep pp with calculated high dca scores to save computational time later
    Query_EggNOG_homologousPP_PP2COG_dict={ pp: Query_EggNOG_homologousPP_PP2COG_dict[pp] for pp in Query_allPPI_allInfo_dict}
    print("len(Query_EggNOG_homologousPP_PP2COG_dict):",len(Query_EggNOG_homologousPP_PP2COG_dict))

    # for subject data
    Query2Subject_homologous_dict_listDict=dict()
    for Subject_phylum, Subject_speID in Subject_tupleList:
        print("Subject_phylum, Subject_speID:",Subject_phylum, Subject_speID)

        # this is cog to pp relationship in eggnot level 2 despite spceis
        Subject_EggNOG_homologousPP_COG2PP_dict_file=homologous_COG2PP_path+"EggNogMaxLevel2_"+Subject_speID+'_HomologousCOG2PP_NameUnSorted_dict.pickle'
        with open(Subject_EggNOG_homologousPP_COG2PP_dict_file, 'rb') as handle:
                Subject_EggNOG_homologousPP_COG2PP_dict=pickle.load(handle)
        print(len(Subject_EggNOG_homologousPP_COG2PP_dict))

        # combined info
        Query2Subject_homologous_dict=defaultdict(list)
        for Query_pp, cogs in Query_EggNOG_homologousPP_PP2COG_dict.items():
            for cog in cogs:
                if cog in Subject_EggNOG_homologousPP_COG2PP_dict:
                    Subject_pps=Subject_EggNOG_homologousPP_COG2PP_dict[cog]
                    # for each cog , should be a append
                    Query2Subject_homologous_dict[Query_pp].extend(Subject_pps)
                    #Namesorted_Query2Subject_homologous_dict[subject_pp]=query_pps

        #thats because in query speceis, some different  protein pairs can exist  in diffrent cog pairs
        #that can be mapped to same protein pairs in subject species
        # so bacically , one protein pair in sub species and one protein pair in query sepceis share several cog paris
        print(len(Query2Subject_homologous_dict))
        Query2Subject_homologous_dict={k: list(set(v)) for k, v in Query2Subject_homologous_dict.items()}

        print(len(Query2Subject_homologous_dict))

        Query2Subject_homologous_dict_listDict[(Subject_phylum, Subject_speID)]=Query2Subject_homologous_dict

    return(Query2Subject_homologous_dict_listDict)

def allQuery2SubjectSingleProteinMapping(Query2Subject_QueSpeAllPPI_homologous_dict_listDict):

    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict=defaultdict(dict)
    for phylum_speID,temp_Query2Subject_QueSpeAllPPI_homologous_dict in Query2Subject_QueSpeAllPPI_homologous_dict_listDict.items():
        print(phylum_speID)
        for Query_pp, Subject_pps in temp_Query2Subject_QueSpeAllPPI_homologous_dict.items():
            Query_pp1,Query_pp2=Query_pp
            for Subject_pp in Subject_pps:
                Subject_pp1,Subject_pp2=Subject_pp

                # here we should notice one  single protein can have multiple homologous protein pairs
                # and same one singel protein to single protein mapping can appear many times in different homologous protein pair mapping
                if Query_pp1 not in Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID]:
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID][Query_pp1]={Subject_pp1} #set
                else:
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID][Query_pp1].add(Subject_pp1)

                if Query_pp2 not in Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID]:
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID][Query_pp2]={Subject_pp2} # set
                else:
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[phylum_speID][Query_pp2].add(Subject_pp2)

    return(Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict)

def allQuery2SubjectSingleProteinMapping_getBlasp(Query_speID,Subject_tupleList,homologous_SeqMappingPath,Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict):
    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_bestHspBits_listDict=defaultdict(dict)
    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_blastp_listDict=defaultdict(dict)
    for phylum, Subject_speID in Subject_tupleList:
        print(phylum, Subject_speID)

        current_homologous_SeqMappingPath=homologous_SeqMappingPath+"EggNogMaxLevel2_QuerySpe_ID"+Query_speID+"and"+"SubjectSpe_ID"+Subject_speID+'/'

        temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict=Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[(phylum,Subject_speID)]

        for Query_proID,Subject_proIDs in temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict.items():
            for Subject_proID in Subject_proIDs:
                #print(current_homologous_SeqMappingPath+Query_proID+"and"+Subject_proID+".xml")
                with open(current_homologous_SeqMappingPath+Query_proID+"and"+Subject_proID+".xml") as handle:
                    blast_record = NCBIXML.read(handle)

                    # ???? here there is a problem is that if blast_record.alignments is None
                    # then this for loop will never get started and thus sorted_alignment_hsps and beste_hsp
                    # will just be the values from last for loop

                    if len(blast_record.alignments)>0:
                        for alignment in blast_record.alignments:
                            #print("times")
                            sorted_alignment_hsps=sorted(alignment.hsps,key=lambda hsp: hsp.bits,reverse=True)
                            best_hsp=sorted_alignment_hsps[0]
                            #print("best_hsp.bits:",best_hsp.bits)
                        Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_bestHspBits_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=best_hsp.bits
                    else:
                        #print("here empty blastp results")
                        Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_bestHspBits_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=np.nan

                # '6 qseqid  qlen sseqid  slen qstart qend sstart send evalue bitscore pident qcovs qcovhsp'
                try:
                    out_frame=pd.read_csv(current_homologous_SeqMappingPath+Query_proID+"and"+Subject_proID+".txt",header=None,sep="\t")
                    out_frame=out_frame.sort_values(by=[9],ascending=True) # sorted by bit scores
                    out_values=out_frame.values.tolist()
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_blastp_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=out_values

                except:
                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_blastp_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=np.nan

    return (Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_bestHspBits_listDict,
           Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_blastp_listDict)

def Query2Subject_AAmapDic(Query_speID,Subject_tupleList,
                           homologous_SeqMappingPath,
                           Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict,
                           overlap_method="remove"):

    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Query2Subject_AAmapDic_listDict=defaultdict(dict)
    for phylum, Subject_speID in Subject_tupleList:

        current_homologous_SeqMappingPath=homologous_SeqMappingPath+"EggNogMaxLevel2_QuerySpe_ID"+Query_speID+"and"+"SubjectSpe_ID"+Subject_speID+'/'

        temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict=Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[(phylum,Subject_speID)]

        for Query_proID,Subject_proIDs in temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict.items():
            for Subject_proID in Subject_proIDs:
                with open(current_homologous_SeqMappingPath+Query_proID+"and"+Subject_proID+"subject2query_AAmapDic_overlapMethod"+overlap_method+".pickle", 'rb') as handle:
                    Subject2Query_AAmapDic=pickle.load(handle)

                    # here pos in AAmapDic start with 1
                    # !! we force it to start from 0 , so its consistent with  0-starting pos from other object
                    Subject2Query_AAmapDic={k-1:v-1for k, v in Subject2Query_AAmapDic.items()}

                    Query2Subject_AAmapDic={v:k for k , v in Subject2Query_AAmapDic.items()}

                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Query2Subject_AAmapDic_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=Query2Subject_AAmapDic

    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_AAmapDic_listDict=defaultdict(dict)
    for phylum, Subject_speID in Subject_tupleList:

        current_homologous_SeqMappingPath=homologous_SeqMappingPath+"EggNogMaxLevel2_QuerySpe_ID"+Query_speID+"and"+"SubjectSpe_ID"+Subject_speID+'/'

        temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict=Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_listDict[(phylum,Subject_speID)]

        for Query_proID,Subject_proIDs in temp_Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_dict.items():
            for Subject_proID in Subject_proIDs:
                with open(current_homologous_SeqMappingPath+Query_proID+"and"+Subject_proID+"subject2query_AAmapDic_overlapMethod"+overlap_method+".pickle", 'rb') as handle:
                    Subject2Query_AAmapDic=pickle.load(handle)

                    # here pos in AAmapDic start with 1
                    # !! we force it to start from 0 , so its consistent with  0-starting pos from other object
                    Subject2Query_AAmapDic={k-1:v-1for k, v in Subject2Query_AAmapDic.items()}

                    Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_AAmapDic_listDict[(phylum,Subject_speID)][(Query_proID,Subject_proID)]=Subject2Query_AAmapDic

    return(Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Query2Subject_AAmapDic_listDict,Query2Subject_QueSpeAllPPI_homologous_singleProteinMaping_Subject2Query_AAmapDic_listDict)

def chooseBestHomologousPP(Query_PP,Subject_PPs,Query2Subject_homologous_ignoreSubjectDCA_singleProteinMaping_Subject2Query_bestHspBits_dict):

    #print(Subject_PPs)
    BestHomologousPP=()
    BestHomologousPP_bestHspBits=()
    # when Subject_PPs is none, for lood dont stat and empty Subject pp returned
    for Subject_PP in Subject_PPs:
        cur_QuerySubjectPP1_bestHspBits=Query2Subject_homologous_ignoreSubjectDCA_singleProteinMaping_Subject2Query_bestHspBits_dict[(Query_PP[0],Subject_PP[0])]
        cur_QuerySubjectPP2_bestHspBits=Query2Subject_homologous_ignoreSubjectDCA_singleProteinMaping_Subject2Query_bestHspBits_dict[(Query_PP[1],Subject_PP[1])]

        if not ((np.isnan(cur_QuerySubjectPP1_bestHspBits)) or (np.isnan(cur_QuerySubjectPP2_bestHspBits))) :

            if len(BestHomologousPP)==0:
                BestHomologousPP=Subject_PP
                BestHomologousPP_bestHspBits=(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits)
            else:
                # compare lower bestHspBits of currrent Subject pp and homologous pp
                # choose one with high lower bestHspbit
                if min(BestHomologousPP_bestHspBits)< min(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits):
                    BestHomologousPP=Subject_PP
                    BestHomologousPP_bestHspBits=(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits)
                # when lower bestHspBits  are same , compare another protein
                elif (min(BestHomologousPP_bestHspBits)== min(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits)) and (max(BestHomologousPP_bestHspBits)< max(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits)):
                    BestHomologousPP=Subject_PP
                    BestHomologousPP_bestHspBits=(cur_QuerySubjectPP1_bestHspBits,cur_QuerySubjectPP2_bestHspBits)

    return(BestHomologousPP)

def getMetaFrame_FullBestHomologousPP(Query_tuple,EggNOG_maxLevel,currentSpe_TaxID,STRING_Version,
                                      benchmark_suffix="STRINPhyPPI_Benchmark/",
                                     smallPhylum="",
                                     BestHomologousPP_filePrefix="BestHomologousPP",
                                        CoEvo_data_folder="CoEvo_data_STRING11.5/",
                                     ):
    '''
    here full BestHomologousPP means all BestHomologous pp compared with Query speceis
    It does not include all pp in origin indepenpendt benchmark dataset
    '''
    input_root_folder=CoEvo_data_folder+smallPhylum+currentSpe_TaxID+"_EggNOGmaxLevel"+EggNOG_maxLevel+"_eggNOGfilteredData/"

    Subect_BestHomologousPP_prefix="BestHomologousPPFor"+Query_tuple[1]+"AtEggNOGmaxLevel"+Query_tuple[0]+"_"
    BestHomologousPP_Benchmark_folder=input_root_folder+Subect_BestHomologousPP_prefix+benchmark_suffix #
    print("BestHomologousPP_Benchmark_folder:",BestHomologousPP_Benchmark_folder)

    allPPI_allInfo_frame=pd.read_csv(BestHomologousPP_Benchmark_folder+BestHomologousPP_filePrefix+"_allPPI_allInfo_frame.csv",
                                 header=0,index_col=None,sep="\t")

    print("allPPI_allInfo_frame.shape:",allPPI_allInfo_frame.shape)

    if benchmark_suffix == "STRINPhyPPI_Benchmark/":
        Pos_allPPI_allInfo_frame=allPPI_allInfo_frame.loc[allPPI_allInfo_frame['benchmark_status']=="P",:]
        #print("Pos_allPPI_allInfo_frame.shape:",Pos_allPPI_allInfo_frame.shape)
        Pos_allPPI_allInfo_frame=Pos_allPPI_allInfo_frame.sort_values(by="maxBetDCA_score",ascending=False)

        Neg_allPPI_allInfo_frame=allPPI_allInfo_frame.loc[allPPI_allInfo_frame['benchmark_status']=="N",:]
        #print("Neg_allPPI_allInfo_frame.shape:",Neg_allPPI_allInfo_frame.shape)

        Neg_allPPI_allInfo_frame=Neg_allPPI_allInfo_frame.sort_values(by="maxBetDCA_score",ascending=False)

        allPPI_allInfo_frame= pd.concat([Pos_allPPI_allInfo_frame,Neg_allPPI_allInfo_frame])
    elif benchmark_suffix == "KEGG_Benchmark/":
        allPPI_allInfo_frame=allPPI_allInfo_frame.sort_values(by="maxBetDCA_score",ascending=False)
    elif benchmark_suffix == "QianCong_Benchmark/":
        allPPI_allInfo_frame=allPPI_allInfo_frame.sort_values(by="maxBetDCA_score",ascending=False)

    else:
        return(allPPI_allInfo_frame)

    return(allPPI_allInfo_frame)

def collect_BestHomologousDCAs_OneSpeOneScore_OnlyTopPosNeg(allPPI_allInfoFrame,
                                                      Query_BestHomologousDCAs_dict,
                                                      ML_inputPath,CoEvo_type="DCA",
                                                           BestHomologousDCAs_dict_withStatus=True):

    X_fileName=ML_inputPath+"OnlyTopPosNeg_NonPara_X_BestHomologous"+CoEvo_type+"s_OneSpeOneScore.npy"
    Y_fileName=ML_inputPath+"OnlyTopPosNeg_NonPara_Y_BestHomologous"+CoEvo_type+"s_OneSpeOneScore.npy"
    #if not os.path.exists(X_fileName):

    NonPara_allPPI_info=allPPI_allInfoFrame.loc[:,["STRING_ID1","STRING_ID2","benchmark_status"]].values.tolist()

    if BestHomologousDCAs_dict_withStatus:
        OnlyTopPosNeg_NonPara_X=np.zeros((len(NonPara_allPPI_info),len(list(Query_BestHomologousDCAs_dict.values())[0])-1))
        OnlyTopPosNeg_NonPara_Y=np.zeros((len(NonPara_allPPI_info),1))
        for idx,l in enumerate(NonPara_allPPI_info):
            p1, p2 , label=l
            numeric_lable=1 if label=="P" else 0

            OnlyTopPosNeg_NonPara_X[idx,:]=Query_BestHomologousDCAs_dict[(p1,p2)][1:]
            OnlyTopPosNeg_NonPara_Y[idx]=numeric_lable
    else:
        OnlyTopPosNeg_NonPara_X=np.zeros((len(NonPara_allPPI_info),len(list(Query_BestHomologousDCAs_dict.values())[0])))
        OnlyTopPosNeg_NonPara_Y=np.zeros((len(NonPara_allPPI_info),1))
        for idx,l in enumerate(NonPara_allPPI_info):
            p1, p2 , label=l
            numeric_lable=1 if label=="P" else 0

            OnlyTopPosNeg_NonPara_X[idx,:]=Query_BestHomologousDCAs_dict[(p1,p2)]
            OnlyTopPosNeg_NonPara_Y[idx]=numeric_lable

    np.save(X_fileName,OnlyTopPosNeg_NonPara_X)
    np.save(Y_fileName,OnlyTopPosNeg_NonPara_Y)

    OnlyTopPosNeg_NonPara_XtopCoEvos=np.load(X_fileName)

    OnlyTopPosNeg_NonPara_YtopCoEvos=np.load(Y_fileName)
    OnlyTopPosNeg_NonPara_YtopCoEvos=np.reshape(OnlyTopPosNeg_NonPara_YtopCoEvos,(OnlyTopPosNeg_NonPara_YtopCoEvos.shape[0],))#

    return(OnlyTopPosNeg_NonPara_XtopCoEvos,OnlyTopPosNeg_NonPara_YtopCoEvos)


import tensorflow as tf

def build_encoder(input_shape, num_layers, num_units):
	slice_input = tf.keras.Input(shape = input_shape, dtype = tf.float32)

	# Feature Extraction
	conv1 = tf.keras.layers.Conv2D(64, (3, 3), activation = tf.nn.relu)
	feature = tf.keras.layers.TimeDistributed(conv1)(slice_input)
	conv2 = tf.keras.layers.Conv2D(4, (3, 3), strides = 2)
	feature = tf.keras.layers.TimeDistributed(conv2)(feature)
	flatten = tf.keras.layers.Flatten()
	feature = tf.keras.layers.TimeDistributed(flatten)(feature) # [Batch, T, F]
	output = tf.keras.layers.BatchNormalization()(feature)

	# RNN
	for i in range(num_layers):
		cell = tf.keras.layers.LSTMCell(num_units)
		rnn = tf.keras.layers.RNN(cell, return_sequences = True)
		output = rnn(output)
		output = tf.keras.layers.LayerNormalization()(output)

	return tf.keras.Model(inputs = [slice_input], outputs = [output], name = 'encoder')

def build_predictor(vocab_size, embed_size, num_layers, num_units):
	label_input = tf.keras.Input(shape = [None], dtype = tf.int64)

	# Label to Embedding
	embed = tf.keras.layers.Embedding(vocab_size, embed_size)(label_input)

	output = embed

	for i in range(num_layers):
		cell = tf.keras.layers.LSTMCell(num_units)
		rnn = tf.keras.layers.RNN(cell, return_sequences = True)
		output = rnn(output)
		output = tf.keras.layers.LayerNormalization()(output)

	return tf.keras.Model(inputs = [label_input], outputs = [output], name = 'predictor')

def build_joint(pred_input_shape, enc_input_shape, vocab_size, hidden_units):
	pred_input = tf.keras.Input(shape = pred_input_shape, dtype = tf.float32)
	enc_input = tf.keras.Input(shape = enc_input_shape, dtype = tf.float32)

	pred_dense = tf.keras.layers.Dense(hidden_units)
	enc_dense = tf.keras.layers.Dense(hidden_units)

	hidden_output = tf.expand_dims(pred_dense(pred_input), axis = 1) + tf.expand_dims(enc_dense(enc_input), axis = 2)
	hidden_output = tf.keras.activations.relu(hidden_output)

	dense_logit = tf.keras.layers.Dense(vocab_size)
	output = dense_logit(hidden_output)

	return tf.keras.Model(inputs = [pred_input, enc_input], outputs = [output], name = 'joint')

def build_transducer(args):
	slice_input_shape = [None, args.slice_width, args.slice_height, args.num_channels]
	joint_pred_input_shape = [None, args.enc_num_units] # [Batch, Time, h_Enc]
	joint_enc_input_shape = [None, args.pred_num_units] # [Batch, Label, h_Pred]

	slice_input = tf.keras.Input(shape = slice_input_shape, dtype = tf.float32, name = 'image_slice')
	label_input = tf.keras.Input(shape = [None], dtype = tf.float32, name = 'label')

	encoder = build_encoder(slice_input_shape, args.enc_num_layers, args.enc_num_units)
	predictor = build_predictor(args.vocab_size, args.embed_size, args.pred_num_layers, args.pred_num_units)
	joint = build_joint(joint_pred_input_shape, joint_enc_input_shape, args.vocab_size, args.joint_num_units)

	h_enc = encoder(slice_input)
	h_pred = predictor(label_input)
	logit = joint([h_pred, h_enc])

	return tf.keras.Model(inputs = [slice_input, label_input], outputs = [logit], name = 'transducer')


from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils.data import getdate

class Retouren(Document):
    def onload(self):
        if self.mv_mitgliedschaft:
            mitgliedschaft = frappe.get_doc("Mitgliedschaft", self.mv_mitgliedschaft)
            self.adressblock = mitgliedschaft.adressblock

    def validate(self):
        if self.status == 'Offen':
            mitgliedschaft = frappe.get_doc("Mitgliedschaft", self.mv_mitgliedschaft)
            mitgliedschaft.m_w_retouren_offen = 1
            anz_offen, anz_in_bearbeitung = get_retouren_qty(self.mv_mitgliedschaft, self)

            if anz_in_bearbeitung < 1:
                mitgliedschaft.m_w_retouren_in_bearbeitung = 0

            mitgliedschaft.m_w_anzahl = anz_offen + anz_in_bearbeitung
            mitgliedschaft.letzte_bearbeitung_von = 'SP'

            mitgliedschaft.retoure_in_folge = self.retoure_in_folge

            mitgliedschaft.save()

        elif self.status == 'In Bearbeitung':
            mitgliedschaft = frappe.get_doc("Mitgliedschaft", self.mv_mitgliedschaft)
            mitgliedschaft.m_w_retouren_in_bearbeitung = 1
            anz_offen, anz_in_bearbeitung = get_retouren_qty(self.mv_mitgliedschaft, self)

            if anz_offen < 1:
                mitgliedschaft.m_w_retouren_offen = 0

            mitgliedschaft.m_w_anzahl = anz_offen + anz_in_bearbeitung
            mitgliedschaft.letzte_bearbeitung_von = 'SP'

            mitgliedschaft.retoure_in_folge = self.retoure_in_folge

            mitgliedschaft.save()

        else:
            anz_offen, anz_in_bearbeitung = get_retouren_qty(self.mv_mitgliedschaft, self)
            mitgliedschaft = frappe.get_doc("Mitgliedschaft", self.mv_mitgliedschaft)

            if anz_offen > 0 or anz_in_bearbeitung > 0:
                if anz_offen > 0:
                    mitgliedschaft.m_w_retouren_offen = 1
                else:
                    mitgliedschaft.m_w_retouren_offen = 0
                if anz_in_bearbeitung > 0:
                    mitgliedschaft.m_w_retouren_in_bearbeitung = 1
                else:
                    mitgliedschaft.m_w_retouren_in_bearbeitung = 0
                mitgliedschaft.m_w_anzahl = anz_offen + anz_in_bearbeitung
                mitgliedschaft.letzte_bearbeitung_von = 'SP'

                mitgliedschaft.retoure_in_folge = self.retoure_in_folge

                mitgliedschaft.save()
            else:
                mitgliedschaft.m_w_retouren_offen = 0
                mitgliedschaft.m_w_retouren_in_bearbeitung = 0
                mitgliedschaft.m_w_anzahl = anz_offen + anz_in_bearbeitung
                mitgliedschaft.letzte_bearbeitung_von = 'SP'

                mitgliedschaft.retoure_in_folge = self.retoure_in_folge

                mitgliedschaft.save()

        if self.adresse_geaendert != 1:
            adresse = frappe.db.sql("""SELECT `adresse_mitglied` FROM `tabMitgliedschaft` WHERE `name` = '{mitgliedschaft}'""".format(mitgliedschaft=self.mv_mitgliedschaft), as_dict=True)
            if len(adresse) > 0:
                if adresse[0].adresse_mitglied and adresse[0].adresse_mitglied != 'None':
                    adresse = adresse[0].adresse_mitglied

                    datum_adressexport = frappe.db.sql("""SELECT `datum_adressexport` FROM `tabMW` WHERE `laufnummer` = '{retoure_mw_sequence_number}' LIMIT 1""".format(retoure_mw_sequence_number=self.retoure_mw_sequence_number), as_dict=True)
                    if len(datum_adressexport) > 0:
                        datum_adressexport = datum_adressexport[0].datum_adressexport
                        self.adresse_geaendert = adresse_geaendert_check(adr=adresse, datum_adressexport=datum_adressexport)

def get_retouren_qty(mitgliedschaft, self):
    anz_offen = frappe.db.sql("""SELECT
                                    COUNT(`name`) AS `qty`
                                FROM `tabRetouren`
                                WHERE `mv_mitgliedschaft` = '{mitgliedschaft}'
                                AND `status` = 'Offen'""".format(mitgliedschaft=mitgliedschaft), as_dict=True)[0].qty
    anz_in_bearbeitung = frappe.db.sql("""SELECT
                                            COUNT(`name`) AS `qty`
                                        FROM `tabRetouren`
                                        WHERE `mv_mitgliedschaft` = '{mitgliedschaft}'
                                        AND `status` = 'In Bearbeitung'""".format(mitgliedschaft=mitgliedschaft), as_dict=True)[0].qty

    old_status = frappe.db.sql("""SELECT `status` FROM `tabRetouren` WHERE `name` = '{retoure}'""".format(retoure=self.name), as_dict=True)
    if len(old_status) > 0:
        if old_status[0].status != self.status:
            if old_status[0].status == 'Offen':
                anz_offen -= 1
            elif old_status[0].status == 'In Bearbeitung':
                anz_in_bearbeitung -= 1

            if self.status == 'Offen':
                anz_offen += 1
            elif self.status == 'In Bearbeitung':
                anz_in_bearbeitung += 1
    else:
        if self.status == 'Offen':
            anz_offen += 1
        elif self.status == 'In Bearbeitung':
            anz_in_bearbeitung += 1

    return anz_offen, anz_in_bearbeitung

def create_post_retouren(data):
    try:
        ausgabe_kurz = frappe.db.sql("""SELECT `ausgabe_kurz` FROM `tabMW` WHERE `laufnummer` = '{retoure_mw_sequence_number}' LIMIT 1""".format(retoure_mw_sequence_number=data['retoureMuWSequenceNumber']), as_dict=True)[0].ausgabe_kurz
        mitgliedschaft = frappe.get_doc("Mitgliedschaft", data['mitgliedId'])

        if mitgliedschaft.adresse_mitglied and mitgliedschaft.adresse_mitglied != 'None':
            datum_adressexport = frappe.db.sql("""SELECT `datum_adressexport` FROM `tabMW` WHERE `laufnummer` = '{retoure_mw_sequence_number}' LIMIT 1""".format(retoure_mw_sequence_number=data['retoureMuWSequenceNumber']), as_dict=True)[0].datum_adressexport
            adresse_geaendert = adresse_geaendert_check(adr=mitgliedschaft.adresse_mitglied, datum_adressexport=datum_adressexport)
        else:
            adresse_geaendert = 0

        if data['neueAddresse']:
            neue_adresse_json = data['neueAddresse']
            neue_adresse = """"""
            try:
                gueltig_ab = neue_adresse_json['validFrom'].split(" ")[0].split("/")[2] + "-" + neue_adresse_json['validFrom'].split(" ")[0].split("/")[0] + "-" + neue_adresse_json['validFrom'].split(" ")[0].split("/")[1]
            except:
                gueltig_ab = None
            if neue_adresse_json['validTo']:
                neue_adresse += """\nGültig bis {0}""".format(neue_adresse_json['validTo'])
            if neue_adresse_json['adresszusatz']:
                neue_adresse += """\n{0}""".format(neue_adresse_json['adresszusatz'])
            if neue_adresse_json['postfach']:
                neue_adresse += """\n{0}""".format(neue_adresse_json['postfach'])
                if neue_adresse_json['postfachNummer']:
                    neue_adresse += """ {0}""".format(neue_adresse_json['postfachNummer'])
            if neue_adresse_json['strasse']:
                neue_adresse += """\n{0}""".format(neue_adresse_json['strasse'])
                if neue_adresse_json['hausnummer']:
                    neue_adresse += """ {0}""".format(neue_adresse_json['hausnummer'])
                if neue_adresse_json['hausnummerZusatz']:
                    neue_adresse += """{0}""".format(neue_adresse_json['hausnummerZusatz'])
            if neue_adresse_json['postleitzahl']:
                neue_adresse += """\n{0} {1}""".format(neue_adresse_json['postleitzahl'], neue_adresse_json['ort'])

        else:
            neue_adresse_json = None
            neue_adresse = None
            gueltig_ab = None

        post_retoure = frappe.get_doc({
            'doctype': 'Retouren',
            'mv_mitgliedschaft': data['mitgliedId'],
            'sektion_id': mitgliedschaft.sektion_id,
            'adressblock': mitgliedschaft.adressblock,
            'ausgabe': ausgabe_kurz,
            'legacy_kategorie_code': data['legacyKategorieCode'],
            'legacy_notiz': data['legacyNotiz'],
            'grund_code': data['grundCode'],
            'grund_bezeichnung': data['grundBezeichnung'],
            'retoure_mw_sequence_number': data['retoureMuWSequenceNumber'],
            'retoure_dmc': data['retoureDMC'],
            'retoureSendungsbild': data['retoureSendungsbild'],
            'datum_erfasst_post': data['datumErfasstPost'],
            'adresse_geaendert': adresse_geaendert,
            'retoure_in_folge': check_retoure_in_folge(data['retoureMuWSequenceNumber'], data['mitgliedId']),
            'neue_adresse_json': str(neue_adresse_json),
            'neue_adresse': neue_adresse,
            'neue_adresse_gueltig_ab': gueltig_ab
        })

        post_retoure.insert(ignore_permissions=True)
        frappe.db.commit()

        return 1

    except Exception as err:
        return err

@frappe.whitelist()
def close_open_retouren(mitgliedschaft):
    retouren = frappe.db.sql("""SELECT
                                    `name`
                                FROM `tabRetouren`
                                WHERE `status` != 'Abgeschlossen'
                                AND `mv_mitgliedschaft` = '{mitgliedschaft}'""".format(mitgliedschaft=mitgliedschaft), as_dict=True)
    if len(retouren) > 0:
        for retoure in retouren:
            r = frappe.get_doc("Retouren", retoure.name)
            r.status = 'Abgeschlossen'
            r.save()

def check_dates(adresse, event):
    changed = adresse_geaendert_check(adr=adresse.name, adresse_fuer_vergleich=adresse)
    if changed == 1:
        mitgliedschaften = frappe.db.sql("""SELECT
                                                `name`
                                            FROM `tabMitgliedschaft`
                                            WHERE `adresse_mitglied` = '{adresse}' LIMIT 1""".format(adresse=adresse.name), as_dict=True)
        if len(mitgliedschaften) > 0:
            mitgliedschaft = mitgliedschaften[0].name
            retouren = frappe.db.sql("""SELECT
                                            `name`
                                        FROM `tabRetouren`
                                        WHERE `mv_mitgliedschaft` = '{mitgliedschaft}'""".format(mitgliedschaft=mitgliedschaft), as_dict=True)
            for retoure in retouren:
                retoure = frappe.get_doc("Retouren", retoure.name)
                if retoure.adresse_geaendert != 1:
                    datum_adressexport = frappe.db.sql("""SELECT
                                                                `datum_adressexport`
                                                            FROM `tabMW`
                                                            WHERE `laufnummer` = '{retoure_mw_sequence_number}' LIMIT 1""".format(retoure_mw_sequence_number=retoure.retoure_mw_sequence_number), as_dict=True)
                    if len(datum_adressexport) > 0:
                        adresse_geaendert = adresse_geaendert_check(adr=adresse.name, adresse_fuer_vergleich=adresse)
                        frappe.db.sql("""UPDATE `tabRetouren` SET `adresse_geaendert` = {adresse_geaendert} WHERE `name` = '{name}'""".format(adresse_geaendert=adresse_geaendert, name=retoure.name), as_list=True)

@frappe.whitelist()
def get_mail_data(mitgliedschaft, retoure, grund_bezeichnung):
    mitgliedschaft = frappe.get_doc("Mitgliedschaft", mitgliedschaft)
    if mitgliedschaft.e_mail_1:
        email_body = '{0}%0d%0a%0d%0aDie Post konnte Ihnen unsere Verbandszeitschrift M+W nicht zustellen. Sie wurde retourniert mit dem Vermerk «{1}».%0d%0aBitte teilen Sie uns Ihre aktuelle Wohnadresse mit, damit wir Ihnen auch weiterhin unsere Post zustellen können.%0d%0a%0d%0aSie sind in unserer Mitgliederdatei unter nachfolgender Adresse geführt:%0d%0a{2}%0d%0a%0d%0a%0d%0a%0d%0a'.format(mitgliedschaft.briefanrede, grund_bezeichnung.split(" (")[0], mitgliedschaft.adressblock.replace("\n", "%0d%0a"))
        if mitgliedschaft.language == 'fr':
            email_body = "Cher Monsieur / Chère Madame,%0d%0a%0d%0aLa poste n'a pas pu vous livrer notre journal de l’Asloca M+W à l’adresse indiquée. Il a été retourné avec la remarque «{0}».%0d%0aVeuillez nous communiquer votre adresse résidentielle actuelle afin que nous puissions continuer à vous livrer notre courrier.%0d%0a%0d%0aDans notre fichier votre adresse est enregistrée comme suit :%0d%0a{1}%0d%0a%0d%0a%0d%0a%0d%0a".format(grund_bezeichnung.split(" (")[0], mitgliedschaft.adressblock.replace("\n", "%0d%0a"))

        return {
            'email': mitgliedschaft.e_mail_1,
            'cc': 'mv+Mitgliedschaft+{0}@libracore.io;mv+Retouren+{1}@libracore.io'.format(mitgliedschaft.name, retoure),
            'subject': 'Ihre Mitgliedschaft ({0}): Neue Adresse?'.format(mitgliedschaft.mitglied_nr),
            'email_body': email_body
        }
    else:
        return None

def adresse_geaendert_check(adr=None, datum_adressexport=None, adresse_fuer_vergleich=False):
    if adr:
        if not adresse_fuer_vergleich:
            adresse_geaendert = frappe.db.sql("""SELECT
                                                        `creation`
                                                    FROM `tabVersion`
                                                    WHERE `docname` = '{adr}'
                                                    AND `ref_doctype` = 'Address'
                                                    AND (
                                                        `data` LIKE '%zusatz%'
                                                        or `data` LIKE '%strasse%'
                                                        or `data` LIKE '%postfach%'
                                                        or `data` LIKE '%postfach_nummer%'
                                                        or `data` LIKE '%plz%'
                                                        or `data` LIKE '%city%'
                                                        or `data` LIKE '%address_line2%'
                                                    )
                                                    ORDER BY `creation` DESC
                                                    LIMIT 1""".format(adr=adr), as_dict=True)
            if len(adresse_geaendert) > 0:
                if datum_adressexport:
                    adresse_geaendert = getdate(adresse_geaendert[0].creation)
                    datum_adressexport = getdate(datum_adressexport)
                    frappe.log_error("adresse_geaendert: {0}\ndatum_adressexport: {1}".format(adresse_geaendert, datum_adressexport), "adresse_geaendert_check: {0}".format(adr))
                    if adresse_geaendert >= datum_adressexport:
                        return 1
                    else:
                        return 0
                else:
                    return 1
            else:
                return 0
        else:
            try:
                latest_adress = adresse_fuer_vergleich._doc_before_save
                if latest_adress.zusatz != adresse_fuer_vergleich.zusatz:
                    return 1
                if latest_adress.strasse != adresse_fuer_vergleich.strasse:
                    return 1
                if latest_adress.postfach != adresse_fuer_vergleich.postfach:
                    return 1
                if latest_adress.postfach_nummer != adresse_fuer_vergleich.postfach_nummer:
                    return 1
                if latest_adress.plz != adresse_fuer_vergleich.plz:
                    return 1
                if latest_adress.city != adresse_fuer_vergleich.city:
                    return 1
                if latest_adress.address_line2 != adresse_fuer_vergleich.address_line2:
                    return 1
            except:
                # no older version avaible
                return 0
            # no changes
            return 0

    else:
        return 0

def check_retoure_in_folge(retoure_mw_sequence_number, mv_mitgliedschaft):
    retoure_mw_sequence_number = int(retoure_mw_sequence_number) - 1
    qty = frappe.db.sql("""SELECT COUNT(`name`) AS `qty` FROM `tabRetouren` WHERE `retoure_mw_sequence_number` = '{retoure_mw_sequence_number}' AND `mv_mitgliedschaft` = '{mv_mitgliedschaft}'""".format(retoure_mw_sequence_number=retoure_mw_sequence_number, mv_mitgliedschaft=mv_mitgliedschaft), as_dict=True)[0].qty
    if qty > 0:
        return 1
    else:
        return 0