import random
from unittest.mock import patch
import pytest
from base58 import b58decode
from ipld import marshal, multihash
from operator import attrgetter

from transactions.common import crypto
from transactions.common.transaction import Transaction, TransactionLink, Input
from transactions.types.assets.create import Create
from transactions.types.assets.transfer import Transfer
from planetmint.exceptions import CriticalDoubleSpend

pytestmark = pytest.mark.bdb

class TestBigchainApi(object):
    def test_get_spent_with_double_spend_detected(self, b, alice):
        from transactions.common.exceptions import DoubleSpend

        from planetmint.exceptions import CriticalDoubleSpend

        tx = Create.generate([alice.public_key], [([alice.public_key], 1)])
        tx = tx.sign([alice.private_key])

        b.models.store_bulk_transactions([tx])

        transfer_tx = Transfer.generate(tx.to_inputs(), [([alice.public_key], 1)], asset_ids=[tx.id])
        transfer_tx = transfer_tx.sign([alice.private_key])
        transfer_tx2 = Transfer.generate(tx.to_inputs(), [([alice.public_key], 2)], asset_ids=[tx.id])
        transfer_tx2 = transfer_tx2.sign([alice.private_key])

        with pytest.raises(DoubleSpend):
            b.validate_transaction(transfer_tx2, [transfer_tx])

        b.models.store_bulk_transactions([transfer_tx])

        with pytest.raises(DoubleSpend):
            b.validate_transaction(transfer_tx2)

        with pytest.raises(CriticalDoubleSpend):
            b.models.store_bulk_transactions([transfer_tx2])

    def test_double_inclusion(self, b, alice):
        from planetmint.backend.exceptions import OperationError
        from planetmint.backend.tarantool.sync_io.connection import TarantoolDBConnection

        tx = Create.generate([alice.public_key], [([alice.public_key], 1)])
        tx = tx.sign([alice.private_key])

        b.models.store_bulk_transactions([tx])
        if isinstance(b.models.connection, TarantoolDBConnection):
            with pytest.raises(CriticalDoubleSpend):
                b.models.store_bulk_transactions([tx])
        else:
            with pytest.raises(OperationError):
                b.models.store_bulk_transactions([tx])

    @pytest.mark.usefixtures("inputs")
    def test_non_create_input_not_found(self, b, user_pk):
        from planetmint_cryptoconditions import Ed25519Sha256
        from transactions.common.exceptions import InputDoesNotExist

        # Create an input for a non existing transaction
        input = Input(
            Ed25519Sha256(public_key=b58decode(user_pk)), [user_pk], TransactionLink("somethingsomething", 0)
        )
        tx = Transfer.generate([input], [([user_pk], 1)], asset_ids=["mock_asset_link"])
        with pytest.raises(InputDoesNotExist):
            b.validate_transaction(tx)

    def test_write_transaction(self, b, user_sk, user_pk, alice, create_tx):
        asset1 = {"data": "QmaozNR7DZHQK1ZcU9p7QdrshMvXqWK6gpu5rmrkPdT3L4"}

        tx = Create.generate([alice.public_key], [([alice.public_key], 1)], assets=[asset1]).sign([alice.private_key])
        b.models.store_bulk_transactions([tx])

        tx_from_db = b.models.get_transaction(tx.id)

        before = tx.to_dict()
        after = tx_from_db.to_dict()

        assert before["assets"][0] == after["assets"][0]
        before.pop("assets", None)
        after.pop("assets", None)
        assert before == after

class TestTransactionValidation(object):
    def test_non_create_input_not_found(self, b, signed_transfer_tx):
        from transactions.common.exceptions import InputDoesNotExist
        from transactions.common.transaction import TransactionLink

        signed_transfer_tx.inputs[0].fulfills = TransactionLink("c", 0)
        with pytest.raises(InputDoesNotExist):
            b.validate_transaction(signed_transfer_tx)

    @pytest.mark.usefixtures("inputs")
    def test_non_create_valid_input_wrong_owner(self, b, user_pk):
        from transactions.common.crypto import generate_key_pair
        from transactions.common.exceptions import InvalidSignature
        from transactions.common.transaction_link import TransactionLink

        output = b.models.get_outputs_filtered(user_pk).pop()
        input_transaction = b.models.get_transaction(output.transaction_id)
        sk, pk = generate_key_pair()
        tx = Create.generate([pk], [([user_pk], 1)])
        tx.operation = "TRANSFER"
        tx.assets = [{"id": input_transaction.id}]
        tx.inputs[0].fulfills = TransactionLink(output.transaction_id, output.index)

        with pytest.raises(InvalidSignature):
            b.validate_transaction(tx)

    @pytest.mark.usefixtures("inputs")
    def test_non_create_double_spend(self, b, signed_create_tx, signed_transfer_tx, double_spend_tx):
        from transactions.common.exceptions import DoubleSpend

        b.models.store_bulk_transactions([signed_create_tx, signed_transfer_tx])

        with pytest.raises(DoubleSpend):
            b.validate_transaction(double_spend_tx)

class TestMultipleInputs(object):
    def test_transfer_single_owner_single_input(self, b, inputs, user_pk, user_sk):
        user2_sk, user2_pk = crypto.generate_key_pair()
        tx_output = b.models.get_outputs_filtered(user_pk).pop()
        input_tx = b.models.get_transaction(tx_output.transaction_id)
        tx_converted = Transaction.from_dict(input_tx.to_dict(), True)

        tx = Transfer.generate(tx_converted.to_inputs(), [([user2_pk], 1)], asset_ids=[input_tx.id])
        tx = tx.sign([user_sk])

        # validate transaction
        b.validate_transaction(tx)
        assert len(tx.inputs) == 1
        assert len(tx.outputs) == 1

    def test_single_owner_before_multiple_owners_after_single_input(self, b, user_sk, user_pk, inputs):
        user2_sk, user2_pk = crypto.generate_key_pair()
        user3_sk, user3_pk = crypto.generate_key_pair()
        tx_output = b.models.get_outputs_filtered(user_pk).pop()

        input_tx = b.models.get_transaction(tx_output.transaction_id)
        tx_converted = Transaction.from_dict(input_tx.to_dict(), True)

        tx = Transfer.generate(tx_converted.to_inputs(), [([user2_pk, user3_pk], 1)], asset_ids=[input_tx.id])
        tx = tx.sign([user_sk])

        b.validate_transaction(tx)
        assert len(tx.inputs) == 1
        assert len(tx.outputs) == 1

    @pytest.mark.usefixtures("inputs")
    def test_multiple_owners_before_single_owner_after_single_input(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()
        user3_sk, user3_pk = crypto.generate_key_pair()

        tx = Create.generate([alice.public_key], [([user_pk, user2_pk], 1)])
        tx = tx.sign([alice.private_key])
        b.models.store_bulk_transactions([tx])

        tx_output = b.models.get_outputs_filtered(user_pk).pop()
        input_tx = b.models.get_transaction(tx_output.transaction_id)
        input_tx_converted = Transaction.from_dict(input_tx.to_dict(), True)

        transfer_tx = Transfer.generate(input_tx_converted.to_inputs(), [([user3_pk], 1)], asset_ids=[input_tx.id])
        transfer_tx = transfer_tx.sign([user_sk, user2_sk])

        # validate transaction
        b.validate_transaction(transfer_tx)
        assert len(transfer_tx.inputs) == 1
        assert len(transfer_tx.outputs) == 1

    @pytest.mark.usefixtures("inputs")
    def test_multiple_owners_before_multiple_owners_after_single_input(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()
        user3_sk, user3_pk = crypto.generate_key_pair()
        user4_sk, user4_pk = crypto.generate_key_pair()

        tx = Create.generate([alice.public_key], [([user_pk, user2_pk], 1)])
        tx = tx.sign([alice.private_key])
        b.models.store_bulk_transactions([tx])

        # get input
        tx_output = b.models.get_outputs_filtered(user_pk).pop()
        tx_input = b.models.get_transaction(tx_output.transaction_id)
        input_tx_converted = Transaction.from_dict(tx_input.to_dict(), True)

        tx = Transfer.generate(input_tx_converted.to_inputs(), [([user3_pk, user4_pk], 1)], asset_ids=[tx_input.id])
        tx = tx.sign([user_sk, user2_sk])

        b.validate_transaction(tx)
        assert len(tx.inputs) == 1
        assert len(tx.outputs) == 1

    def test_get_owned_ids_single_tx_single_output(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()

        tx = Create.generate([alice.public_key], [([user_pk], 1)])
        tx = tx.sign([alice.private_key])
        b.models.store_bulk_transactions([tx])

        stored_tx = b.models.get_transaction(tx.id)

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user2_pk)
        assert owned_inputs_user1 == [stored_tx.outputs[0]]
        assert owned_inputs_user2 == []

        tx_transfer = Transfer.generate(tx.to_inputs(), [([user2_pk], 1)], asset_ids=[tx.id])
        tx_transfer = tx_transfer.sign([user_sk])
        b.models.store_bulk_transactions([tx_transfer])

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user2_pk)

        stored_tx_transfer = b.models.get_transaction(tx_transfer.id)

        assert owned_inputs_user1 == [stored_tx.outputs[0]]
        assert owned_inputs_user2 == [stored_tx_transfer.outputs[0]]

    def test_get_owned_ids_single_tx_multiple_outputs(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()

        # create divisible asset
        tx_create = Create.generate([alice.public_key], [([user_pk], 1), ([user_pk], 1)])
        tx_create_signed = tx_create.sign([alice.private_key])
        b.models.store_bulk_transactions([tx_create_signed])

        # get input
        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user2_pk)

        stored_tx = b.models.get_transaction(tx_create.id)

        expected_owned_inputs_user1 = [stored_tx.outputs[0], stored_tx.outputs[1]]
        assert sorted(owned_inputs_user1, key=attrgetter("index")) == sorted(
            expected_owned_inputs_user1, key=attrgetter("index")
        )
        assert owned_inputs_user2 == []

        # transfer divisible asset divided in two outputs
        tx_transfer = Transfer.generate(
            tx_create.to_inputs(), [([user2_pk], 1), ([user2_pk], 1)], asset_ids=[tx_create.id]
        )
        tx_transfer_signed = tx_transfer.sign([user_sk])
        b.models.store_bulk_transactions([tx_transfer_signed])
        stored_tx_transfer = b.models.get_transaction(tx_transfer.id)

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user2_pk)
        assert sorted(owned_inputs_user1, key=attrgetter("index")) == sorted(
            expected_owned_inputs_user1, key=attrgetter("index")
        )
        assert sorted(owned_inputs_user2, key=attrgetter("index")) == sorted(
            [stored_tx_transfer.outputs[0], stored_tx_transfer.outputs[1]], key=attrgetter("index")
        )

    def test_get_owned_ids_multiple_owners(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()
        user3_sk, user3_pk = crypto.generate_key_pair()

        tx = Create.generate([alice.public_key], [([user_pk, user2_pk], 1)])
        tx = tx.sign([alice.private_key])

        b.models.store_bulk_transactions([tx])
        stored_tx = b.models.get_transaction(tx.id)

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user_pk)
        expected_owned_inputs_user1 = [stored_tx.outputs[0]]

        assert owned_inputs_user1 == owned_inputs_user2
        assert owned_inputs_user1 == expected_owned_inputs_user1

        tx = Transfer.generate(tx.to_inputs(), [([user3_pk], 1)], asset_ids=[tx.id])
        tx = tx.sign([user_sk, user2_sk])
        b.models.store_bulk_transactions([tx])

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        owned_inputs_user2 = b.models.get_outputs_filtered(user2_pk)
        spent_user1 = b.models.get_spending_transaction(tx.id, 0)

        assert owned_inputs_user1 == owned_inputs_user2
        assert not spent_user1

    def test_get_spent_single_tx_single_output(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()

        tx = Create.generate([alice.public_key], [([user_pk], 1)])
        tx = tx.sign([alice.private_key])
        b.models.store_bulk_transactions([tx])

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk).pop()

        # check spents
        input_txid = owned_inputs_user1.transaction_id
        spent_inputs_user1 = b.models.get_spending_transaction(input_txid, 0)
        assert spent_inputs_user1 is None

        # create a transaction and send it
        tx = Transfer.generate(tx.to_inputs(), [([user2_pk], 1)], asset_ids=[tx.id])
        tx = tx.sign([user_sk])
        b.models.store_bulk_transactions([tx])

        spent_inputs_user1 = b.models.get_spending_transaction(input_txid, 0)
        assert spent_inputs_user1 == tx.to_dict()

    def test_get_spent_single_tx_multiple_outputs(self, b, user_sk, user_pk, alice):
        # create a new users
        user2_sk, user2_pk = crypto.generate_key_pair()

        # create a divisible asset with 3 outputs
        tx_create = Create.generate([alice.public_key], [([user_pk], 1), ([user_pk], 1), ([user_pk], 1)])
        tx_create_signed = tx_create.sign([alice.private_key])
        b.models.store_bulk_transactions([tx_create_signed])

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)

        # check spents
        for input_tx in owned_inputs_user1:
            assert b.models.get_spending_transaction(input_tx.transaction_id, input_tx.index) is None

        # transfer the first 2 inputs
        tx_transfer = Transfer.generate(
            tx_create.to_inputs()[:2], [([user2_pk], 1), ([user2_pk], 1)], asset_ids=[tx_create.id]
        )
        tx_transfer_signed = tx_transfer.sign([user_sk])
        b.models.store_bulk_transactions([tx_transfer_signed])

        # check that used inputs are marked as spent
        for ffill in tx_create.to_inputs()[:2]:
            spent_tx = b.models.get_spending_transaction(ffill.fulfills.txid, ffill.fulfills.output)
            assert spent_tx == tx_transfer_signed.to_dict()

        # check if remaining transaction that was unspent is also perceived
        # spendable by Planetmint
        assert b.models.get_spending_transaction(tx_create.to_inputs()[2].fulfills.txid, 2) is None

    def test_get_spent_multiple_owners(self, b, user_sk, user_pk, alice):
        user2_sk, user2_pk = crypto.generate_key_pair()
        user3_sk, user3_pk = crypto.generate_key_pair()

        transactions = []
        for i in range(3):
            payload = multihash(marshal({"msg": random.random()}))
            tx = Create.generate([alice.public_key], [([user_pk, user2_pk], 1)], payload)
            tx = tx.sign([alice.private_key])
            transactions.append(tx)

        b.models.store_bulk_transactions(transactions)

        owned_inputs_user1 = b.models.get_outputs_filtered(user_pk)
        # check spents
        for input_tx in owned_inputs_user1:
            assert b.models.get_spending_transaction(input_tx.transaction_id, input_tx.index) is None

        # create a transaction
        tx = Transfer.generate(transactions[0].to_inputs(), [([user3_pk], 1)], asset_ids=[transactions[0].id])
        tx = tx.sign([user_sk, user2_sk])
        b.models.store_bulk_transactions([tx])

        # check that used inputs are marked as spent
        assert b.models.get_spending_transaction(transactions[0].id, 0) == tx.to_dict()
        # check that the other remain marked as unspent
        for unspent in transactions[1:]:
            assert b.models.get_spending_transaction(unspent.id, 0) is None

def test_get_outputs_filtered_only_unspent(b, alice):
    tx = Create.generate([alice.public_key], [([alice.public_key], 1), ([alice.public_key], 1)])
    tx = tx.sign([alice.private_key])
    b.models.store_bulk_transactions([tx])

    tx_transfer = Transfer.generate(tx.to_inputs([0]), [([alice.public_key], 1)], asset_ids=[tx.id])
    tx_transfer = tx_transfer.sign([alice.private_key])
    b.models.store_bulk_transactions([tx_transfer])

    outputs = b.models.get_outputs_filtered(alice.public_key, spent=False)
    assert len(outputs) == 2

def test_get_outputs_filtered_only_spent(b, alice):
    tx = Create.generate([alice.public_key], [([alice.public_key], 1), ([alice.public_key], 1)])
    tx = tx.sign([alice.private_key])
    b.models.store_bulk_transactions([tx])

    tx_transfer = Transfer.generate(tx.to_inputs([0]), [([alice.public_key], 1)], asset_ids=[tx.id])
    tx_transfer = tx_transfer.sign([alice.private_key])
    b.models.store_bulk_transactions([tx_transfer])

    outputs = b.models.get_outputs_filtered(alice.public_key, spent=True)
    assert len(outputs) == 1

def test_get_outputs_filtered(b, alice):
    tx = Create.generate([alice.public_key], [([alice.public_key], 1), ([alice.public_key], 1)])
    tx = tx.sign([alice.private_key])
    b.models.store_bulk_transactions([tx])

    tx_transfer = Transfer.generate(tx.to_inputs([0]), [([alice.public_key], 1)], asset_ids=[tx.id])
    tx_transfer = tx_transfer.sign([alice.private_key])
    b.models.store_bulk_transactions([tx_transfer])

    outputs = b.models.get_outputs_filtered(alice.public_key)
    assert len(outputs) == 3

def test_cant_spend_same_input_twice_in_tx(b, alice):
    """Recreate duplicated fulfillments bug
    https://github.com/planetmint/planetmint/issues/1099
    """
    from transactions.common.exceptions import DoubleSpend

    # create a divisible asset
    tx_create = Create.generate([alice.public_key], [([alice.public_key], 100)])
    tx_create_signed = tx_create.sign([alice.private_key])
    assert b.validate_transaction(tx_create_signed) == tx_create_signed
    b.models.store_bulk_transactions([tx_create_signed])

    # Create a transfer transaction with duplicated fulfillments
    dup_inputs = tx_create.to_inputs() + tx_create.to_inputs()
    tx_transfer = Transfer.generate(dup_inputs, [([alice.public_key], 200)], asset_ids=[tx_create.id])
    tx_transfer_signed = tx_transfer.sign([alice.private_key])
    with pytest.raises(DoubleSpend):
        b.validate_transaction(tx_transfer_signed)

def test_transaction_unicode(b, alice):
    import copy

    from transactions.common.utils import serialize

    # http://www.fileformat.info/info/unicode/char/1f37a/index.htm

    beer_python = [{"data": multihash(marshal({"beer": "\N{BEER MUG}"}))}]
    beer_json = {"data": multihash(marshal({"beer": "\N{BEER MUG}"}))}

    tx = (Create.generate([alice.public_key], [([alice.public_key], 100)], assets=beer_python)).sign(
        [alice.private_key]
    )

    tx_1 = copy.deepcopy(tx)
    b.models.store_bulk_transactions([tx])

    assert beer_json["data"] in serialize(tx_1.to_dict())


"""
Classes used by the rest api and other utilities that handle data formatting
and gaps in a series of data.
"""
import datetime

from collections import OrderedDict

from esmond.util import atdecode, atencode
from tastypie.exceptions import BadRequest

class QueryUtil(object):
    """Class holding common query methods used by multiple resources
    and data structures to validate incoming request elements."""

    _timerange_limits = {
        30: datetime.timedelta(days=30),
        60: datetime.timedelta(days=30),
        300: datetime.timedelta(days=30),
        3600: datetime.timedelta(days=365),
        86400: datetime.timedelta(days=365*10),
    }

    timeseries_request_types = ['RawData', 'BaseRate', 'Aggs']
    bulk_request_types = ['timeseries', 'interface']

    @staticmethod
    def decode_datapath(datapath):
        return [ atdecode(step) for step in datapath ]

    @staticmethod
    def encode_datapath(datapath):
        return [ atencode(step) for step in datapath ]

    @staticmethod
    def valid_timerange(obj, in_ms=False):
        """Check the requested time range against the requested aggregation
        level and limit if too much data was requested.

        The in_ms flag is set to true if a given resource (like the
        /timeseries/ namespace) is doing business in milliseconds rather
        than seconds."""
        if in_ms:
            s = datetime.timedelta(milliseconds=obj.begin_time)
            e = datetime.timedelta(milliseconds=obj.end_time)
        else:
            s = datetime.timedelta(seconds=obj.begin_time)
            e = datetime.timedelta(seconds=obj.end_time)

        divs = { False: 1, True: 1000 }

        try:
            if e - s > QueryUtil._timerange_limits[obj.agg/divs[in_ms]]:
                return False
        except KeyError:
            raise BadRequest('invalid aggregation level: %s' %
                    obj.agg)

        return True

    @staticmethod
    def format_data_payload(data, in_ms=False, coerce_to_bins=None):
        """Massage results from cassandra for json return payload.

        The in_ms flag is set to true if a given resource (like the
        /timeseries/ namespace) is doing business in milliseconds rather
        than seconds.

        If coerce_to_bins is not None, truncate the timestamp to the
        the bins spaced coerce_to_bins ms apart. This is useful for
        fitting raw data to bin boundaries."""

        divs = { False: 1000, True: 1 }

        results = []

        for row in data:
            ts = row['ts']

            if coerce_to_bins:
                ts -= ts % coerce_to_bins

            d = [ts/divs[in_ms], row['val']]

            # Further options for different data sets.
            if row.has_key('is_valid'): # Base rates
                if row['is_valid'] == 0: d[1] = None
            elif row.has_key('cf'): # Aggregations
                pass
            else: # Raw Data
                pass

            results.append(d)

        return results

class Fill(object):
    """Set of methods to verify that a series of binned data contains
    the correct number of datapoints over a given time range, and if
    not, fill the missing bins with an invalid value before returning
    the data to the client.

    Normally persister will backfill gaps in the data in the DB but gaps
    could be returned under the following circumstances:

    1 - The most common scenario is when requesting up to the minute
    binned data where the most recent value might not have been written
    yet.

    2 - The query might span when a new device started having data
    recorded.

    3 - A gap (like if a device was offline for a period of time) might
    exceed the "heartbeat limit" and generate a span too long to reasonably
    fill with invalid data points.
    """
    @staticmethod
    def expected_bin_count(start_bin, end_bin, freq):
        """Get expected number of bins in a given range of bins."""
        return ((end_bin - start_bin) / freq) + 1

    @staticmethod
    def get_expected_first_bin(begin, freq):
        """Get the first bin of a given frequency based on the begin ts
        of a timeseries query."""
        # Determine the first bin in the series based on the begin
        # timestamp in the timeseries request.
        #
        # Bin math will round down to last bin but timerange queries will
        # return the next bin.  That is, given a 30 second bin, a begin
        # timestamp of 15 seconds past the minute will yield a bin calc
        # of on the minute, but but the time range query will return
        # 30 seconds past the minute as the first result.
        #
        # A begin timestamp falling directly on a bin will return
        # that bin.
        bin = (begin/freq)*freq
        if bin < begin:
            return bin+freq
        elif bin == begin:
            return bin
        else:
            # Shouldn't happen
            raise RuntimeError

    @staticmethod
    def get_bin_alignment(begin, end, freq):
        """Generate a few values needed for checking and filling a series if
        need be."""
        start_bin = Fill.get_expected_first_bin(begin,freq)
        end_bin = (end/freq)*freq
        expected_bins = Fill.expected_bin_count(start_bin, end_bin, freq)

        return start_bin, end_bin, expected_bins

    @staticmethod
    def generate_filled_series(start_bin, end_bin, freq, data):
        """Genrate a new 'filled' series if the returned series has unexpected
        gaps.  Initialize a new range based in the requested time range as
        an OrderedDict, then iterate through original series to retain original
        values.
        """
        # Generate the empty "proper" timerange
        filled_range = []
        s = start_bin + 0 # copy it
        while s <= end_bin:
            filled_range.append((s,None))
            s += freq

        # Make it a ordered dict
        fill = OrderedDict(filled_range)

        # Go through the original data and plug in
        # good values

        for dp in data:
            fill[dp[0]] = dp[1]

        for i in fill.items():
            yield list(i)

    @staticmethod
    def verify_fill(begin, end, freq, data):
        """Top-level function to inspect a returned series for gaps.
        Returns the original series of the count is correct, else will
        return a new filled series."""
        begin, end, freq = int(begin), int(end), int(freq)
        start_bin,end_bin,expected_bins = Fill.get_bin_alignment(begin, end, freq)
        #print 'got :', len(data)
        #print 'need:', Fill.expected_bin_count(start_bin,end_bin,freq)
        if len(data) == Fill.expected_bin_count(start_bin,end_bin,freq):
            #print 'verify: not filling'
            return data
        else:
            #print 'verify: filling'
            return list(Fill.generate_filled_series(start_bin,end_bin,freq,data))


import tensorflow as tf
from tensorflow.contrib.rnn import GRUCell
from utils import DataInput
import numpy as np

class DRL_Model(object):
    def __init__(self, user_count, item_count, hidden_size, batch_size, primary_session_dqn, target_session_dqn, primary_record_dqn, target_record_dqn):

        # Hyperparameter Settings
        hidden_size = 128
        session_length = 10
        gamma = 0.9
        margin = 0.1

        # Tensorflow Parameter Placeholders
        self.u = tf.placeholder(tf.int32, [batch_size,]) # [B]
        self.i = tf.placeholder(tf.int32, [batch_size,]) # [B]
        self.last_i = tf.placeholder(tf.int32, [batch_size,]) # [B]
        self.hist = tf.placeholder(tf.int32, [batch_size, session_length]) # [B, T]
        self.next_hist = tf.placeholder(tf.int32, [batch_size, session_length]) # [B, T]
        self.label = tf.placeholder(tf.float32, [batch_size,]) # [B]
        self.lr = tf.placeholder(tf.float64, [])
        self.i_table = tf.placeholder(tf.int32, [item_count,]) # [I]
        self.primary_session_dqn = primary_session_dqn
        self.target_session_dqn = target_session_dqn
        self.primary_record_dqn = primary_record_dqn
        self.target_record_dqn = target_record_dqn

        # Embedding Table Initialization
        user_emb_w = tf.get_variable("user_emb_w", [user_count, hidden_size])
        item_emb_w = tf.get_variable("item_emb_w", [item_count, hidden_size])
        user_emb = tf.nn.embedding_lookup(user_emb_w, self.u)
        item_emb = tf.nn.embedding_lookup(item_emb_w, self.i)
        last_item_emb = tf.nn.embedding_lookup(item_emb_w, self.last_i)
        h_emb = tf.nn.embedding_lookup(item_emb_w, self.hist)
        next_h_emb = tf.nn.embedding_lookup(item_emb_w, self.next_hist)
        item_emb_table = tf.nn.embedding_lookup(item_emb_w, self.i_table)

        # Session-Level DQNs for Producing Session Policy
        session_policy = tf.layers.dense(user_emb, 80, activation=tf.nn.sigmoid)
        session_policy = tf.layers.dense(session_policy, 40, activation=tf.nn.sigmoid)
        session_policy = tf.layers.dense(session_policy, hidden_size, activation=None)

        # Self-Attnetive GRU Network for Constructing Consumer State Representations
        with tf.variable_scope('gru', reuse=tf.AUTO_REUSE):
        	output, _ = tf.nn.dynamic_rnn(GRUCell(hidden_size), inputs=h_emb, dtype=tf.float32)
        	state, alphas = self.seq_attention(output, hidden_size, session_length)
        	state = tf.nn.dropout(state, 0.1)

        	next_output, _ = tf.nn.dynamic_rnn(GRUCell(hidden_size), inputs=next_h_emb, dtype=tf.float32)
        	next_state, next_alphas = self.seq_attention(next_output, hidden_size, session_length)
        	next_state = tf.nn.dropout(next_state, 0.1)

        # Record-Level DQNs for Producing Actions of Transition Vectors
        with tf.variable_scope('transition', reuse=tf.AUTO_REUSE):
            transition = tf.layers.batch_normalization(inputs=tf.concat([session_policy, state], axis=1))
            transition = tf.layers.dense(transition, 80, activation=tf.nn.sigmoid)
            transition = tf.layers.dense(transition, 40, activation=tf.nn.sigmoid)
            transition = tf.layers.dense(transition, hidden_size, activation=None)

            next_transition = tf.layers.batch_normalization(inputs=tf.concat([session_policy, next_state], axis=1))
            next_transition = tf.layers.dense(next_transition, 80, activation=tf.nn.sigmoid)
            next_transition = tf.layers.dense(next_transition, 40, activation=tf.nn.sigmoid)
            next_transition = tf.layers.dense(next_transition, hidden_size, activation=None)

        # Computing the Metric Loss for the Predicted Target Embeddings
        target_item_emb = tf.add(last_item_emb, transition)
        self.distance = tf.norm(target_item_emb-item_emb, ord='euclidean', axis=1)
        metric_loss = self.label * tf.square(tf.maximum(0., margin - self.distance)) + (1 - self.label) * tf.square(self.distance)
        self.metric_loss = 0.5 * tf.reduce_mean(metric_loss)

        # Compute the MSE Loss for the Record-Level DQNs
        with tf.variable_scope('record_dqn', reuse=tf.AUTO_REUSE):
            q_value = self.primary_record_dqn.forward(state, transition)
            next_q_value = self.target_record_dqn.forward(next_state, next_transition)
            predict_q_value = self.label + gamma*next_q_value
            self.dqn_loss = tf.reduce_mean(tf.losses.mean_squared_error(labels=predict_q_value, predictions=q_value))

        # Compute the MSE Loss for the Session-Level DQNs
        with tf.variable_scope('session_dqn', reuse=tf.AUTO_REUSE):
            meta_q_value = self.primary_session_dqn.forward(state, session_policy)
            next_meta_q_value = self.target_session_dqn.forward(next_state, session_policy)
            predict_meta_q_value = self.label + gamma*next_meta_q_value
            self.meta_dqn_loss = tf.reduce_mean(tf.losses.mean_squared_error(labels=predict_meta_q_value, predictions=meta_q_value))

        # Aggregation Loss Functions for Backpropogation
        self.loss = self.metric_loss + self.dqn_loss + self.meta_dqn_loss

        # Step VariableS for Updating Parameters in the Training Process
        self.embedding = target_item_emb
        self.item_emb_table = item_emb_table
        self.global_step = tf.Variable(0, trainable=False, name='global_step')
        self.global_epoch_step = tf.Variable(0, trainable=False, name='global_epoch_step')
        self.global_epoch_step_op = tf.assign(self.global_epoch_step, self.global_epoch_step+1)
        trainable_params = tf.trainable_variables()
        self.opt = tf.train.GradientDescentOptimizer(learning_rate=self.lr)
        gradients = tf.gradients(self.loss, trainable_params)
        clip_gradients, _ = tf.clip_by_global_norm(gradients, 1)
        self.train_op = self.opt.apply_gradients(zip(clip_gradients, trainable_params), global_step=self.global_step)

    def train(self, sess, uij, lr):
        loss, _ = sess.run([self.loss, self.train_op], feed_dict={
                self.u: uij[0],
                self.i: uij[1],
                self.last_i: uij[2],
                self.hist: uij[3],
                self.next_hist: uij[4],
                self.label: uij[5],
                self.lr: lr
                })
        return loss

    def test(self, sess, uij):
        distance, embedding = sess.run([self.distance, self.embedding], feed_dict={
                self.u: uij[0],
                self.i: uij[1],
                self.last_i: uij[2],
                self.hist: uij[3],
                self.next_hist: uij[4],
                self.label: uij[5]
                })
        return distance, uij[5], uij[0], uij[1], embedding

    def get_item_emb(self, sess, i_table):
        item_emb_table = sess.run(self.item_emb_table, feed_dict={
                self.i_table: i_table
                })
        return item_emb_table

    def seq_attention(self, inputs, hidden_size, attention_size):
        # Trainable parameters
        w_omega = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
        b_omega = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
        u_omega = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
        v = tf.tanh(tf.tensordot(inputs, w_omega, axes=1) + b_omega)
        vu = tf.tensordot(v, u_omega, axes=1, name='vu')  # (B,T) shape
        alphas = tf.nn.softmax(vu, name='alphas')         # (B,T) shape
        # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape
        output = tf.reduce_sum(inputs * tf.tile(tf.expand_dims(alphas, -1), [1, 1, hidden_size]), 1, name="attention_embedding")
        return output, alphas

class DQN(object):
    def __init__(self, hidden_size, scope_name):
        self.hidden_size = hidden_size
        self.scope_name = scope_name

    def forward(self, state, transition):
        with tf.variable_scope(self.scope_name):
            concat = tf.concat([state, transition], axis=1)
            concat = tf.layers.dense(concat, self.hidden_size, activation=tf.nn.relu)
            q_value = tf.layers.dense(concat, 1, activation=tf.nn.tanh)
            q_value = tf.reshape(q_value, [-1])
            return q_value


import cv2

img1 = cv2.imread('car.jpg')
img2 = cv2.imread('messi.jpg')
img1 = cv2.resize(img1, (600, 600))
img2 = cv2.resize(img2, (600, 600))
result1 = cv2.add(img2, img1)
result2 = cv2.addWeighted(img1, 0.2, img2, 0.8, 0)
cv2.imshow('Result', result1)
cv2.waitKey(0)
cv2.destroyAllWindows()


# import dependencies

import requests
import pymongo
import pandas as pd

from splinter import Browser
from bs4 import BeautifulSoup
import time

# open chrome driver browser
def init_browser():
    executable_path = {'executable_path': 'chromedriver.exe'}
    return Browser('chrome', **executable_path, headless=False)

# ## NASA Mars News

def scrape():
    browser = init_browser()

    mars_news_url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'"
    browser.visit(mars_news_url)

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

    titles = mars_news_soup.body.find("div", class_="content_title").text

    paras = mars_news_soup.body.find("div", class_="article_teaser_body").text

    # ## Mars Space Images

    time.sleep(3)

    image_url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"

    browser.visit(image_url)

    html = browser.html

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

    image = soup.find('article', class_='carousel_item')

    image_url  = soup.find('article')['style']

    image_url= image_url.replace("background-image: url('", '')

    image_url= image_url.replace("');", "")

    full_image_url = "https://www.jpl.nasa.gov" + image_url

    full_image_url

    #browser.click_link_by_id('full_image')

    #browser.click_link_by_partial_text('more info')

    #image_html = browser.html
    #mars_image_soup = BeautifulSoup(image_html, 'html.parser')

    #image = mars_image_soup.body.find("figure", class_="lede")

    #link = image.find('a')
    #href = link['href']

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

    #featured_image_url = base_url + href

    #featured_image_url

    # ## Mars Weather

    #time.sleep(3)

    #weather_url = "https://twitter.com/marswxreport?lang=en"
    #browser.visit(weather_url)

    #html = browser.html
    #mars_weather_soup = BeautifulSoup(html, 'html.parser')

    #weather_tweet = soup.find_all('div', class_='css-1dbjc4n')

    #weather_tweet[2].find('span')

    #weather_tweet[0].find('section', class_='css-1dbjc4n')

    #tweet_braket=weather_tweet[0].find('div',class_='css-901oao r-hkyrab r-1qd0xha r-a023e6 r-16dba41 r-ad9z0x r-bcqeeo r-bnwqim r-qvutc0')

    # tweet_braket1=tweet_braket.find('span', class_='css-901oao css-16my406 r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0')

    # tweet=tweet_braket1.getText()

    # find the tweet text

    #tweet_container = mars_weather_soup.body.find('div','js-tweet-text-container')

    #mars_weather = tweet_container.find('p').text

    #mars_weather

    # ## Mars Facts
    time.sleep(3)
    facts_url = "https://space-facts.com/mars/"

    tables = pd.read_html(facts_url)

    df = tables[0]
    df.columns = ["Item", "Description"]

    facts_html=df.to_html()

    facts_html

    # ## Mars Hemispheres

    #cerberus
    time.sleep(3)

    url = 'https://astrogeology.usgs.gov/search/map/Mars/Viking/cerberus_enhanced'
    browser.visit(url)
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')
    url = soup.find('div', class_='downloads')
    link = url.find('a')
    ce_href = link['href']

    #Schiaparelli
    time.sleep(3)
    url = 'https://astrogeology.usgs.gov/search/map/Mars/Viking/Schiaparelli_enhanced'
    browser.visit(url)
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')
    url = soup.find('div', class_='downloads')
    link = url.find('a')
    sc_href = link['href']

    #Syrtis Major
    time.sleep(3)
    url = 'https://astrogeology.usgs.gov/search/map/Mars/Viking/Syrtis Major_enhanced'
    browser.visit(url)
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')
    url = soup.find('div', class_='downloads')
    link = url.find('a')
    sy_href = link['href']

    #valles_marineris
    time.sleep(3)
    url = 'https://astrogeology.usgs.gov/search/map/Mars/Viking/valles_marineris_enhanced'
    browser.visit(url)
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')
    url = soup.find('div', class_='downloads')
    link = url.find('a')
    va_href = link['href']

    hemispheres_image_urls = [
        {"title": "cerberus Hemisphere", "img_url": ce_href},
        {"title": "Schiaparelli Hemisphere", "img_url": sc_href},
        {"title": "Syrtis Major Hemisphere", "img_url": sy_href},
        {"title": "valles_marineris Hemisphere", "img_url": va_href}
    ]

    mars_dict = {
        'latestheadline': titles,
        'latestparagraph':  paras,
        'featuredimage': full_image_url,
        'factstable': facts_html,
        'weather': "tweet",
        "ce_title": "cerberus Hemisphere", "ce_img_url": ce_href,
        "sc_title": "Schiaparelli Hemisphere", "sc_img_url": sc_href,
        "sy_title": "Syrtis Major Hemisphere", "sy_img_url": sy_href,
        "va_title": "valles_marineris Hemisphere", "va_img_url": va_href
        }

    browser.quit()
    return mars_dict


# coding: utf-8

# In[1]:

def polarization_interception_efficiency(alpha,N_R,N_P):
    import numpy as np
    import scipy as sp
    import scipy.io as si
    import scipy.constants as sc
    #from scipy.interpolate import Rbf
    from scipy.interpolate import griddata

    pi = sc.pi
    mat_contents = si.loadmat('theta_b_PR_results_3.mat')
    matrix = mat_contents['results']
    x = np.exp(np.transpose(matrix[:,0]))
    y = np.exp(np.transpose(matrix[:,1]))
    z = np.exp(np.transpose(matrix[:,2]))
    d = np.exp(np.transpose(matrix[:,3]))
    #rbfi = Rbf(x,y,z,d)
    xi = alpha*np.ones(N_R.size)
    yi = N_R
    zi = N_P
    di = griddata((x,y,z), d, (xi, yi, zi), method='linear')
    #di = rbfi(xi,yi,zi)
    theta_b = pi/(1+di)
    eta_PR_fit = 1/np.sqrt(alpha)*np.sin(theta_b)+alpha**2*N_P*(pi-theta_b)
    return eta_PR_fit

# In[ ]:


from util.util_base import *

def compress():
  """Compresses an image."""
  img = tf.placeholder(tf.float32, [1, None, None, 3])

  # Transform and compress the image, then remove batch dimension.
  y = analysis_transform(img, args.conv_filters, args.num_filters)
  y_hat, likelihoods, entropy_bottleneck, string = entropy_estimation(y, False)
  x_hat = synthesis_transform(y_hat,args.conv_filters, args.num_filters)
  num_pixels = tf.to_float(tf.reduce_prod(tf.shape(img)[:-1]))

  # Total number of bits divided by number of pixels.
  eval_bpp = tf.reduce_sum(tf.log(likelihoods)) / (-tf.log(2.0) * num_pixels)

  # Mean squared error across pixels.
  x_hat = tf.clip_by_value(x_hat, 0, 1)
  mse = tf.reduce_sum(tf.squared_difference(tf.round(img), x_hat)) / num_pixels

  base_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="pre256")
  print(base_var)
  test_image, test_image_padded, bdry = kodak()
  rec_image = np.zeros(np.shape(test_image))
  rec_image_padded = np.zeros(np.shape(test_image))
  avg_entropy = []
  avg_psnr = []
  avg_entropy_padded = []
  avg_psnr_padded = []
  avg_ms_ssims= []

  with tf.Session() as sess:
    # Load the latest model checkpoint, get the compressed string and the tensor
    # shapes.
    latest = tf.train.latest_checkpoint(checkpoint_dir=args.checkpoint_dir)
    tf.train.Saver().restore(sess, save_path=latest)
    for q in range(len(test_image)):
      cur_data = np.reshape(test_image[q, :, :, :], [1, wid, hgt, channels])
      psnr, bpp, x_hat_, msssim_rec = eval_test_image(sess, cur_data, string, img, y, eval_bpp, mse, num_pixels, x_hat, test_image, q)
      eval_bpp_ = sess.run([eval_bpp], feed_dict={img: cur_data})

      avg_entropy.append(bpp)
      avg_psnr.append(psnr)
      avg_ms_ssims.append(msssim_rec)
      rec_image[q,:,:,:] = x_hat_
      if (q % 8) == 0:
          print("Progress %d/%d." % (q, len(test_image)))
          print("Real bpp: %.4f, Eval bpp: %.4f" % (bpp, np.float32(eval_bpp_)))

    #print("Boundary padded test images")
    #for q in range(len(test_image_padded)):
    #  cur_data_padded = np.reshape(test_image_padded[q, :, :, :], [1, wid+bdry[0]+bdry[2], hgt+bdry[1]+bdry[3], channels])
    #  psnr, bpp, x_hat_ = eval_test_image_padded(sess, cur_data_padded, string, img, y, eval_bpp, mse, num_pixels, x_hat, test_image_padded, q, bdry)
    #  eval_bpp_ = sess.run([eval_bpp], feed_dict={img: cur_data_padded})
    #
    #  avg_entropy_padded.append(bpp)
    #  avg_psnr_padded.append(psnr)
    #  avg_psnr_padded.append(psnr)
    #  os.remove(r'./kodak/' + str(q) + '.bin')
    #  rec_image_padded[q,:,:,:] = x_hat_
    #  if (q % 8) == 0:
    #      print("Progress %d/%d." % (q, len(test_image_padded)))
    #      print("Real bpp: %.4f, Eval bpp: %.4f" % (bpp, np.float32(eval_bpp_)))

  final_avg_psnr = np.mean(avg_psnr)
  final_avg_entropy = np.mean(avg_entropy)
  avg_msssim = np.mean(avg_ms_ssims)
  #final_avg_psnr_padded = np.mean(avg_psnr_padded)
  #final_avg_entropy_padded = np.mean(avg_entropy_padded)
  if os.path.exists("./color/base.png"):
    os.remove("./color/base.png")
  mpimg.imsave(r"./color/base.png", np.squeeze(rec_image[0,:,:,:]))
  print('Base PSNR: %.4f, Coded Entropy: %.4f ' % (final_avg_psnr, final_avg_entropy))
  #print('Base PSNR: %.4f, Coded Entropy: %.4f (padded)' % (final_avg_psnr_padded, final_avg_entropy_padded))
  print('End-to-End MS-SSIM: %.4f ' % (avg_msssim))

def decompress():
  """Decompresses an image."""

  # Read the shape information and compressed string from the binary file.
  with open(args.input, "rb") as f:
    x_shape = np.frombuffer(f.read(4), dtype=np.uint16)
    y_shape = np.frombuffer(f.read(4), dtype=np.uint16)
    string = f.read()

  y_shape = [int(s) for s in y_shape] + [args.num_filters]

  # Add a batch dimension, then decompress and transform the image back.
  strings = tf.expand_dims(string, 0)
  entropy_bottleneck = tfc.EntropyBottleneck(dtype=tf.float32)
  y_hat = entropy_bottleneck.decompress(
      strings, y_shape, channels=args.num_filters)
  x_hat = synthesis_transform(y_hat, args.num_filters)

  # Remove batch dimension, and crop away any extraneous padding on the bottom
  # or right boundaries.
  x_hat = x_hat[0, :x_shape[0], :x_shape[1], :]

  # Write reconstructed image out as a PNG file.
  op = save_image(args.output, x_hat)

  # Load the latest model checkpoint, and perform the above actions.
  with tf.Session() as sess:
    latest = tf.train.latest_checkpoint(checkpoint_dir=args.checkpoint_dir)
    tf.train.Saver().restore(sess, save_path=latest)
    sess.run(op)

if __name__ == "__main__":
  parser = argparse.ArgumentParser(
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)

  parser.add_argument(
      "--conv_filters", type=int, default=48,
      help="Number of filters conv layer.")
  parser.add_argument(
      "--num_filters", type=int, default=48,
      help="Number of filters bottleneck layer.")
  parser.add_argument(
      "--checkpoint_dir", default="color/model48-lambda3000",
      help="Directory where to save/load model checkpoints.")

  args = parser.parse_args()

  compress()


import main as m
import matplotlib.pyplot as plt

bd = m.PopulationData(name_file='bd.xls')
tbl = bd[0] + bd[1] + bd[2] # Выбираем базы данных (нужные таблицы)

tbl.limit_depth(0, 350) # Указываем глубину

tbl.print_locals()
ans = int(input('Выбор локации:'))
num_loc = ans
tbl_loc = tbl.limit_local(num_loc)

kinds = tbl.get_kinds()
tbl_loc.print_kinds()
locals = tbl.get_locals()

a = int(input('Первый график:'))
b = int(input('Второй график:'))
name_graph = 'Наложение видов ' + kinds[a] + '' + kinds[b] + ' (' + locals[num_loc] + ')'

for num in [a, b]:

    name = kinds[num] + '\n' + locals[num_loc]

    tbl_kind = tbl_loc.limit_kind(num)

    res = tbl_kind.filter_columns([0, 7, 11])
    res.group_by_column([0, 1])
    res.group_date()
    print(res)
    res.plot([2], name=name, stl='--')

plt.legend()
plt.show()
# plt.savefig(name_graph)


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "T+ 3D Scene",
    "author": "MKB",
    "version": (0, 1, 0),
    "blender": (2, 78, 0),
    "location": "View3D > Shortcut [M]",
    "description": "Replacement for Move-to-Layer with Move-to-Layer and Visible Scene",
    "warning": "",
    "wiki_url": "",
    "category": "ToolPlus",
}

import bpy
from bpy import *
from bpy.props import*
from bpy.types import AddonPreferences

#Panel preferences
class TP_Panels_Preferences(AddonPreferences):
    bl_idname = __name__

    #Tab Prop
    prefs_tabs = EnumProperty(
        items=(('info',       "Info",       "Info"),
               ('url',        "URLs",       "URLs")),
               default='info')

    def draw(self, context):
        layout = self.layout

        #Info
        row= layout.row(align=True)
        row.prop(self, "prefs_tabs", expand=True)

        if self.prefs_tabs == 'info':

            box = layout.box().column(1)

            row = box.column(1)
            row.label(text="T+ 3D Scene")
            row.label(text="Replacement for Move-to-Layer [M]")
            row.label(text="include: Move-to-Layer and Visible Scene (Layer Properties)")
            row.label(text="Deactivate the Move-to-Layer Shortcut [M] in TAB INPUT")
            row.label(text="Search M with key binding > Object Mode")
            row.label(text="Saver User Setttings and restart Blender")

            row.label(text="Happy Blending! :)")

        #Weblinks
        if self.prefs_tabs == 'url':
            row = layout.column_flow(2)
            row.operator('wm.url_open', text = 'Thread', icon = 'BLENDER').url = "https://blenderartists.org/forum/showthread.php?418914-Addon-T-3D-Scene&p=3169536#post3169536"

class View3D_TP_Scene_Batch(bpy.types.Operator):
    """T+ 3D Scene :)"""
    bl_label = "T+ 3D Scene :)"
    bl_idname = "tp_batch.scene_batch"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        isModelingMode = not (
        context.sculpt_object or
        context.vertex_paint_object
        or context.weight_paint_object
        or context.image_paint_object
        or context.edit_object)
        return (context.mode == 'OBJECT' and isModelingMode)

    def draw(self, context):
        layout = self.layout.column(1)

        scene = context.scene
        layout.operator_context = 'INVOKE_REGION_WIN'

        box = layout.box().column(1)

        row = box.column(1)

        row.prop(context.object, "layers", text="Move")

        row.separator()

        row.prop(context.scene, "layers", text="Scene")

        box.separator()
        box.separator()

    def execute(self, context):
        return {'FINISHED'}

    def check(self, context):
        return True

    def invoke(self, context, event):
        dpi_value = bpy.context.user_preferences.system.dpi
        return context.window_manager.invoke_props_dialog(self, width=dpi_value*3, height=300)

# Registry
addon_keymaps = []

def register():

    bpy.utils.register_module(__name__)

    #KeyMap
    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon
    km = kc.keymaps.new(name='3D View', space_type='VIEW_3D')
    kmi = km.keymap_items.new('tp_batch.scene_batch', 'M', 'PRESS')
    kmi.active = True
    addon_keymaps.append((km, kmi))

def unregister():

    bpy.utils.unregister_module(__name__)

    #KeyMap
    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)
    addon_keymaps.clear()

if __name__ == "__main__":
    register()


import sys

import click
import textacy

from . import Content
from . import Network
from . import Qrmine
from . import ReadData
from . import Sentiment
from . import MLQRMine
from . import __version__

@click.command()
@click.option('--verbose', '-v', is_flag=True, help="Will print verbose messages.")
@click.option('--inp', '-i', multiple=True,
              help='Input file in the text format with <break>Topic</break>')
@click.option('--out', '-o', multiple=False, default='',
              help='Output file name')
@click.option('--csv', multiple=False, default='',
              help='csv file name')
@click.option('--num', '-n', multiple=False, default=3,
              help='N (clusters/epochs etc depending on context)')
@click.option('--rec', '-r', multiple=False, default=3,
              help='Record (based on context)')
@click.option('--titles', '-t', multiple=True,
              help='Document(s) or csv title(s) to analyze/compare')
@click.option('--filters', '-f', multiple=True,
              help='Filters to apply')
@click.option('--codedict', is_flag=True,
              help='Generate coding dictionary')
@click.option('--topics', is_flag=True,
              help='Generate topic model')
@click.option('--assign', is_flag=True,
              help='Assign documents to topics')
@click.option('--cat', is_flag=True,
              help='List categories of entire corpus or individual docs')
@click.option('--summary', is_flag=True,
              help='Generate summary for entire corpus or individual docs')
@click.option('--sentiment', is_flag=True,
              help='Generate sentiment score for entire corpus or individual docs')
@click.option('--sentence', is_flag=True, default=False,
              help='Generate sentence level scores when applicable')
@click.option('--nlp', is_flag=True,
              help='Generate all NLP reports')
@click.option('--nnet', is_flag=True,
              help='Display accuracy of a neural network model')
@click.option('--svm', is_flag=True,
              help='Display confusion matrix from an svm classifier')
@click.option('--knn', is_flag=True,
              help='Display nearest neighbours')
@click.option('--kmeans', is_flag=True,
              help='Display KMeans clusters')
@click.option('--cart', is_flag=True,
              help='Display Association Rules')
@click.option('--pca', is_flag=True,
              help='Display PCA')
def cli(verbose, inp, out, csv, num, rec, titles, filters, codedict, topics, assign, cat, summary, sentiment, sentence,
        nlp, nnet,
        svm,
        knn, kmeans, cart, pca):
    data = ReadData()
    if inp:
        data.read_file(inp)
    if len(filters) > 0:
        data = filter_data(inp, filters, sentence, num)
    if verbose:
        click.echo("We are in the verbose mode.")
    if out:
        sys.stdout = open(out, 'w')
    if inp and codedict:
        generate_dict(data, num)
    if inp and topics:
        generate_topics(data, assign, num)
    # if inp and assign:
    #     assign_topics(data)
    if inp and cat:
        generate_categories(data, titles, num)
    if inp and summary:
        generate_summary(data, titles)
    if inp and sentiment:
        get_sentiment(data, titles, sentence, verbose)
    if inp and cart: #python qrminer.py --cart -i src/qrmine/resources/interview.txt -n 10
        get_categories_association(data, num)
    if inp and nlp:
        main(inp)
    if csv:
        ml = MLQRMine()
        ml.csvfile = csv
        if len(titles) > 0:
            ml.titles = titles
    if csv and nnet:
        get_nnet(ml, num)
    if csv and svm:
        get_svm(ml)
    if csv and knn:
        get_knn(ml, num, rec)
    if csv and kmeans:
        get_kmeans(ml, num)
    if csv and cart:
        get_association(ml)
    if csv and pca:
        get_pca(ml, num, verbose)

"""
The following functions work on all the text sections.
"""

"""
This filters data according to search criteria

If search is empty, return entire data

If search is pos, neg or neu apply a sentiment filter

Here search is the filters applied

filters variable refers to the titles
"""

def filter_data(inp, search, sentence, num):
    data = ReadData()
    to_return = ReadData()
    data.read_file(inp)

    filters = []
    for s in search:
        if s == 'pos':
            for title in data.titles:
                t = [title]
                if get_sentiment(data, t, sentence, False) == 'pos':
                    filters.append(title)
        if s == 'neg':
            for title in data.titles:
                t = [title]
                if get_sentiment(data, t, sentence, False) == 'neg':
                    filters.append(title)
        if s == 'neu':
            for title in data.titles:
                t = [title]
                if get_sentiment(data, t, sentence, False) == 'neu':
                    filters.append(title)
        # If search itself is a title
        if any(s in l for l in data.titles):
            filters.append(s)
        # If the given category is present in the document
        for title in data.titles:
            t = [title]
            if any(s in l for l in generate_categories(data, t, num)):
                filters.append(title)

    click.echo("Selected Titles")
    for filter in filters:
        click.echo(filter)

    ct = 0
    for title in data.titles:
        if any(title in l for l in filters):
            to_return.append(title, data.documents[ct])
        ct += 1

    if len(search) > 0 and len(to_return.documents) > 0:
        click.echo("Filters applied. \n")
        return to_return
    else:
        return data

# test: test_generate_dict in test_nlp.py
def generate_dict(data, num):
    if not num:
        num = 10
    q = Qrmine()
    all_interviews = Content(data.content)
    q.print_dict(all_interviews, num)

def generate_topics(data, assign, num):
    q = Qrmine()
    q.content = data
    q.process_content()
    q.print_topics()
    if assign:
        q.print_documents(num)

# def assign_topics(data):
#     q = Qrmine()
#     q.content = data
#     q.process_content()
#     q.print_documents()

def get_categories_association(data, num):
    q = Qrmine()
    q.content = data
    click.echo(q.category_association(num))
    click.echo("Frequent Itemsets")
    click.echo("---------------------------")

"""
Function working at both levels
"""

def generate_categories(data, tags, num):
    q = Qrmine()

    if len(tags) > 0:
        ct = 0
        for title in data.titles:
            for tag in tags:
                if title == tag:
                    click.echo(tag)
                    content = data.documents[ct]
            ct += 1
        interview = Content(content)
        doc = textacy.make_spacy_doc(interview.doc)
        return q.print_categories(doc, num)

    else:
        all_interviews = Content(data.content)
        doc = textacy.make_spacy_doc(all_interviews.doc)
        return q.print_categories(doc, num)

def generate_summary(data, tags):
    if len(tags) > 0:
        ct = 0
        for title in data.titles:
            for tag in tags:
                if title == tag:
                    click.echo(tag)
                    content = data.documents[ct]
            ct += 1
        interview = Content(content)
        click.echo(" ".join(interview.generate_summary(2)))
        click.echo("_________________________________________")

    else:
        all_interviews = Content(data.content)
        click.echo(" ".join(all_interviews.generate_summary(2)))
        click.echo("_________________________________________")

"""
"""

def get_sentiment(data, tags, sentence, verbose):
    if len(tags) > 0:
        ct = 0
        for title in data.titles:
            for tag in tags:
                if title == tag:
                    click.echo(tag)
                    content = data.documents[ct]
            ct += 1
        interview = Content(content)
        doc = textacy.make_spacy_doc(interview.doc)

        ## Sentiment
        s = Sentiment()

        if sentence is True:
            for sentence in doc.sents:
                if len(sentence) > 3:
                    sent = s.sentiment_analyzer_scores(sentence.text)
                    if verbose:
                        click.echo("{:-<40} {}\n".format(sent["sentence"], str(sent["score"])))
                    click.echo(s.sentiment())

        else:
            sent = s.sentiment_analyzer_scores(doc.text)
            if verbose:
                click.echo("{:-<40} {}\n".format(sent["sentence"], str(sent["score"])))
            click.echo(s.sentiment())
        return s.sentiment()
    else:
        all_interviews = Content(data.content)
        doc = textacy.make_spacy_doc(all_interviews.doc)

        ## Sentiment
        s = Sentiment()
        if sentence is True:
            for sentence in doc.sents:
                if len(sentence) > 3:
                    sent = s.sentiment_analyzer_scores(sentence.text)
                    if verbose:
                        click.echo("{:-<40} {}\n".format(sent["sentence"], str(sent["score"])))
                    click.echo(s.sentiment())

        else:
            sent = s.sentiment_analyzer_scores(doc.text)
            if verbose:
                click.echo("{:-<40} {}\n".format(sent["sentence"], str(sent["score"])))
            click.echo(s.sentiment())
        return s.sentiment()

"""
ML
"""

def get_nnet(ml, n=3):
    ml.epochs = n
    ml.prepare_data(True)  # Oversample
    ml.get_nnet_predictions()
    click.echo("\n%s: %.2f%%" % (ml.model.metrics_names[1], ml.get_nnet_scores()[1] * 100))

def get_svm(ml):
    ml.prepare_data(True)  # Oversample
    click.echo(ml.svm_confusion_matrix())

# https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html#sklearn.neighbors.KDTree
def get_knn(ml, n=3, r=3):
    ml.prepare_data()
    knn = ml.knn_search(n, r)
    for n in knn:
        print("Records: ", n + 1)

def get_kmeans(ml, n=3):
    ml.prepare_data()
    click.echo("K-Means Clusters:")
    click.echo(ml.get_kmeans(n))

def get_association(ml):
    ml.prepare_data()
    click.echo(ml.get_apriori())

def get_pca(ml, n=3, verbose=None):
    ml.prepare_data()
    if verbose:
        click.echo(ml.head)
    click.echo(ml.get_pca(n))

def main(input_file):
    # content property returns the entire text and the documents returns the array of documents
    data = ReadData()
    data.read_file(input_file)

    q = Qrmine()
    all_interviews = Content(data.content)

    q.content = data

    ## Summary
    click.echo(" ".join(all_interviews.generate_summary(2)))
    click.echo("_________________________________________")

    doc = textacy.make_spacy_doc(all_interviews.doc)

    ## Sentiment
    s = Sentiment()
    x = []
    for sentence in doc.sents:
        if len(sentence) > 3:
            x.append(sentence.text)
            sent = s.sentiment_analyzer_scores(sentence.text)
            click.echo("{:-<40} {}\n".format(sent["sentence"], str(sent["score"])))
            click.echo("{:-<40} {}\n".format(sentence.text, str(s.similarity(sentence.text, "Dummy sentence"))))

    ## Network
    n = Network()
    click.echo(n.sents_to_network(x))
    # n.draw_graph(True)
    click.echo(n.draw_graph(False))

    q.process_content()

    q.print_categories(doc)
    q.print_topics()
    q.print_documents()
    q.print_dict(all_interviews)

def main_routine():
    click.echo("_________________________________________")
    click.echo("QRMine(TM) Qualitative Research Miner. v" + __version__)
    cli()  # run the main function

if __name__ == '__main__':
    main_routine()


'''import SecondFile
import datetime
import calendar

#from SecondFile import subject

#SecondFile.display_name("John Doe")

studentName = SecondFile.display_name
studentName("Johnny Does")

dateNow = datetime.date.today()
print(dateNow)

isLeapYear = calendar.isleap(2023)

if isLeapYear:
    print("2023 is a leap year")
else:
    print("2023 is not a leap year")'''

import tkinter as tk
from PIL import ImageTk, Image

form = tk.Tk()
form.title("Rotate Image")

imageName = "dog.jpg"
openImage = Image.open(imageName)
rotatedImage = openImage.rotate(90)

img = ImageTk.PhotoImage(rotatedImage)

labelWidget = tk.Label(form, image=img)
labelWidget.pack()

form.mainloop()


import torch
import torch.nn as nn
import FrEIA.framework as Ff
import FrEIA.modules as Fm
import torch.nn.functional as F

class cINN(nn.Module):
    '''cINN for class-conditional MNISt generation'''
    def __init__(self, opt):
        super().__init__()
        self.opt = opt
        self.cinn = self.build_inn(opt)

        self.trainable_parameters = [p for p in self.cinn.parameters() if p.requires_grad]
        for p in self.trainable_parameters:
            p.data = 0.01 * torch.randn_like(p)

    def build_inn(self, opt):

        def subnet(ch_in, ch_out):
            return nn.Sequential(nn.Linear(ch_in, 2048),
                                 nn.LeakyReLU(0.2),
                                 nn.Linear(2048, ch_out)
                                 )

        cond = Ff.ConditionNode(opt.input_dim)
        nodes = [Ff.InputNode(2048)]
        nodes.append(Ff.Node(nodes[-1], Fm.Flatten, {}))

        for k in range(opt.num_coupling_layers):
            # nodes.append(Ff.Node(nodes[-1], Fm.PermuteRandom, {'seed':k}))
            nodes.append(Ff.Node(nodes[-1], Fm.GLOWCouplingBlock,
                                 {'subnet_constructor':subnet, 'clamp':1.0},
                                 conditions=cond))

        return Ff.ReversibleGraphNet(nodes + [cond, Ff.OutputNode(nodes[-1])], verbose=False)

    def forward(self, x, c):
        z, jac = self.cinn(x, c, jac=True)
        return z, jac

    def reverse_sample(self, z, c):
        return self.cinn(z, c, rev=True, jac=False)

class LinearModule(nn.Module):
    def __init__(self, vertice, out_dim):
        super(LinearModule, self).__init__()
        self.register_buffer('vertice', vertice.clone())
        self.fc = nn.Linear(vertice.numel(), out_dim)

    def forward(self, semantic_vec):
        input_offsets = semantic_vec - self.vertice
        response = F.relu(self.fc(input_offsets))
        return response

class GSModule(nn.Module):
    def __init__(self, vertices, out_dim):
        super(GSModule, self).__init__()
        self.individuals = nn.ModuleList()
        assert vertices.dim() == 2, 'invalid shape : {:}'.format(vertices.shape)
        self.out_dim     = out_dim
        self.require_adj = False
        for i in range(vertices.shape[0]):
            layer = LinearModule(vertices[i], out_dim)
            self.individuals.append(layer)

    def forward(self, semantic_vec):
        responses = [indiv(semantic_vec) for indiv in self.individuals]
        global_semantic = sum(responses)
        return global_semantic

class RelationNet(nn.Module):
    def __init__(self, args):
        super(RelationNet, self).__init__()
        self.fc1 = nn.Linear(args.C_dim + 2048, 2048)
        self.fc2 = nn.Linear(2048, 1)

    def forward(self, s, c):

        c_ext = c.unsqueeze(0).repeat(s.shape[0], 1, 1)
        cls_num = c_ext.shape[1]

        s_ext = torch.transpose(s.unsqueeze(0).repeat(cls_num, 1, 1), 0, 1)
        relation_pairs = torch.cat((s_ext, c_ext), 2).view(-1, c.shape[1] + s.shape[1])
        relation = nn.ReLU()(self.fc1(relation_pairs))
        relation = nn.Sigmoid()(self.fc2(relation))
        return relation

class RelationNetV2(nn.Module):
    def __init__(self, args):
        super(RelationNetV2, self).__init__()
        self.fc1 = nn.Linear(args.C_dim + 2048, 2048)
        self.fc2 = nn.Linear(2048, 1)

    def forward(self, s, c):

        c_ext = c.unsqueeze(0).repeat(s.shape[0], 1, 1)
        cls_num = c_ext.shape[1]

        s_ext = torch.transpose(s.unsqueeze(0).repeat(cls_num, 1, 1), 0, 1)
        relation_pairs = torch.cat((s_ext, c_ext), 2).view(-1, c.shape[1] + s.shape[1])
        h = nn.ReLU()(self.fc1(relation_pairs))
        relation = nn.Sigmoid()(self.fc2(h))
        return relation, h

class Linear_classifier(nn.Module):
    def __init__(self, input_dim, nclass):
        super(Linear_classifier, self).__init__()
        self.fc1 = nn.Linear(input_dim, 1024)
        self.fc2 = nn.Linear(1024, nclass)
        self.logic = nn.LogSoftmax(dim=1)
    def forward(self, x):
        h = nn.ReLU()(self.fc1(x))
        o = self.logic(self.fc2(h))
        return o, h


import math

class Deformacoes():
    def __init__(self) -> None:
        pass
        """
        Calcula as deformações resultantes de tensões
        em planos inclinados"""

    def deformacaox1(self,
        deformacaox = 0,
        deformacaoy = 0,
        deformacaoxy = 0,
        angulo = 0
        ) -> dict:
        """Calcula a deformação em um plano inclinado
        x angulos"""

        dx = ((deformacaox+deformacaoy)/2
        + (deformacaox-deformacaoy)*math.cos(math.radians(2*angulo))/2
        + deformacaoxy*math.sin(math.radians(2*angulo))/2)

        resultados = {
            'Deformação em x':format(dx,'.3E')
        }

        return resultados

    def deformacaoy1(self,dx,dy,dx1=0,ang = 0) -> dict:
        """Calcula a deformação em y no plano
        inclinado"""

        dy = dx+dy-dx1

        return {'A deformação em y é':format(dy,'.3E')}

    def deformacaox1y1(self,
        deformacaox,
        deformacaoy,
        deformacaoxy,
        angulo) -> dict:
        """Calcula a deformação de cisalhamento no plano
        inclinado"""

        dxy = 2*((deformacaoy-deformacaox)*math.sin(
        math.radians(2*angulo)
        )/2
        +deformacaoxy*math.cos(math.radians(2*angulo))/2)

        return {'Deformação de cisalhamento':
            format(dxy,'.3E')}

    def deformacoesprincipais(self,
        dx,
        dy,
        dxy) -> dict:
        """Define as deformações principais
        no plano inclinado"""

        df1 = ((dx+dy)/2+math.sqrt((
            math.pow((dx-dy)/2,2) + math.pow(dxy/2,2)
        )))

        df2 = dx+dy-df1

        planp = math.atan(dxy/(dx-dy))/2

        dfmax = max(df1,df2)
        dfmin = min(df1,df2)

        return {
            'Deformação fletora máxima': format(dfmax,'.3E'),
            'Deformação fletora mínima':
                format(dfmin,'.3E'),
            'Ângulo do plano principal':
                math.degrees(planp)
        }

    def cisalhamentoprincipal(self,
        dx,
        dy,
        dxy) -> dict:
        """Define as deformações no plano de
        cisalhamento principal"""

        dxymax = 2*math.sqrt(
            math.pow((dx-dy)/2,2) + math.pow(dxy/2,2)
        )

        #Cálculo da tensão média normal no plano
        dmed = (dx+dy)/2

        #Calculo do ângulo do plano
        if dxy:
            planp = math.atan((dx-dy)/dxy)/2
        if not dxy:
            a = Deformacoes.deformacoesprincipais(self,dx,dy,dxy)
            ang = a['Ângulo do plano principal']
            t1 = ang+45
            t2 = ang-45

            c = Deformacoes.deformacaox1y1(self,dx,dy,dxy,t1)
            d = Deformacoes.deformacaox1y1(self,dx,dy,dxy,t2)

            def1 = c['Deformação de cisalhamento']
            def2 = d['Deformação de cisalhamento']

            planp = float(max(def1,def2))

        return {
            'Deformação de cisalhamento máxima': format(
                dxymax,'.3E'
            ),
            'Deformação média': format(dmed,'.3E'),
            'Plano principal de cisalhamento':
            math.degrees(planp)

        }

    def defpoisson(self,
        dx,dy,v) -> dict:
        """Calcula as deformações levando em consideração
        o coeficiente de poisson"""

        dfx = dx - v*dy
        dfy = dy - v*dx
        dfz = v*(dx+dy)

        return {
            'Deformação em x': format(dfx,'.2E'),
            'Deformação em y': format(dfy,'.2E'),
            'Deformação em z': format(dfz,'.2E')
        }

    def poisson(self,dx,dy,tx,ty) -> float:
        """Define o coeficiente de Poisson a partir
        das deformações e tensões do elemento"""

        v = (ty*dx-tx*dy)/(tx*dx-ty*dy)

        return v

    def elasticidade(self,ty,tx,v=0,dx=0,dy=0) -> float:
        """Define a elasticidade a partir do coeficiente
        de Poisson"""
        try:
            if v:
                if dy:
                    e = (ty-v*tx)/dy
                if dx:
                    e = (tx-v*ty)/dx
            if not v:
                v = Deformacoes.poisson(self,dx,dy,tx,ty)
                e = (ty-v*tx)/dy
            return e
        except:
            return print('Não foi possível calcular, provavelmente '
            'você não digitou o coeficiente ou algum outro'
            ' parâmetro')

    def tensoes(self, dy,elasticidade,
        v,dx,) -> float:
        """Define a deformação em um elemento a partir da
        deformação que ele apresenta"""

        tx = (dy*elasticidade*v+dx*elasticidade)/(1-v**2)

        ty = dy*elasticidade + v*tx

        return tx,ty


# 434. 字符串中的单词数
# 统计字符串中的单词个数，这里的单词指的是连续的不是空格的字符。

# 请注意，你可以假定字符串里不包括任何不可打印的字符。

class Solution:
    def countSegments(self, s: str) -> int:
        return len(s.split())

class Solution2:
    def countSegments(self, s: str) -> int:
        s+=" "
        n = len(s)
        res=0
        for i in range(1,n):
            if s[i]==" " and s[i-1] != " ":
                res+=1
        return res
sol = Solution()
s=", , , ,        a, eaefa"
print(sol.countSegments(s))


class Conic(object):
    """ The class that creates a Conic like the format::

            a x2 + 2 h x y + b y2 + 2 g x + 2 f y + c = 0

    Only `a`, `h` and `g` are needed. rest is optional. They are set to zero by default."""

    def __init__(self, a: float, h: float, b: float, f: float = 0, g: float = 0, c: float = 0) -> None:
        self.c = c
        self.g = g
        self.f = f
        self.a = a
        self.h = h
        self.b = b

    def __str__(self) -> str:
        return '{0.a} x2 + {1} x y + {0.b} y2 + {2} x + {3} y + {0.c} = 0'.format(self, 2 * self.h, 2 * self.g,
                                                                                2 * self.f)

    @classmethod
    def from_str(cls, string: str, *, delimiter: str = ' ') -> object:
        """
        ```This method is used as an alternative constractor of Conic```

        :arg:
            string: in the format "a h b g f c". space in between.
            delimiter: takes the delimiter of the string. if not provided, defaults to ' '.

        :return: Returns an Object of the class ``Conic``.

        """
        args = string.split(delimiter)
        args = filter(lambda x: x is not '', args)
        try:
            args = map(lambda x: float(x), args)
            klass = cls(*args)

        except ValueError as exc:
            print('Error: ', exc)
            print('Please Check Your Input')
            raise

        return klass

class Line2D(object):
    """
    Class Straight Line that constracts a straight line in 2D
    """

    def __init__(self, m: float, c: float) -> None:
        self.c = c
        self.m = m

    @classmethod
    def from_intersection(cls, x: float, y: float) -> object:
        """
        Takes the x and y axis intercept and returns a Line2D object. It is used as an Alternative
        Constructor.

            Y / b + X / a = 1
        ->  Y / b = 1 - X/a
        ->  Y  =  b - (b / a) X

        :param x: the X axis intercept
        :param y: the Y axis intercept
        :return: returns a Line2D object
        """
        m = -y / x
        c = y

        return cls(m, c)

    def get_intersection(self):
        if self.c == 0:
            return 0, 0

        i_x = -self.m / self.c
        i_y = 1 / self.c

        return i_x, i_y

    def __mul__(self, other):
        a = self.m * other.m
        h = - self.m - other.m
        b = 1

if __name__ == '__main__':
    conic1 = Conic(1, 2, 1)
    conic2 = Conic.from_str("1 2 3")
    print(conic1)
    print(conic2)


'''
Contains constant variables
'''

from lib import gconstants

FRIENDLY_FULLNAME =  gconstants.AGENT_INIT_FULLNAME # ""Banana Cluster Control Agent Daemon Init Control"
SHORT_NAME = gconstants.AGENT_INIT_NAME # "bccagent"
DAEMON_NAME = gconstants.AGENT_DAEMON_FULLNAME # "Banana Cluster Control Daemon"
#
VERSION = gconstants.VERSION
CONFIG_EXT = gconstants.CONFIG_EXT # "ini"
CONFIG_DIR = gconstants.CONFIG_DIR # "config"
#
CFG_SECT_INTERNAL = gconstants.AGENT_INIT_NAME # "bccagent"
LOGGING_NAME = gconstants.LOGGING_NAME # "console"
#
STATE_ON = "RUNNING"
STATE_OFF = "SHUTDOWN"
STATE_BUSY_ON = "BUSY"


# https://gist.github.com/samson-wang/a6073c18f2adf16e0ab5fb95b53db3e6
def get_grad(model,feats=feats):
     #device = model.device
     device = 'cuda'
     model.eval()
     ref = torch.ones((1,3,224,224)).to(device).float().requires_grad_(
 True)
     if ref.grad is not None:
         ref.grad.zero_()
     dummy_out = model(ref)
     loss = feats[0][...,3,3].sum()
     loss.backward()
     g = ref.grad
     g1 = (g!=0).float()
     print(g1.mean())
get_grad(model)
feats = []
def get_feats(self,inp,out,feats=feats):
    feats.insert(0,out)
model.layer4.register_forward_hook(get_feats)


def longestPalindrome( s: str) -> str:
    n, max_len, ans = len(s), 0, ''
    def expand_around_center(l, r):
        if r < n and s[l] != s[r]:
            return '' # Index out of range or elements unequal(for even sized palindromes) thus return empty string
        while l >= 0 and r < n and s[l] == s[r]: # Till the s[l], s[r] elements are in range and same, the palindrome continues to grow
            l, r = l - 1, r + 1
        return s[l + 1:r] # Return the palindrome formed
    for i in range(n):
        a, b = expand_around_center(i, i), expand_around_center(i, i + 1) # (i,i) for odd and (i,i+1) for even sized palindromes
        main = a if len(a) > len(b) else b # Check which one of a, b is larger
        if len(main) > max_len: # Check if palindrome with i as center is larger than previous entries then update if necessary
            max_len, ans = len(main), main
    return ans

if __name__ == '__main__':

    lst = "babad"
    print("longest palindromic is: ",  longestPalindrome(lst))


import pandas as pd
import numpy as np
import time
from sklearn.model_selection import train_test_split

import sys
sys.path.append("..")
transactions = pd.read_csv('./assets/ratings_Beauty.csv',names=['UserId','ProductId',], header=None)
data = pd.melt(transactions.set_index('UserId')['ProductId'].apply(pd.Series).reset_index(),
             id_vars=['UserId'],
             value_name='ProductId') \
    .dropna().drop(['variable'], axis=1) \
    .groupby(['UserId', 'ProductId']) \
    .agg({'ProductId': 'count'}) \
    .rename(columns={'ProductId': 'purchase_count'}) \
    .reset_index() \
    .rename(columns={'ProductId': 'productId'})

data['productId'] = data['productId'].astype(np.int64)


#Código basado en la implementación de https://medium.com/100-days-of-algorithms/day-75-merkles-puzzles-d9f0e8f9c9d0
from os import urandom
from hashlib import sha1
from random import shuffle,choice
print("El numero de puzzles es 2^n")
puzzle_size=int(input("Por favor ingrese el numero n  (de preferencia 16): "))
puzzle_size = 2 ** 16

def merkles_puzzle():
    secrets = [None] * puzzle_size
    puzzles = [None] * puzzle_size

    for i in range(puzzle_size):
        # generate secret
        secrets[i] = urandom(16)

        # pair := secret|index
        pair = secrets[i] + int.to_bytes(i, 4, 'big')
        # plaintext := pair|sha1(pair)
        plaintext = pair + sha1(pair).digest()

        # cipthertext := ENCRYPT(plaintext, key)
        key = urandom(10)
        noise = sha1(key).digest()
        noise += sha1(noise).digest()
        ciphertext = bytes(i ^ j for i, j in zip(plaintext, noise))

        # puzzle := ciphertext|key
        puzzles[i] = ciphertext + key[2:]

    # randomize order
    shuffle(puzzles)

    # return
    return secrets, puzzles

def solve_puzzle(puzzle):
    ciphertext = puzzle[:40]
    key = puzzle[40:]

    for i in range(puzzle_size):
        # guess key
        noise = sha1(int.to_bytes(i, 2, 'big') + key).digest()
        noise += sha1(noise).digest()

        # plaintext := DECRYPT(ciphertext, key)
        plaintext = bytes(i ^ j for i, j in zip(ciphertext, noise))

        # pair|digest := key|index|sha1(pair)
        pair = plaintext[:20]
        digest = plaintext[20:]

        # on match: time, key, index
        if sha1(pair).digest() == digest:
            return i, pair[:16], int.from_bytes(pair[16:], 'big')

print("Alice genera los puzzles y los secretos")
secretos,puzzles=merkles_puzzle()

print("Bob decodifica algun puzzle random")
tiempoBob,secretoBob,indice=solve_puzzle(choice(puzzles))

print("Bob obtuvo el siguiente secreto:",secretoBob,",con el indice:",indice,", en",tiempoBob,"pasos")
print("Con el indice devuelto por bob, alice obtiene el siguiente secreto:",secretos[indice])


import re
import pandas as pd
import numpy as np

def parse_txt_to_csv(txtfile):
    parallel_time_table = {i: [np.nan]*10 for i in range(1, 21)}
    speedup_table = {i: [np.nan]*10 for i in range(1, 21)}
    efficiency_table = {i: [np.nan]*10 for i in range(1, 21)}
    sequential_time_table = {1: [np.nan]*10}
    parallel_approximation_table = {i: [np.nan]*10 for i in range(1, 21)}
    sequential_approximation_table = {1: [np.nan]*10}

    with open(txtfile, 'r') as file:
        for line in file:
            if "Hilo" in line:
                brackets = re.findall(r'\[(.*?)\]', line)
                if len(brackets) >= 2:
                    thread = int(brackets[0])
                    iteration = int(brackets[1]) - 1
                    value = float(re.findall(r'[-+]?\d*\.\d+|\d+', line)[-1])
                    if "Tiempo de ejecucion paralelo" in line:
                        parallel_time_table[thread][iteration] = value
                    elif "Speedup" in line:
                        speedup_table[thread][iteration] = value
                    elif "Eficiencia" in line:
                        efficiency_table[thread][iteration] = value
                    elif "Aproximacion paralela de pi" in line:
                        parallel_approximation_table[thread][iteration] = value
            elif "Tiempo de ejecucion secuencial" in line:
                brackets = re.findall(r'\[(.*?)\]', line)
                if brackets:
                    iteration = int(brackets[0]) - 1
                    value = float(re.findall(r'[-+]?\d*\.\d+|\d+', line)[-1])
                    sequential_time_table[1][iteration] = value
            elif "Aproximacion secuencial de pi" in line:
                brackets = re.findall(r'\[(.*?)\]', line)
                if brackets:
                    iteration = int(brackets[0]) - 1
                    value = float(re.findall(r'[-+]?\d*\.\d+|\d+', line)[-1])
                    sequential_approximation_table[1][iteration] = value

    parallel_time_df = pd.DataFrame(parallel_time_table).T
    parallel_time_df.index = ['Hilo ' + str(i) for i in parallel_time_df.index]
    parallel_time_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    speedup_df = pd.DataFrame(speedup_table).T
    speedup_df.index = ['Hilo ' + str(i) for i in speedup_df.index]
    speedup_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    efficiency_df = pd.DataFrame(efficiency_table).T
    efficiency_df.index = ['Hilo ' + str(i) for i in efficiency_df.index]
    efficiency_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    sequential_time_df = pd.DataFrame(sequential_time_table).T
    sequential_time_df.index = ['Hilo ' + str(i) for i in sequential_time_df.index]
    sequential_time_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    parallel_approximation_df = pd.DataFrame(parallel_approximation_table).T
    parallel_approximation_df.index = ['Hilo ' + str(i) for i in parallel_approximation_df.index]
    parallel_approximation_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    sequential_approximation_df = pd.DataFrame(sequential_approximation_table).T
    sequential_approximation_df.index = ['Hilo ' + str(i) for i in sequential_approximation_df.index]
    sequential_approximation_df.columns = ['Iteración ' + str(i) for i in range(1, 11)]

    with pd.ExcelWriter('output.xlsx') as writer:
        parallel_time_df.to_excel(writer, sheet_name='Tiempo Paralelo')
        speedup_df.to_excel(writer, sheet_name='Speedup')
        efficiency_df.to_excel(writer, sheet_name='Eficiencia')
        sequential_time_df.to_excel(writer, sheet_name='Tiempo Secuencial')
        parallel_approximation_df.to_excel(writer, sheet_name='Aproximación Paralela de pi')
        sequential_approximation_df.to_excel(writer, sheet_name='Aproximación Secuencial de pi')

parse_txt_to_csv('output.txt')


from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.cross_validation import LeaveOneOut, cross_val_score
from sklearn import preprocessing
from sklearn.cross_validation import KFold

parameter_candidates = [
            {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
            {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
        ]

class svm():

    def fit(self):
        df = pd.read_csv('Datasetnew.csv',header=None)
        h=np.asarray(df)
        dataset = np.nan_to_num(h)
        XX = dataset[:,1:65]
        y = dataset[:,0]
        X = preprocessing.normalize(XX)
        loo = LeaveOneOut(len(y))
        correct_1 = 0
        correct_0 = 0
        wrong = 0
        for train, test in loo:
        	X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]
        	clf = GridSearchCV(estimator=SVC(), param_grid=parameter_candidates, n_jobs=-1)
        	clf.fit(X_train, y_train)
        	predict = clf.predict(X_test)
        	cnf_matrix_mnb = confusion_matrix(y_test, predict)
        	if (predict == 1 and y_test ==1):
        		correct_1 = correct_1 + 1
        	elif(predict == 0 and y_test == 0):
        		correct_0 = correct_0 + 1
        	else:
        		wrong = wrong + 1
        print()
        print("correct_1 %s" %correct_1)
        print("correct_0 %s" %correct_0)
        print("wrong %s" %wrong)

        	#print(cnf_matrix_mnb)

svm().fit()

#cnf_matrix_mnb = confusion_matrix(y_test, predict)
#print(P)
'''print(predict)
print(cnf_matrix_mnb)

clf = GridSearchCV(estimator=svm.SVC(), param_grid=parameter_candidates, n_jobs=-1)
estimator = clf.fit(X, Y)
cv = LeaveOneOut(len(Y))
scores = cross_val_score(estimator, X, Y, cv = cv)
print(scores)
cnf_matrix_mnb = confusion_matrix(Y, scores)
print('Best score for data1:', clf.best_score_)
print(cnf_matrix_mnb)'''
#print("Mean score: {0:.3f} (+/-{1:.3f})").format(np.mean(scores), sem(scores))

#print(X1)


#!/usr/bin/python3
import pandas as pd
import requests
import numpy as np
import os
from nsetools import Nse
from datetime import timezone
from datetime import date
from datetime import datetime,timedelta
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from statistics import mean
import random

class stock_analsys:
    global_constants = {}
    #this tolerance is for verifying if the candle length and the candle body length are close....test for MARUBOZU
    global_constants['ratio_MARUBOZU'] = 0.9
    global_constants['ratio_DOJI'] = 0.3
    global_constants['ratio_MEAN'] = 0.9
    global_constants['ratio_trend_REV'] = 3.
    global_constants['trend_days'] = 20
    global_constants['curve_fit_poly_degree'] = 5
    global_constants['prev_trend_days'] = [4,8,11]
    global_constants['supp_res_days'] = 50 #number of days to be considered for finding the support resistance
    global_constants['num_days_prev_vol'] = 10
    global_out_dict = {}

    def __init__(self,symbs,delta_days=500):
        self.make_plots = False
        self.ff = 'poly10'
        self.fitting_funcs = {'poly2':self.poly2,'poly3':self.poly3,'poly4':self.poly4,'poly5':self.poly5,'expo':self.expo,'poly6':self.poly6,'poly7':self.poly7,'poly8':self.poly8,'poly9':self.poly9,'poly10':self.poly10,'poly11':self.poly11,'poly12':self.poly12,'poly13':self.poly13,'sin_mix':self.sin_mix}
        self.delta_days = delta_days
        self.stocks = []
        self.marubozu = []
        self.engulf = []
        self.harami = []
        self.doji = []
        self.reversal = []
        self.trend = {}
        self.supp = []
        self.resis = []
        self.vol = []
        for i in self.global_constants['prev_trend_days']:
            self.trend['TREND'+str(i)] = []
        self.symbs = symbs
        self.multi_stock()

    def single_stock(self,stock):
        self.make_plots = True
        self.stock_name = stock
        self.yahoo_fetch_history()
        self.process_data_all()
        self.analyze_candleS()
        self.find_trend()

    def multi_stock(self):
        self.TREND = {}
        iCount = 0
        for key in self.symbs:
            for stock in self.symbs[key]:
                iCount += 1
                print(stock)
                self.MARUBOZU = 'FALSE'
                self.ENGULF = 'FALSE'
                self.DOJI = 'FALSE'
                self.REVSERSAL = 'FALSE'
                self.HARAMI = 'FALSE'
                self.VOL = 'FALSE'
                for i in self.global_constants['prev_trend_days']:
                    self.TREND['TREND'+str(i)] = []

                self.stock_name = stock
                self.yahoo_fetch_history()
                self.process_data_all()
                self.analyze_candleS()
                self.find_trend()

                self.stocks.append(stock)
                self.marubozu.append(self.MARUBOZU)
                self.engulf.append(self.ENGULF)
                self.doji.append(self.DOJI)
                self.harami.append(self.HARAMI)
                self.reversal.append(self.REVSERSAL)
                self.vol.append(self.VOL)
                for i in self.global_constants['prev_trend_days']:
                    self.trend['TREND'+str(i)].extend(self.TREND['TREND'+str(i)])

        self.global_out_dict['STOCK'] = self.stocks
        self.global_out_dict['MARUBOZU'] = self.marubozu
        self.global_out_dict['DOJI'] = self.doji
        for i in self.global_constants['prev_trend_days']:
            self.global_out_dict['TREND'+str(i)] = self.trend['TREND'+str(i)]
        self.global_out_dict['TREND_REVERSAL'] = self.reversal
        self.global_out_dict['ENGULF'] = self.engulf
        self.global_out_dict['HARAMI'] = self.harami
        #self.global_out_dict['SUPPORT'] = self.supp
        #self.global_out_dict['RESISTANCE'] = self.resis
        self.global_out_dict['GOOD volume'] = self.vol
        self.df = pd.DataFrame(self.global_out_dict)
        self.df.to_csv(os.getcwd()+'/OUT.csv')

    def yahoo_fetch_history(self):
        now = datetime.now()
        past = now - timedelta(days = self.delta_days)
        period1 = int(datetime.timestamp(past))
        period2 = int(datetime.timestamp(now))
        url = 'https://query1.finance.yahoo.com/v7/finance/download/'+self.stock_name+'.NS'
        url += '?period1='+str(period1)+'&period2='+str(period2)+'&interval=1d&events=history&includeAdjustedClose=true'
        r = requests.get(url, allow_redirects=False)
        with open(os.getcwd()+'/dat.csv', 'wb') as f:f.write(r.content)
        #reading into temp ff to remove "null" rows and then write back to dat.csv
        ff = pd.read_csv('dat.csv')
        ff = ff.dropna()
        ff.to_csv(os.getcwd()+'/dat.csv')
        self.dat = pd.read_csv('dat.csv')

    def process_data_all(self):
        self.dat['candle_len'] = (self.dat['High']-self.dat['Low']).to_list()
        #in case of DOJI candle we assign 0.001 as a very small body length...to avoid any DIV error!
        self.dat['body_len'] = list(map(lambda x: abs(x) if x!=0.0 else 0.001,(self.dat['Close']-self.dat['Open']).to_list()))
        self.dat['body_mean'] = [abs(x) for x in ((self.dat['Close']+self.dat['Open'])*.5).to_list()]
        self.dat['open_close_diff'] = (self.dat['Close'] - self.dat['Open']).to_list()
        self.dat['ratio_bodylen_cndlen'] = (self.dat['body_len']/self.dat['candle_len']).to_list()
        self.dat['upper_wick_len'] = list(map(lambda hi,clos,opn,diff: hi-clos if diff>0.0 else hi-opn,self.dat['High'],self.dat['Close'],self.dat['Open'],self.dat['open_close_diff']))
        self.dat['lower_wick_len'] = list(map(lambda low,clos,opn,diff: opn-low if diff>0.0 else clos-low,self.dat['Low'],self.dat['Close'],self.dat['Open'],self.dat['open_close_diff']))

    def create_bins(self,lb,ub,bins):
        print(type(lb))
        bins = []
        width = ((ub-lb)/bins)
        for low in range(lb, lb + bins*width + 1, width):
            bins.append((low, low+width))
        bins2 = pd.IntervalIndex.from_tuples(bins)
        return bins2

    def analyze_candleS(self):
        now = -1
        prev = now -1

        supp_res_data_frame = self.dat.iloc[-70:,:]

        #supp_res_data_frame['supp_bins'] = pd.qcut(supp_res_data_frame['Low'],q=5,precision=0)
        supp_res_data_frame['supp_bins'] = pd.cut(supp_res_data_frame['Low'].to_list(),bins=5,right=False)
        #supp_res_data_frame['supp_bins'].value_counts().plot(kind='barh')

        #print(supp_res_data_frame)
        #print(supp_res_data_frame['supp_bins'].value_counts())

        #to avoid DIV error
        if(self.dat['lower_wick_len'].to_list()[now]>0):
            lower_wick_len = self.dat['lower_wick_len'].to_list()[now]
        else:
            lower_wick_len = .1

        marubozu_cond1 = self.dat['ratio_bodylen_cndlen'].to_list()[now]>self.global_constants['ratio_MARUBOZU']
        engulf_cond1 = (self.dat['Low'].to_list()[now]/self.dat['Low'].to_list()[prev])<=1.#Current Low shld be lower than prev Low
        engulf_cond2 = (self.dat['High'].to_list()[now]/self.dat['High'].to_list()[prev])>=1.#Curn high > Prev high
        engulf_cond3 = (self.dat['body_len'].to_list()[now]/self.dat['body_len'].to_list()[prev])>1.#

        doji_cond1 = self.dat['ratio_bodylen_cndlen'].to_list()[now]<self.global_constants['ratio_DOJI']
        doji_cond2 = self.dat['upper_wick_len'].to_list()[now]/lower_wick_len>self.global_constants['ratio_MEAN']
        trend_cond1 = self.dat['upper_wick_len'].to_list()[now]/lower_wick_len>self.global_constants['ratio_trend_REV']
        trend_cond2 = self.dat['lower_wick_len'].to_list()[now]/lower_wick_len>self.global_constants['ratio_trend_REV']

        #checking if the Curr vol > avg of the last 10 days volume
        good_volumes = self.dat['Volume'].to_list()[now]>mean(self.dat['Volume'].to_list()[-self.global_constants['num_days_prev_vol']:-1])

        harami_cond1 = (self.dat['body_len'].to_list()[now]/self.dat['body_len'].to_list()[prev])<1.
        #Curr body len<Prev body len
        if(self.dat['open_close_diff'].to_list()[prev]>0):
            harami_cond2 =(self.dat['Open'].to_list()[prev]<self.dat['body_mean'].to_list()[now]<self.dat['Close'].to_list()[prev])
        else:
            harami_cond2 =(self.dat['Close'].to_list()[prev]<self.dat['body_mean'].to_list()[now]<self.dat['Open'].to_list()[prev])

        if(marubozu_cond1):
            self.MARUBOZU = 'TRUE'
        if(engulf_cond1 and engulf_cond2 and engulf_cond3):
            self.ENGULF = 'TRUE'
        if(doji_cond1 and doji_cond2):
            self.DOJI = 'TRUE'
        if((trend_cond1 or trend_cond2) and doji_cond1):
            self.REVSERSAL = 'TRUE'
        if(harami_cond1 and harami_cond2):
            self.HARAMI = 'TRUE'
        if(good_volumes):
            self.VOL = 'TRUE'

    #https://machinelearningmastery.com/curve-fitting-with-python/
    def find_trend(self):
        #print(self.stock_name)
        high_price = self.dat["High"].to_list()
        low_price = self.dat["Low"].to_list()
        high_price = high_price[-int(self.global_constants['trend_days']):-1]
        low_price = low_price[-int(self.global_constants['trend_days']):-1]
        mean_values = list(map(lambda x,y: (x+y)/2.,high_price,low_price))
        x_data = np.arange(1,int(self.global_constants['trend_days']),1)
        if(len(mean_values)!=0):
            popt, _ = curve_fit(self.fitting_funcs[self.ff],x_data,mean_values)
            mean_fitted = self.fitting_funcs[self.ff](x_data,*popt)
            if(self.make_plots):
                plt.plot(x_data,mean_values,'--b')
                plt.plot(x_data,mean_fitted,'-r')
                plt.show()
            for i in self.global_constants['prev_trend_days']:
                x_tick = self.global_constants['trend_days']-i
                mean_func_left_intrvl = self.fitting_funcs[self.ff](x_data[x_tick],*popt)
                mean_func_right_intrvl = self.fitting_funcs[self.ff](x_data[-1],*popt)
                mean_slope = (mean_func_right_intrvl-mean_func_left_intrvl)/i
                #print(mean_func_left_intrvl)
                #print(mean_func_right_intrvl)
                #print(mean_slope)
                if(mean_slope>0.0):
                    self.trend['TREND'+str(i)].append('BULLISH')
                else:
                    self.trend['TREND'+str(i)].append('BEARISH')
        else:
            for i in self.global_constants['prev_trend_days']:
                self.trend['TREND'+str(i)].append('UNKOWN')
    def sin_mix(self,x, a, b, c, d):
	    return a * np.sin(b - x) + c * x**2 + d
    def expo(self,x, a, b, c):
	    return a * np.exp (-b * x) + c
    def poly2(self,x, a, b, c):
	    return (a * x) + (b * x**2) + c
    def poly3(self,x, a, b, c, d):
	    return (a * x) + (b * x**2) + (c * x**3) + d
    def poly4(self,x, a, b, c, d, e):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + e
    def poly5(self,x, a, b, c, d, e, f):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + f
    def poly6(self,x, a, b, c, d, e, f,g):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + g
    def poly7(self,x, a, b, c, d, e, f,g,h):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) +h
    def poly8(self,x, a, b, c, d, e, f,g,h,i):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) +i
    def poly9(self,x, a, b, c, d, e, f,g,h,i,j):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) + (i * x**9) + j
    def poly10(self,x, a, b, c, d, e, f,g,h,i,j,k):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) + (i * x**9) + (j * x**10) + k
    def poly11(self,x, a, b, c, d, e, f,g,h,i,j,k,l):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) + (i * x**9) + (j * x**10) + (k * x**11) + l
    def poly12(self,x, a, b, c, d, e, f,g,h,i,j,k,l,m):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) + (i * x**9) + (j * x**10) + (k * x**11) + (l * x**12) + m
    def poly13(self,x, a, b, c, d, e, f,g,h,i,j,k,l,m,n):
	    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + (f * x**6) + (g * x**7) + (h * x**8) + (i * x**9) + (j * x**10) + (k * x**11) + (l * x**12) + (m * x**13) + n

    def test_func(self):
        rnd = random.sample(range(1, 50), 10)
        rnd.append(1000)
        rnd.append(300)
        rnd.append(500)
        rnd.append(700)
        xx = pd.cut(rnd,bins=3)
        print(rnd)
        print(xx.value_counts())

stock_symbols = {}
stock_symbols['NIFTY F&O'] = pd.read_csv('sos_scheme.csv')['Symbol'].to_list()
cls_instance = stock_analsys(stock_symbols)
#cls_instance.single_stock('IOC')
#cls_instance.single_stock('DRREDDY')
#cls_instance.test_func()

#stock_symbols['NIFTY auto'] = pd.read_csv('ind_niftyautolist.csv')['Symbol'].to_list()
#stock_symbols['NIFTY bank'] = pd.read_csv('ind_niftybanklist.csv')['Symbol'].to_list()
#stock_symbols['NIFTY it'] = pd.read_csv('ind_niftyitlist.csv')['Symbol'].to_list()
#stock_symbols['NIFTY metal'] = pd.read_csv('ind_niftymetallist.csv')['Symbol'].to_list()
#stock_symbols['NIFTY pharma'] = pd.read_csv('ind_niftypharmalist.csv')['Symbol'].to_list()
#stock_symbols['NIFTY oilGas'] = pd.read_csv('ind_niftyoilgaslist.csv')['Symbol'].to_list()
#cls_instance.single_stock('KOTAKBANK')
#cls_instance.single_stock('RELIANCE')
#nse = Nse()
#ll = nse.get_index_list()
#ll = nse.get_index_quote("nifty it")