__author__ = 'Ronak'

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def allPossibleFBT(self, N):
        """
        :type N: int
        :rtype: List[TreeNode]
        """
        if N == 1:
            return [TreeNode(0)]

        nodes = []
        for i in range(1, N-1,2):
            for left in self.allPossibleFBT(i):
                for right in self.allPossibleFBT(N-1-i):
                    root = TreeNode(0)
                    root.left, root.right = left, right
                    nodes.append(root)
        return nodes

if __name__ == "__main__":
    obj = Solution()
    print(obj.allPossibleFBT(7))


from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

import regras_de_uso

app = FastAPI()

@app.get("/")
async def bem_vinda():
    site = "Seja bem vinda"
    return site.replace('\n', '')

###################################################################################
# Classes
# Classe representando os dados do usuário
class Usuario(BaseModel):
    #def __init__(self, id, nome, email, senha):
    id: int
    nome: str
    email: str
    senha: str

# Classe representando os dados do cliente
class Endereco(BaseModel):
    rua: str
    cep: str
    cidade: str
    estado: str

# Classe representando a lista de endereços de um cliente (Não usei ainda..)
class ListaDeEnderecosDoUsuario(BaseModel):
    usuario: Usuario
    enderecos: List[Endereco] = []

# Classe representando os dados do produto
class Produto(BaseModel):
    id: int
    nome: str
    descricao: str
    preco: float

# Classe representando o carrinho de compras de um cliente com uma lista de produtos
class CarrinhoDeCompras(BaseModel):
    id_usuario: int
    id_produtos: List[Produto] = ()
    preco_total: float
    quantidade_de_produtos: int

###################################################################################
#ok Criar um usuário,
#ok se tiver outro usuário com o mesmo ID retornar falha,
#ok se o email não tiver o @ retornar falha,
#ok senha tem que ser maior ou igual a 3 caracteres,
#ok senão retornar OK
@app.post("/usuario/")
async def criar_usuario(usuario: Usuario):
    print(usuario.dict())
    novo_user = regras_de_uso.regras_usuario_cadastrar(usuario.dict())

    return novo_user

###################################################################################
# Se o id do usuário existir, retornar os dados do usuário
# senão retornar falha
@app.get("/usuario/{id}")
async def retornar_usuario(id: int):
    dados_usuario = regras_de_uso.regras_id_usuario(id)

    return dados_usuario

##################################################################################
# Se existir um usuário com exatamente o mesmo nome, retornar os dados do usuário
# senão retornar falha
@app.get("/usuario/nome/{nome}")
async def retornar_usuario_com_nome(nome: str):
    print(nome)
    mesmo_usuario = regras_de_uso.regras_nome_usuario(nome)
    print(mesmo_usuario)

    return mesmo_usuario

#################################################################################
# Se o id do usuário existir, deletar o usuário e retornar OK
# senão retornar falha
# ao deletar o usuário, deletar também endereços e carrinhos vinculados a ele
@app.delete("/usuario/{id}")
async def deletar_usuario(id: int):
    dados_usuario_apaga = regras_de_uso.regras_id_usuario_delete(id)

    return dados_usuario_apaga

#################################################################################
# Se não existir usuário com o id_usuario retornar falha,
# senão retornar uma lista de todos os endereços vinculados ao usuário
# caso o usuário não possua nenhum endereço vinculado a ele, retornar
# uma lista vazia
### Estudar sobre Path Params (https://fastapi.tiangolo.com/tutorial/path-params/)
@app.get("/usuario/{id_usuario}/endereços/")
async def retornar_enderecos_do_usuario(id_usuario: int):
    endereço_usuario = regras_de_uso.regras_endereco_usuario(id_usuario)

    return endereço_usuario

#################################################################################
# Retornar todos os emails que possuem o mesmo domínio
# (domínio do email é tudo que vêm depois do @)
# senão retornar falha
@app.get("/usuarios/emails/{dominio}")
async def retornar_emails(dominio: str):
    email_database = regras_de_uso.regras_email_database(dominio)

    return email_database

##################################################################################
# Se não existir usuário com o id_usuario retornar falha,
# senão cria um endereço, vincula ao usuário e retornar OK
@app.post("/endereco/{id_usuario}")
async def criar_endereco(endereco: Endereco, id_usuario: int):
    cria_endereco_id_usuario = \
        regras_de_uso.regras_cria_endereco_usuario(endereco.dict(), id_usuario)

    return cria_endereco_id_usuario

##################################################################################
# Se não existir endereço com o id_endereco retornar falha,
# senão deleta endereço correspondente ao id_endereco e retornar OK
# (lembrar de desvincular o endereço ao usuário)
@app.delete("/endereco/{id_endereco}")
async def deletar_endereco(id_endereco: int):
    dados_endereco_apaga = regras_de_uso.regras_id_endereco_delete(id_endereco)

    return dados_endereco_apaga

#################################################################################
# Se tiver outro produto com o mesmo ID retornar falha,
# senão cria um produto e retornar OK
@app.post("/produto/")
async def criar_produto(produto: Produto):
    cria_produto = regras_de_uso.regras_cria_produto(produto.dict())
    return cria_produto

#################################################################################
# Se não existir produto com o id_produto retornar falha,
# senão deleta produto correspondente ao id_produto e retornar OK
# (lembrar de desvincular o produto dos carrinhos do usuário) TODO entender vinculação
@app.delete("/produto/{id_produto}/")
async def deletar_produto(id_produto: int):
    dados_produto_apaga = regras_de_uso.regras_produto_apaga(id_produto)

    return dados_produto_apaga

#################################################################################
# Se não existir usuário com o id_usuario ou id_produto retornar falha,
# se não existir um carrinho vinculado ao usuário, crie o carrinho
# e retornar OK
# senão adiciona produto ao carrinho e retornar OK
@app.post("/carrinho/{id_usuario}/{id_produto}/")
async def adicionar_carrinho(carrinho: CarrinhoDeCompras, id_usuario: int, id_produto: int):
    criar_carrinho = regras_de_uso.regras_cria_carrinho(id_usuario, id_produto, carrinho.dict())
    return criar_carrinho

#################################################################################
# Se não existir carrinho com o id_usuario retornar falha,
# senão retorna o carrinho de compras.
@app.get("/carrinho/{id_user}")
async def retornar_carrinho(id_user: int):
    dados_carrinho = regras_de_uso.regras_retornar_carrinho(id_user)
    return dados_carrinho

#################################################################################
# Se não existir carrinho com o id_usuario retornar falha,
# senão retorna o o número de itens e o valor total do carrinho de compras.
@app.get("/carrinho/{id_usuario}/checkout")
async def retornar_total_carrinho(id_usuario: int):
    informação_carrinho = regras_de_uso.regras_itens_valor_total(id_usuario)
    if informação_carrinho is list:
        numero_itens = informação_carrinho[0]
        valor_total = informação_carrinho[1]

        return numero_itens, valor_total
    else:
        return informação_carrinho

##################################################################################
# Se não existir usuário(?? Não seria carrinho?) com o id_usuario retornar falha,
# senão deleta o carrinho correspondente ao id_usuario e retornar OK
@app.delete("/carrinho/{id_usuario}/")
async def deletar_carrinho(id_usuario: int):
    deleta_carrinho_user = regras_de_uso.regras_deleta_carrinho(id_usuario)

    return deleta_carrinho_user


class Node:
    def __init__(self, value):
        self.value = value
        self.next = None
        self.prev = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None

    def traverseDoublyLinkedList(self):
        if self.head == None:
            print("No linked list to travel")

        else:
            temp = self.head
            while temp!=None:
                print(temp.value)
                temp = temp.next

    def insertAtStart(self, value):
        print(f"inserting {value} at start of linked list")
        if self.head == None:
            start = Node(value)
            self.head = start

        else:
            start = Node(value)
            self.head.prev = start
            start.next = self.head
            self.head = start

    def insertAtEnd(self, value):
        print(f"inserting {value} at end of linked list")
        if self.head == None:
            self.head = Node(value)

        else:
            temp = self.head
            while temp.next != None:
                temp = temp.next

            newNode = Node(value)
            temp.next = newNode
            newNode.prev = temp

    def insertAtAnIndex(self, index, value):
        print(f"inserting: {value} at index: {index} of linked list")
        count = 0
        if self.head == None:
            self.head = Node(value)

        #if need to insert at 0th index
        elif (index == 0):
            self.insertAtStart(value)

        else:
            temp = self.head
            while (count<index and temp!=None):
                if (count == index-1):
                    #if end is none and temp reached index then insert at end
                    if temp.next == None:
                        self.insertAtEnd(value)
                        break

                    #else insert it normally
                    else:
                        indexedNode = temp.next
                        newTemp = Node(value)
                        newTemp.next = indexedNode
                        indexedNode.prev = newTemp
                        newTemp.prev = temp
                        temp.next = newTemp
                        break
                else:
                    count += 1
                    temp = temp.next

            #handling for some outward index, in case at the temp reached end of linkedlist
            if temp == None:
                print(f"provided index doesn't exists so adding it at end")
                self.insertAtEnd(value)

    def deleteFromStart(self):
        print("deleting value from start")
        if self.head != None and self.head.next != None:
            start = self.head
            first = start.next
            first.prev = None
            self.head = first
            print(f"delete value {start.value} from start")
            del start

        elif self.head!=None and self.head.next == None:
            temp = self.head
            self.head = None
            del temp

        else:
            print("invalid linked list, cannot delete at start")

    def deleteFromEnd(self):
        print("deleting value from end")
        if self.head != None:
            first = self.head
            if (first.next == None):
                self.deleteFromStart()
            else:
                temp = first.next
                while(temp.next!=None):
                    temp = temp.next
                    first = first.next
                first.next = None
                print(f"delete value {temp.value} from end")
                del temp

    def deleteFromIndex(self, index):
        print(f"deleting node from an index {index}")

        if self.head == None:
            print(f"invalid linked list, cannot delete at index value: {index}")

        elif index == 0:
            self.deleteFromStart()

        elif index == 1:
            temp = self.head.next
            first = self.head
            second = temp.next
            second.prev = self.head
            first.next = second
            del temp

        else:
            count = 0
            temp = self.head
            while (count < index and temp!=None):
                if (count == index-1):
                    if temp.next == None:
                        print("error in deleting, None value")
                        break

                    else:
                        nodeToBeDeleted = temp.next
                        temp.next = nodeToBeDeleted.next
                        temp.next.prev = temp
                        del nodeToBeDeleted
                        break

                else:
                    count += 1
                    temp = temp.next

    def reverseDoublyLinkedList(self):
        print("reversing the doubly linked list")
        start = self.head
        temp = start.next
        start.next = None
        start.prev = temp
        thirdTemp = None

        while temp != None:
            secondTemp = temp

            if (thirdTemp == None):
                temp = temp.next
                secondTemp.next = start
                secondTemp.prev = temp
                thirdTemp = secondTemp

            else:
                temp = temp.next
                secondTemp.next = thirdTemp
                secondTemp.prev = temp
                thirdTemp = secondTemp

        self.head = thirdTemp

if __name__ == "__main__":
    link = DoublyLinkedList()
    link.head = Node(1)
    second = Node(2)
    third = Node(3)
    fourth = Node(4)

    link.head.next = second
    second.prev = link.head
    second.next = third
    third.prev = second
    third.next = fourth
    fourth.prev = third

    link.insertAtStart(0)
    link.insertAtEnd(5)
    link.traverseDoublyLinkedList()

    link.insertAtAnIndex(4, -4)
    link.insertAtAnIndex(7, 6)
    link.traverseDoublyLinkedList()

    link.insertAtAnIndex(9, 8)
    link.traverseDoublyLinkedList()

    link.deleteFromEnd()
    link.deleteFromStart()
    link.deleteFromIndex(4)
    link.deleteFromIndex(1)
    link.traverseDoublyLinkedList()

    link.reverseDoublyLinkedList()
    link.traverseDoublyLinkedList()


import datetime

from flask_script import Command, Option
from sqlalchemy.orm import load_only
from sqlalchemy import and_

from app import db
from app.resources.accounts.models import Account
from app.resources.account_stats.models import AccountStats
from app.resources.users.models import User

class UpdateAccountStats(Command):
    """
    Command to update stats of account

    :arg verbose:
        print progress
    :arg dry:
        dry run
    """

    option_list = [
        Option('--verbose', '-v', dest='verbose', action='store_true',
               default=False),
        Option('--dry', '-dry', dest='dry', action='store_true',
               default=False),
    ]

    def run(self, verbose, dry):
        if verbose:
            print('---' + str(datetime.datetime.utcnow()) + '---')
            print('updating account stats')

        try:
            account_ids = [a.row_id for a in Account.query.options(
                load_only('row_id')).all()]
            if account_ids:
                for account_id in account_ids:
                    user_count = User.query.filter(and_(
                        User.account_id == account_id,
                        User.deleted.is_(False))).count()
                    db.session.add(AccountStats(
                        account_id=account_id, total_users=user_count))
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            exit(1)

        print('---' + str(datetime.datetime.utcnow()) + '---')
        print('Done')


"""Contains CBV mixins for frontend views."""

from frontend.constants import SELECTED_TASK_CLASS
from frontend.widgets import JSONEditorWidget
from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK

class IsAdminOrOwnerOnlyMixin:
    """Allow access views only for admin or associated object user.

    This is analogous to the IsAdminOrOwnerThenWriteElseReadOnly
    permissions class in the tasks API.
    """

    def dispatch(self, request, *args, **kwargs):
        """Call parent dispatch method only if user is allowed."""
        if request.user.is_superuser or request.user == self.get_object().user:
            return super().dispatch(request, *args, **kwargs)
        return self.handle_no_permission()

class UserFormViewMixin:
    """Provides the user as initial data to formviews."""

    def get_initial(self):
        """Automatically fill in the user."""
        initial = super().get_initial()

        return {**initial, "user": self.request.user.pk}

class DisableUserSelectFormViewMixin:
    """Don't let the user form field be editable."""

    def get_form(self, form_class=None):
        """Set the user field to disabled."""
        form = super().get_form(form_class)

        form.fields["user"].disabled = True

        return form

class TaskTypeFormViewMixin:
    """Set specific form settings for task types."""

    def get_form(self, form_class=None):
        """Tweak the widgets and ordering."""
        form = super().get_form(form_class)

        # Adjust the ordering. See
        # https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.field_order.
        # Unrecognized fields will be ignored, so we can set order for
        # all of the subclasses' fields, even if not all occur in each
        # subclass.
        form.field_order = [
            "name",
            "description",
            "user",
            "container_type",
            "container_image",
            "logs_path",
            "results_path",
            "command_to_run",
            "json_file_option",
            "required_arguments",
            "required_arguments_default_values",
            "environment_variables",
        ]
        form.order_fields(form.field_order)

        # Use JSON Editor widget for JSON fields
        form.fields["environment_variables"].widget = JSONEditorWidget()
        form.fields["required_arguments"].widget = JSONEditorWidget()
        form.fields[
            "required_arguments_default_values"
        ].widget = JSONEditorWidget()

        # Use monospace on code bits
        form.fields["command_to_run"].widget.attrs.update(
            style="font-family: monospace"
        )

        return form

class ContainerTaskTypeFormViewMixin:
    """Set widgets for container task type fields."""

    def get_form(self, form_class=None):
        """Tweak the widget for container stuff."""
        form = super().get_form(form_class)

        # Use monospace on code bits
        form.fields["container_image"].widget.attrs.update(
            style="font-family: monospace"
        )
        form.fields["logs_path"].widget.attrs.update(
            style="font-family: monospace"
        )
        form.fields["results_path"].widget.attrs.update(
            style="font-family: monospace"
        )

        return form

class ExecutableTaskTypeFormViewMixin:
    """Set widgets for container task type fields."""

    def get_form(self, form_class=None):
        """Tweak the widget for the JSON file option."""
        form = super().get_form(form_class)

        # Use monospace on code bits
        form.fields["json_file_option"].widget.attrs.update(
            style="font-family: monospace"
        )

        return form

class SetTaskClassCookieMixin:
    """Set the task class cookie when get is called."""

    task_class = "fill me in"

    def get(self, *args, **kwargs):
        """Set the cookie if it's not what we want."""
        if (
            SELECTED_TASK_CLASS not in self.request.session
            or self.request.session[SELECTED_TASK_CLASS] != self.task_class
        ):
            self.request.session[SELECTED_TASK_CLASS] = self.task_class

        return super().get(*args, **kwargs)

class SetContainerTaskClassCookieMixin(SetTaskClassCookieMixin):
    """Set cookie to prefer container task classes."""

    task_class = CONTAINER_TASK

class SetExecutableTaskClassCookieMixin(SetTaskClassCookieMixin):
    """Set cookie to prefer executable task classes."""

    task_class = EXECUTABLE_TASK


from django.urls import path
from django.views.static import serve
from django.conf.urls import url
from django.conf import settings
from .views import (
    AboutUs,
    Accessories,
    CardPaymentView,
    Clothes,
    ItemDetailView,
    CheckoutView,
    HomeView,
    OrderSuccessful,
    OrderSummaryView,
    PhoneView,
    PrivacyPolicy,
    SearchView,
    TermsConditions,
    add_to_cart,
    remove_from_cart,
    remove_single_item_from_cart,
    PaymentView,
    AddCouponView,
    RequestRefundView
)

app_name = 'rope'

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('accessories', Accessories.as_view(), name='accessories'),
    path('search', SearchView.as_view(), name='search'),
    path('phones', PhoneView.as_view(), name='phones'),
    path('checkout/', CheckoutView.as_view(), name='checkout'),
    path('order-summary/', OrderSummaryView.as_view(), name='order-summary'),
    path('product/<slug>/', ItemDetailView.as_view(), name='product'),
    path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'),
    path('add-coupon/', AddCouponView.as_view(), name='add-coupon'),
    path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'),
    path('remove-item-from-cart/<slug>/', remove_single_item_from_cart,
         name='remove-single-item-from-cart'),
    path('payment/<payment_option>/', PaymentView.as_view(), name='payment'),
    path('cardpayment/<payment_option>/', CardPaymentView.as_view(), name='cardpayment'),

    path('ordersuccessful', OrderSuccessful.as_view(), name='ordersuccessful'),
    path('clothes', Clothes.as_view(), name='clothes'),
    path('about_us', AboutUs.as_view(), name='about_us'),
    path('privacy-policy', PrivacyPolicy.as_view(), name='privacy-policy'),
    path('termsandconditions', TermsConditions.as_view(), name='termsandconditions'),

    path('request-refund/', RequestRefundView.as_view(), name='request-refund'),
    url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]


'''
  Four friends want to attend a concert. Each ticket costs X rupees.
  They have decided to go to the concert if and only if the total cost of the tickets does not exceed 1000 rupees.
  Determine whether they will be going to the concert or not.
'''

# Running Loop For Test Cases
for t in range(int(input())):

  # Taking Input For X = Cost Of Each Ticket
  X = int(input())

  # If Total Cost Of Tickets < 1000; They Will Go To The Concert
  FourTickets = "YES" if ((4*X) <= 1000) else "NO"

  # Printing Result
  print(FourTickets)


from typing import Any
from unittest import mock

from pyesg import stochastic_process
from esg.regime_switching_brownian_motion import RegimeSwitching
import pytest
import numpy as np
import pandas as pd
from unittest.mock import MagicMock, Mock, call, patch
import unittest

class NumpyArg:

    def __init__(self, arg: Any) -> None:
        self.arg = arg

    def __eq__(self, __value: object) -> bool:
        return np.array_equiv(self.arg, __value)

    def __repr__(self) -> str:
        return f'numpy arg: {self.arg}'

class ReturnValueWithArgs:

    def __init__(self, return_value, *args, **kwargs) -> None:
        self.args = args
        self.return_value = return_value

    def __call__(self, *args: Any, **kwds: Any) -> Any:
        if(self.args == args):
            return self.return_value
        else:
            raise ValueError(f'No return value for args: {args}, but for {self.args}')

#transition matrix for two regimes
k2_tm = [[0.65, 0.35],
         [0.06, 0.94]]

#transition matrix for three regimes
k3_tm = [[0.65, 0.25, 0.1],
         [0.06, 0.74, 0.2],
         [0.11, 0.24, 0.65]]

@pytest.fixture()
def transition_matrix():
    def create_transition_matrix(n_regimes):
        if (n_regimes == 2):
            return k2_tm
        if (n_regimes == 3):
            return k3_tm
        if(n_regimes != 2 or n_regimes != 3):
            raise ValueError(f'Returns transition matrix for 2 and 3 regimes, you passed: {n_regimes}')

    return create_transition_matrix

class TestRegimeSwithing():

    def setup_method(cls):
      cls.model = RegimeSwitching.example()

    @pytest.mark.parametrize('number_of_regimes,expected', [
        (2, [0,1]),
        (3, [0,1,2])
        ])
    def test_should_return_regimes_ids(self, number_of_regimes, expected, transition_matrix):

        self.model.probs = transition_matrix(number_of_regimes)

        actual = self.model.regimes_idx

        np.testing.assert_array_equal(actual, expected)

    @pytest.mark.parametrize('number_of_scenarios,current_regimes,expected_calls',[
        (2, 1, [call(n_scenarios=1,probs=k2_tm[1])]),
        (2, [0,0,0], [call(n_scenarios=3,probs=k2_tm[0])]),
        (2,[0,1,0], [call(n_scenarios=2,probs=k2_tm[0]),call(n_scenarios=1,probs=k2_tm[1])]),
        (3,[0,1,0,2], [call(n_scenarios=2,probs=k3_tm[0]),call(n_scenarios=1,probs=k3_tm[1]),call(n_scenarios=1,probs=k3_tm[2])])
    ])
    def test_when_next_regime_called_should_call_random_regime(self, number_of_scenarios, current_regimes, expected_calls,transition_matrix):

        self.model.probs = transition_matrix(number_of_scenarios)

        self.model.random_regimes = Mock(return_value=[0])

        self.model.next_regime(current_regimes)

        self.model.random_regimes.assert_has_calls(expected_calls)

    @pytest.mark.parametrize('number_of_regimes,current_regimes,random_regimes,expected_regimes',[
        (2, 1, [np.array([1])], [1]),
        (2, [0,0], [np.array([0,1])], [0,1]),
        (2, [0,1,0], [np.array([0,1]), np.array([1])], [0,1,1]),
        (3, [0,1,0,2], [np.array([1,2]), np.array([0]), np.array([1])], [1,0,2,1])
    ])
    def test_when_next_regime_called_should_return_next_regimes(self, number_of_regimes, current_regimes, random_regimes, expected_regimes,transition_matrix):

        self.model.probs = transition_matrix(number_of_regimes)

        self.model.random_regimes = Mock(side_effect=random_regimes)

        result = self.model.next_regime(current_regimes)

        np.testing.assert_equal(result,expected_regimes)

    @pytest.mark.parametrize('n_regimes, n_scenarios,expected_shape',[
        (2, 1,(1,)),
        (2, 5,(5,)),
        (3, 5,(5,))
    ])
    def test_random_regimes_should_return_shape(self, n_regimes, n_scenarios,expected_shape, transition_matrix):

        self.model.probs = transition_matrix(n_regimes)
        result = self.model.random_regimes(n_scenarios=n_scenarios,probs=self.model.probs[0])

        assert result.shape == expected_shape
        assert all(item in self.model.regimes_idx for item in result)

    @pytest.mark.parametrize('regime,expected_value',[
        ([1], 11.3),
        ([0], 10.9),
    ])
    @patch('pyesg.stochastic_process.StochasticProcess')
    @patch('pyesg.stochastic_process.StochasticProcess')
    def test_call_step_should_return_value_for_single_initial_value(self,  stochastic_model1, stochastic_model2, regime,expected_value):

        model0 = stochastic_model2()
        model0.step.return_value = 10.9
        model1 = stochastic_model1()
        model1.step.return_value = 11.3

        regime_switching_model = RegimeSwitching(models= [model0, model1],probs=k2_tm)
        regime_switching_model.next_regime = Mock(side_effect = ReturnValueWithArgs(regime,current_regimes=0))

        result = regime_switching_model.step(x0=10,current_regimes=0)

        assert result == expected_value

    @pytest.mark.parametrize('next_regimes,initial_values0,initial_values1,model0_return, model1_return,expected_value',[
        ([0,0,0], [10,15,20], None, [10.9, 15.6, 20.8], None, [10.9, 15.6,20.8]),
        ([1,0,1], [15], [10,20], [11.6], [15.3,20.3], [15.3, 11.6, 20.3]),
        ([0,1,0], [10,20], [15], [10.9,20.8], [15.6], [10.9, 15.6, 20.8]),
    ])
    @patch('pyesg.stochastic_process.StochasticProcess')
    @patch('pyesg.stochastic_process.StochasticProcess')
    def test_call_step_should_return_value_for_multiple_initial_value(self,
                                                                      stochastic_model1,
                                                                      stochastic_model2,
                                                                      next_regimes,
                                                                      initial_values0,
                                                                      initial_values1,
                                                                      model0_return,
                                                                      model1_return,
                                                                      expected_value):

        model0 = stochastic_model2()
        model0.step.side_effect = ReturnValueWithArgs(model0_return,NumpyArg(initial_values0),1)
        model1 = stochastic_model1()
        model1.step.side_effect = ReturnValueWithArgs(model1_return,NumpyArg([initial_values1]),1)

        initial_values= [10,15,20]

        regime_switching_model = RegimeSwitching(models= [model0, model1],probs=k2_tm)
        regime_switching_model.next_regime = Mock(side_effect = ReturnValueWithArgs(next_regimes,current_regimes=[0,0,1]))

        result = regime_switching_model.step(x0=initial_values,current_regimes=[0,0,1],dt=1)

        np.testing.assert_array_equal(result, expected_value)

    def test_scenarios_regimes_multiple_initial_values(self):

        n_scenarios = 3
        n_steps = 5
        current_regime = [0, 1, 0]

        result = self.model.scenarios_regimes(current_regime,n_steps)
        assert result.shape == (n_steps+1, n_scenarios)

    def test_scenarios_with_multiple_initial_value(self):

        n_steps = 3
        n_scenarios = 2
        initial_values = [10, 10]
        current_regimes = [0, 0]
        dt = 1/4

        result = self.model.scenarios(initial_values, current_regimes, dt, n_steps, n_scenarios)

        assert result.shape == (n_scenarios,n_steps+1)

    def test_scenarios_with_single_initial_value(self):

        n_steps = 3
        n_scenarios = 2
        initial_values = 10
        current_regimes = 0
        dt = 1/4

        result = self.model.scenarios(initial_values, current_regimes, dt, n_steps, n_scenarios)

        assert result.shape == (n_scenarios,n_steps+1)


#!/usr/bin/env python

# this script can extract time frame into jpg images

import csv
import cv2
import glob
import os
import pandas as pd
import math
from subprocess import call
import settings
import function_list as ff
cg = settings.Experiment()

def extract_timeframes(main_path,movie_path,excel_file):
    """After we have all of our videos split between train and test, and
    all nested within folders representing their classes, we need to
    make a data file that we can reference when training our RNN(s).
    This will let us keep track of image sequences and other parts
    of the training process.

    We'll first need to extract images from each of the videos. We'll
    need to record the following data in the file:

    [train|test] or batch, class, filename, nb frames

    Extracting can be done with ffmpeg:
    `ffmpeg -i video.mpg image-%04d.jpg`
    """
    data =[]

    # create image folder
    image_folder = os.path.join(main_path,'images')
    ff.make_folder([image_folder])

    # find all the movies
    excel_file = pd.read_excel(excel_file)
    movie_list = excel_file['video_name']

    # extract time frames from each movie:
    for i in range(0,excel_file.shape[0]):
        case = excel_file.iloc[i]
        print(i, case['video_name'])

        # set the file name for images
        file_name = case['video_name']
        file_name_sep = file_name.split('.') # remove .avi
        file_name_no_ext = file_name_sep[0]
        if len(file_name_sep) > 1:
            for ii in range(1,len(file_name_sep)-1):
                file_name_no_ext += '.'
                file_name_no_ext += file_name_sep[ii]
        save_folder = os.path.join(image_folder,file_name_no_ext)
        ff.make_folder([save_folder])

        src = os.path.join(movie_path,file_name)
        if os.path.isfile(src) == 0:
            ValueError('no movie file')

        if os.path.isfile(os.path.join(save_folder,file_name_no_ext+'-0001.jpg')) == 0:
            cap = cv2.VideoCapture(src)
            count = 1
            frameRate = 1
            while(cap.isOpened()):
                frameId = cap.get(1) # current frame number
                ret, frame = cap.read()

                if (ret != True):
                    break
                if (frameId % math.floor(frameRate) == 0):
                    if count < 10:
                        number = '000'+str(count)
                    if count >=10:
                        number = '00'+str(count)

                dest = os.path.join(save_folder,file_name_no_ext+'-'+number+'.jpg')
                cv2.imwrite(dest,frame)
                count += 1
            cap.release()
            # call(["ffmpeg", "-i", src, dest]) % this will cause some error (not extract exact 20 frames) in some avis

        # Now get how many frames it is.
        nb_frames = len(ff.find_all_target_files(['*.jpg'],save_folder))
        data.append([case['video_name'],file_name_no_ext,nb_frames])

    print('done extraction')
    data_df = pd.DataFrame(data,columns = ['video_name','video_name_no_ext','nb_frames'])
    data_file = pd.merge(excel_file,data_df,on = "video_name")
    data_file.to_excel(os.path.join(cg.nas_main_dir,'data_file.xlsx'),index=False)

def main():
    """
    Extract images from videos and build a new file that we
    can use as our data input file. It can have format:

    [train|test], class, filename, nb frames
    """
    main_path = cg.local_dir
    movie_path = os.path.join(main_path,'original_movie')
    excel_file = os.path.join(cg.nas_main_dir,'movie_list_w_classes.xlsx')
    extract_timeframes(main_path,movie_path,excel_file)

if __name__ == '__main__':
    main()


in_file = '../data/tm_alpha_beta_3state.3line.txt'
out_dir = '../bin/'

#iterates through input file, parsing sequences and topologies
f=open(in_file, 'r')
f=f.readlines()

#iterates through input file, parsing sequences and topologies according to
#given window size
IDs=[]
sequences=[]
g=0
o=0
p=0
for i in range(0, len(f), 3):
    if 'G' in f[i+2]:
        g+=1
        continue
    else:
        IDs.append(f[i].split("|", 1)[0].rstrip().strip('>'))
        p+=1
#QUESTION:WHAT'S THE DIFFERENCE BETWEEN 'PASS' AND 'CONTINUE'?

for i in range(1, len(f), 3):
    if 'G' in f[i+1]:
        continue
    else:
        sequences.append(f[i].rstrip('\n'))

o=g+p
print('Your test file contains {} protein sequences.'.format(o))
print('In total, {} membrane proteins will be used in the final dataset.'.format(p))
print('{} sequences refer to globular proteins and were removed from the final dataset.'.format(g))
print('TopoPRED will now prepare your sequences to PSI-BLAST. Please wait ...')

#RUNS PSI-BLAST ON INPUT PROTEIN SEQUENCES
for i in range(len(IDs)):
    with open((out_dir + str(IDs[i]) + '.fa'), 'w') as fa:
        fa.write(str(IDs[i]) + '\n')
        fa.write(str(sequences[i]) + '\n')

    ####GO TO BASH HERE####


def RPN_to_INF(RPN,convert):
    stack = []
    string = RPN.split(' ')
    for i in string:
        try:
            char = int(i)
            stack.append(char)
        except:
            v1 = stack.pop()
            v2 = stack.pop()
            if convert == True:
                temp = eval(f'({v2} {i} {v1})')
            else:
                temp = f'({v2} {i} {v1})'
            stack.append(temp)
    return(stack[-1])

print(RPN_to_INF('77 55 + 7 7 7 * * *',False))

def INF_to_RNP(INF):
    return(eval(INF))


# https://leetcode.com/problems/linked-list-in-binary-tree/solutions/524881/python-recursive-solution-o-n-l-time/?q=python&orderBy=most_votes
# Solution 1: Brute DFS
def isSubPath(self, head, root):

    def dfs(head, root):
        if not head: return True
        if not root: return False
        # 一定是先確認head 再處理root!
        # ＪＭ：窮舉之後，再統整

        return root.val == head.val and (dfs(head.next, root.left)
                                         or dfs(head.next, root.right))

    if not head: return True
    if not root: return False
    return dfs(head, root) or self.isSubPath(
        head, root.left) or self.isSubPath(head, root.right)
      # 提供不同的開頭...

# Solution 2: DP
class Solution(object):

    def isSubPath(self, head, root):
        A, dp = [head.val], [0]
        i = 0
        node = head.next
        while node:
            while i and node.val != A[i]:
                i = dp[i - 1]
            i += node.val == A[i]
            A.append(node.val)
            dp.append(i)
            node = node.next

        def dfs(root, i):
            if not root: return False
            while i and root.val != A[i]:
                i = dp[i - 1]
            i += root.val == A[i]
            return i == len(dp) or dfs(root.left, i) or dfs(root.right, i)

        return dfs(root, 0)


# Program to get numebr of occurrence of blank spaces
# Created by: Siddhartha
# Created on: 1st April 2020

# function to count occurance of an alphabet from a file
def count_blank_spaces(file):
    # initialize occurrences as 0
    occurrences = 0
    # using the read function to get the whole file as a string
    whole_file_as_string = file.read()
    # strip string of escape sequences
    whole_file_as_string = whole_file_as_string.strip()
    for character in whole_file_as_string:
        # match the character with blank character
        if character == ' ':
            occurrences += 1
    return occurrences

# driver function to process file and return output
def main(fileName, mode):
    with open(fileName, mode) as file:
        occurrences = count_blank_spaces(file)
    return occurrences

if __name__ == "__main__":
    fileName = 'files/story.txt'
    mode = 'r'
    occurrences = main(fileName, mode)
    print("The blank character occurs {} times".format(occurrences))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
uniswap-python examples
@author: mpascariu
"""

# Setup
import os
import json
import sys
from web3 import Web3
from uniswap import Uniswap

# Here I have a file containing API keys, wallet and smart contract addresses
sys.path.append("/Volumes/DEIFX/py.defi")
import _init

# Set up the API connection
w3 = Web3(Web3.HTTPProvider(_init.polygon_url_alchemy))
print(w3.is_connected())

# Uniswap-python

uniswap = Uniswap(
    address     = _init.w_cologne,
    private_key = _init.pk_cologne,
    provider    = _init.polygon_url_alchemy,
    version     = 3
    )

wmatic = uniswap.get_weth_address()
dai   = '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063'
eure  = '0x18ec0A6E18E5bc3784fDd3a3634b31245ab704F6'
usdt  = '0xc2132D05D31c914a87C6611C10748AEb04B58e8F'
usdc  = '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'

def value(x):
    out = w3.from_wei(x,  'ether')
    out = round(out, 4)
    return print(out)

# sell 1000 tokens for DAI
# the amount of DAI received is:
amount     = 1000
decimals   = 18
amount_wei = amount * (10**decimals)

value(uniswap.get_price_output(wmatic, dai, amount_wei))
value(uniswap.get_price_output(eure, dai, amount_wei))
uniswap.get_raw_price(token_in = dai, token_out = eure) * 1000

# spend 1000 DAI for tokens
# the amount of tokens received is:
value(uniswap.get_price_input(dai, wmatic, amount_wei))
value(uniswap.get_price_input(dai, eure, amount_wei))
uniswap.get_raw_price(token_in = dai, token_out = eure) * 1000
uniswap.get_raw_price(token_in = usdt, token_out = eure) * 1000

# check wallet ballance
value(uniswap.get_token_balance(eure))
value(uniswap.get_token_balance(dai))


"""
Make a route-level df from trips and shapes.

Must include the route's line geom and service hours and
district.
"""
import datetime
import geopandas as gpd
import intake
import pandas as pd
import sys

from loguru import logger
from typing import Literal

from calitp_data_analysis import geography_utils, utils
from shared_utils import portfolio_utils
from bus_service_utils import create_parallel_corridors
from segment_speed_utils import helpers, gtfs_schedule_wrangling
from update_vars import (BUS_SERVICE_GCS, COMPILED_CACHED_GCS,
                         ANALYSIS_DATE,
                        )

catalog = intake.open_catalog(
    "../_shared_utils/shared_utils/shared_data_catalog.yml")

def shape_geom_to_route_geom(
    analysis_date: str
) -> gpd.GeoDataFrame:
    """
    Merge routes and trips to get line geometry.
    """
    cols_to_keep = ["route_id", "shape_id", "geometry"]
    operator_cols = ["feed_key", "name"]

    df = gtfs_schedule_wrangling.get_trips_with_geom(
        analysis_date,
        trip_cols = operator_cols + [
                     "trip_id",
                     "shape_id","shape_array_key",
                     "route_id", "route_type"
                    ],
        exclude_me = ["Amtrak Schedule", "*Flex"],
        crs = geography_utils.CA_StatePlane
        # make sure units are in feet
    )

    # Merge trips with the shape's line geom, and get it to shape_id level
    df = (df[operator_cols + cols_to_keep + ["route_type"]]
        .drop_duplicates(subset=operator_cols + ["shape_id"])
        .reset_index(drop=True)
    )

    # Now, get it from shape_id level to route_id level
    routes = create_parallel_corridors.process_transit_routes(
        df, operator_cols = operator_cols
    )

    # Add gtfs_dataset_name back
    feed_gtfs_data_crosswalk = helpers.import_scheduled_trips(
        analysis_date,
        columns = ["feed_key", "gtfs_dataset_key"],
        get_pandas = True
    ).rename(columns = {"schedule_gtfs_dataset_key": "gtfs_dataset_key"})

    routes2 = pd.merge(
        routes,
        feed_gtfs_data_crosswalk,
        on = "feed_key",
        how = "inner"
    )

    return routes2

def aggregate_trip_service_to_route_level(
    analysis_date: str,
    route_cols: list
) -> pd.DataFrame:
    """
    Aggregate trip-level service hours to the route-level.
    """
    trips = helpers.import_scheduled_trips(
        analysis_date,
        columns = route_cols + ["trip_id", "service_hours"],
        get_pandas = True
    ).rename(columns = {"schedule_gtfs_dataset_key": "gtfs_dataset_key"})

    route_service_hours = portfolio_utils.aggregate_by_geography(
        trips,
        group_cols = route_cols,
        sum_cols = ["service_hours"]

    )

    return route_service_hours

def add_district(route_df: gpd.GeoDataFrame,
                 route_cols: list) -> gpd.GeoDataFrame:
    """
    Merge in district info (only 1 district per route_id)
    """
    districts = (catalog.caltrans_districts.read()
                 [["DISTRICT", "geometry"]]
                 .rename(columns = {"DISTRICT": "district"})
                ).to_crs(route_df.crs)

    # Find overlay and calculate overlay length
    # Keep the district with longest overlay for that route_id
    overlay_results = gpd.overlay(
        route_df[route_cols + ["geometry"]].drop_duplicates(),
        districts,
        how = "intersection",
        keep_geom_type = True
    )

    overlay_results = overlay_results.assign(
        overlay_length = overlay_results.geometry.to_crs(
            geography_utils.CA_StatePlane).length
    )

    longest_overlay = (overlay_results
                       .sort_values(route_cols + ["overlay_length"])
                       .drop_duplicates(subset=route_cols, keep="last")
                       .reset_index(drop=True)
    )

    # Only keep 1 district per route
    gdf = pd.merge(
        route_df,
        longest_overlay[route_cols + ["district"]],
        on = route_cols,
        how = "left"
    )

    return gdf

if __name__ == "__main__":

    logger.add("./logs/quarterly_performance_pipeline.log", retention="6 months")
    logger.add(sys.stderr,
               format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}",
               level="INFO")

    start = datetime.datetime.now()

    route_cols = ["gtfs_dataset_key", "feed_key", "name", "route_id"]

    # Merge to get shape_level geometry, then pare down to route-level geometry
    route_geom = shape_geom_to_route_geom(
        ANALYSIS_DATE)

    # Add district
    route_geom_with_district = add_district(route_geom, route_cols)

    # Get route-level service
    route_service = aggregate_trip_service_to_route_level(ANALYSIS_DATE, route_cols)

    # Merge service hours with route-level geometry and district
    gdf = pd.merge(
        route_geom_with_district,
        route_service,
        on = route_cols,
        how = "left",
        validate = "1:1"
    )

    utils.geoparquet_gcs_export(
        gdf,
        BUS_SERVICE_GCS,
        f"routes_{ANALYSIS_DATE}.parquet"
    )

    end = datetime.datetime.now()
    logger.info(f"route level service: {ANALYSIS_DATE} {end - start}")


#!/usr/bin/python3
import requests
from PIL import Image
from io import BytesIO

matches = {
    (237, 28, 36, 255) : "apple",
    (253, 215, 0, 255) : "banana",
    (47, 21, 62, 255) : "epic coin",
    (255, 204, 0, 255) : "golden fish",
    (255, 242, 0, 255) : "golden coin",
    (217, 17, 27, 255) : "life potion",
    (0, 198, 255, 255) : "normie fish",
    (255, 21, 21, 255) : "ruby",
    (255, 130, 170, 255) : "unicorn horn",
    (46, 46, 52, 255) : "wolf skin",
    (77, 98, 11, 255) : "zombie eye"
}

def handle_guard(message):

    r = requests.get(message.attachments[0].url)
    img = Image.open(BytesIO(r.content))
    pixel_data = set(img.getdata())
    for k, v in matches.items():
        if k in pixel_data:
            return matches[k]

    return "none found"


#!/usr/bin/env python
"""Driver
This loads data into Cockroach DB.
Script expects Cockroach IP is passed.
"""
import sys
import subprocess
import time
import psycopg2

if len(sys.argv) == 1:
    print('Must pass IP from Cockroach server')
    sys.exit()
else:
    print('Host IP: ' + str(sys.argv[1]))

subprocess.call('cp ~/data-science/jupyter_home/kickstart.csv.xz  /tmp/', shell=True)
time.sleep(5)
subprocess.call('xz -d /tmp/kickstart.csv.xz', shell=True)
time.sleep(5)
subprocess.call('hdfs dfs -put /tmp/kickstart.csv /', shell=True)

CONN = psycopg2.connect(
    database='tx',
    user='test_user',
    port='26257',
    host=str(sys.argv[1])
)
CONN.set_session(autocommit=True)
CUR = CONN.cursor()

CAT = subprocess.Popen(["hadoop", "fs", "-cat", "/kickstart.csv"], stdout=subprocess.PIPE)

i = 0
for line in CAT.stdout:
    i = i + 1
    l = str(line).strip('[b"\\n]').split(',')
    for k in range(0, 8):
        l[k] = l[k].strip('\'')

    if l[0] != 'category':
        sql = 'INSERT INTO tx.kickstart VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)'
        CUR.execute(sql, l)

    if i%1000 == 0:
        print(str(i) + ' records loaded')


import torch
import re
import os
import pickle
import random
from tqdm import tqdm

"""
common utils
"""
def collect_all_data(path):
    random.seed(999)

    files = os.listdir(path)
    all_data = []
    for file in files:
        with open(path + file, 'rb') as f:
            data = pickle.load(f)
        all_data.append(data)
    all_data = sum(all_data, [])

    random.shuffle(all_data)

    with open(path + 'all_data.pkl', 'wb') as f:
        pickle.dump(all_data, f)

    return all_data

def make_vocab_file(data, data_save_path, special_token_save_path):
    all_s = []
    special_tok = set()
    for d in tqdm(data, desc='making vocab train file...'):
        for s in d:
            # find special token e.g. #@이름#
            compile = re.compile(r'(?<=#@)(.*?)(?=#)')
            special_tok.update(compile.findall(s))
            s = ' '.join(s.strip().split())
            all_s.append(s + '\n')

    with open(data_save_path, 'w') as f:
        f.writelines(all_s)

    all_special_tokens = []
    for tok in list(special_tok):
        all_special_tokens.append('#@' + tok + '#\n')

    with open(special_token_save_path, 'w') as f:
        f.writelines(all_special_tokens)

def load_dataset(path):
    with open(path, 'rb') as f:
        data = pickle.load(f)
    return data

def save_checkpoint(file, model, optimizer, scheduler=None):
    if scheduler == None:
        state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict()}
    else:
        state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict()}
    torch.save(state, file)
    print('model pt file is being saved\n')

def tensor2list(tensor, tokenizer):
    tensor = tensor.detach().cpu().tolist()
    tensor = [tokenizer.decode(t[1:]) for t in tensor]
    return tensor

def isInTopk(gt_id, selected_id, topk):
    selected_id = selected_id.tolist()
    if len(selected_id) < topk:
        raise IndexError("topk is larger than selected id")

    if gt_id in selected_id[:topk]:
        return 1
    return 0


# Remove Outermost Parentheses
# A valid parentheses string is either empty (""), "(" + A + ")", or A + B,
# where A and B are valid parentheses strings, and + represents string concatenation.
# For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
# A valid parentheses string S is primitive if it is nonempty, and there does not
# exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.
# Given a valid parentheses string S, consider its primitive decomposition:
# S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
# Return S after removing the outermost parentheses of every primitive string in
# the primitive decomposition of S.

# Example 1:
# Input: "(()())(())"
# Output: "()()()"
# Explanation:
# The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
# After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
#
# Example 2:
# Input: "(()())(())(()(()))"
# Output: "()()()()(())"
# Explanation:
# The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
# After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
#
# Example 3:
# Input: "()()"
# Output: ""
# Explanation:
# The input string is "()()", with primitive decomposition "()" + "()".
# After removing outer parentheses of each part, this is "" + "" = "".

class Solution:
    def removeOuterParentheses(self, S: str) -> str:

        # Solution 1: ------ count ------
        # Idea: Recursively append "(" and ")" in reserved list
        #       1. If "(", add 1
        #       2. If ")", minus 1
        #       3. Append condition: count > 1, skip the outer "(" and ")"
        reserveList = []
        count = 0
        for index, item in enumerate(S):
            if item == '(':
                count += 1
            if count > 1:
                reserveList.append(item)
            if item == ')':
                count -= 1
        return "".join(reserveList)

        # Solution 2: ------ Stack ------
        # Idea: Recursively add "(" and ")" to new string
        #       1. Initiate empty stack, push first item in
        #       2. If is "(" push in stack, if is ")" pop out
        #       3. Add condition: only if stack is not empty, skip the outer items
        stack = []
        ans = ""
        for i in range(len(S)):
            if S[i] == "(":
                if stack != []:
                    ans += S[i]
                stack.append(i)
            # if S[i] == ')'
            else:
                m = stack.pop()
                if stack != []:
                    ans += S[i]
        return ans

testCase = Solution()
print(testCase.removeOuterParentheses("(()(()))()"))


import filetype
import os
import subprocess
import multiprocessing

folders = os.listdir('/home/cosmadrian/Desktop/iMaterialist Challenge/data')
base_dir = '/home/cosmadrian/Desktop/iMaterialist Challenge/data/'
def delete_files(folder):
    files = [f for f in os.listdir(base_dir + folder)]
    for_deletion = [
        base_dir + folder + '/' + img
        for img in files
            if filetype.guess(base_dir + folder + '/' + img)is None or
                filetype.guess(base_dir + folder + '/' + img).mime.split('/', 1)[0] != 'image'
    ]
    print(folder, len(for_deletion))

    for file in for_deletion:
        os.remove(file)

for folder in folders:
    delete_files(folder)


import argparse
import cv2
import numpy as np
import mediapipe as mp

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-p", "--person", required = True, help = "path to image file of person")
    ap.add_argument("-b", "--background", required = True, help = "path to background image")
    args = vars(ap.parse_args())

    image = cv2.imread(args["person"])
    background_img = cv2.imread(args["background"])

    resized_bg_img = cv2.resize(background_img, (image.shape[1], image.shape[0]))

    mp_selfie_segmentation = mp.solutions.selfie_segmentation
    segment = mp_selfie_segmentation.SelfieSegmentation(model_selection = 0)

    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    results = segment.process(image)

    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    image_seg_mask = results.segmentation_mask

    threshold = 0.5
    binary_mask = image_seg_mask > threshold

    mask3d = np.dstack((binary_mask, binary_mask, binary_mask))

    replaced_img = np.where(mask3d, image, resized_bg_img)

    cv2.imwrite("result.jpg", replaced_img)


import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt

#pre-process
mandi = pd.read_csv("azadpur.csv")
mandi.drop(mandi.columns[[0,1,2,3,4,5,6]], axis=1, inplace=True)
mandi.columns = ["price", "dod"]
mandi["dod"] =  pd.to_datetime(mandi['dod'], format='%d %b %Y')
mandi = mandi.sort(["dod"], ascending = True)

ws = pd.read_csv("WS.csv")
ws.columns = ["dod", "mid", "arrival", "origin", "var", "min", "max", "price"]
ws.drop(ws.columns[[1,2,3,4,5,6]], axis=1, inplace=True)

temp = mandi.drop_duplicates(cols='dod', take_last=True)

data = ws
for c in mandi.ix[:,0]:
	f = data[data["mid"] == c]
	f.drop(f.columns[[1,3,4,5,6]], axis=1, inplace=True)
	f = f[f["dod"] >= "2006-01-01"]
	f = f[f["dod"] <= "2015-06-23"]
	g = f.drop_duplicates(cols='dod', take_last=True)
	if len(g) > 500 and len(g) < 1000 and c!=435:
		break


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ablog', '0002_tag'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='entry',
            options={'ordering': ['-created'], 'verbose_name': 'Blog Entry', 'verbose_name_plural': 'Blog Entries'},
        ),
        migrations.AddField(
            model_name='entry',
            name='tags',
            field=models.ManyToManyField(to='ablog.Tag'),
            preserve_default=True,
        ),
    ]


from flask import Flask, json
import csv

class format_class:
    def __init__(self,dictionary_list, tid):
        self.dictionary_list = dictionary_list
        self.tid = tid

    def write_to_txt(self):
        file_type = ".txt"
        output_file = open("output" + "_" + self.tid + file_type, 'w+')
        output_file.write("--- Output Of Response ---\n")
        for item in self.dictionary_list:
            try:
                output_file.write(str(item['name']) + "," + "http: " +str(item['http_response']) + "," + str(item['result_date'])+ "," + str(item['resolution_url']) + "\n")
            except:
                output_file.write(str(item['name']) + "," + "https: " + str(item['https_response']) + "," + str(item['result_date'])+ "," + str(item['resolution_url']) +"\n")
        output_file.close()

    def write_to_json(self):
        try:
            outcome_list = self.dictionary_list
            with open('domains.json', 'w') as f:
                json.dump(outcome_list, f, indent=2)
        except:
            print("Error occured to convert list to JSON (except in function)")
        json_string = json.dumps(outcome_list, indent=2)
        return json_string

    def write_to_csv(self):
        file_type = ".csv"
        count = len(self.dictionary_list)

        with open('output_'+ self.tid + file_type, 'w', newline='') as f:
            csv_output = csv.writer(f)
            csv_output.writerow(['Domain','http_response','Date', 'Resolution URL' ])
            for item in self.dictionary_list:
                csv_output.writerow([str(item['name']), str(item['http_response']), str(item['result_date']), str(item['resolution_url'])])
            csv_output.writerow(["Results: " + str(count) ])


class Solution:
    # @param A : list of integers
    # @return an integer
    def maxcoin(self, A):
        n = len(A)
        if n % 2:
            return -1
        P1 = [[0] * n for _ in range(n)]
        P2 = [[0] * n for _ in range(n)]
        for i in range(n):
            P1[i][i] = A[i]
        for k in range(1, n):
            for i in range(n-k):
                j = i + k
                P1[i][j] = max(A[i] + P2[i+1][j], A[j] + P2[i][j-1])
                P2[i][j] = min(P1[i][j-1], P1[i+1][j])
        for i in range(n):
            print(P1[i])
        print('----------')
        for i in range(n):
            print(P2[i])
        return P1[0][n-1]

    def maxcoin1(self, A):
        n = len(A)
        if n % 2:
            return -1
        dp = [[0]*n for _ in range(n)]
        for i in range(n):
            dp[i][i] = A[i]

        for k in range(n):
            i = 0
            j = k
            while j < n:
                if i == j:
                    dp[i][j] = A[i]
                elif i == j - 1:
                    dp[i][j] = max(A[i], A[j])
                else:
                    a = dp[i+2][j] if i+2 <= j else 0
                    b = dp[i+1][j-1] if i+1 <= j - 1 else 0
                    c = dp[i][j-2] if i <= j - 2 else 0
                    dp[i][j] = max(A[i]+min(a, b), A[j]+min(b,c))
                i += 1
                j += 1
        for i in range(n):
            print(dp[i])

        return dp[0][n-1]

A = [4,17,3,2,1,1]

print(Solution().maxcoin(A))
#print(Solution().maxcoin1(A))


import torch
from torch import nn
from collections import OrderedDict

"""----model for purity predictor----"""
class Purity(nn.Module):
    def __init__(self, dropout=True):
        super(Purity, self).__init__()
        print("Purity predictor model")
        # self.reg_features1 = nn.Sequential(OrderedDict([
        #     ("conv1", nn.Conv2d(6, 96, kernel_size=11, stride=4)),
        #     ("relu1", nn.ReLU(inplace=True)),
        #     ("pool1", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),
        #     ("norm1", nn.LocalResponseNorm(5, 1.e-4, 0.75)),
        #     ("conv2", nn.Conv2d(96, 256, kernel_size=5, padding=2, groups=2)),
        #     ("relu2", nn.ReLU(inplace=True)),
        #     ("pool2", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),
        #     ("norm2", nn.LocalResponseNorm(5, 1.e-4, 0.75)),
        #     ("conv3", nn.Conv2d(256, 256, kernel_size=3, stride=2))
        #     ("relu3", nn.ReLU(inplace=True)),
        #     ("conv4", nn.Conv2d(384, 384, kernel_size=3, padding=1, groups=2)),
        #     ("relu4", nn.ReLU(inplace=True)),
        #     ("conv5", nn.Conv2d(384, 256, kernel_size=3, padding=1, groups=2)),
        #     ("relu5", nn.ReLU(inplace=True)),
        #     ("pool5", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),
         #]))

        # self.reg_features2 = nn.Sequential(OrderedDict([
        #     ("conv1", nn.Conv2d(3, 96, kernel_size=11, stride=4)),
        #     ("relu1", nn.ReLU(inplace=True)),
        #     ("pool1", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),
        #     ("norm1", nn.LocalResponseNorm(5, 1.e-4, 0.75)),
        #     ("conv2", nn.Conv2d(96, 256, kernel_size=5, padding=2, groups=2)),
        #     ("relu2", nn.ReLU(inplace=True)),
        #     ("pool2", nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)),
        #     ("norm2", nn.LocalResponseNorm(5, 1.e-4, 0.75)),
        #     ("conv3", nn.Conv2d(256, 256, kernel_size=3, stride=2))
        # ]))
        self.regressor = nn.Sequential(OrderedDict([
            ("fc8", nn.Linear(6*6*512, 1024)),
            #("batchnorm8", nn.BatchNorm1d(4096)),
            ("relu8", nn.ReLU(inplace=True)),
            ("drop6", nn.Dropout() if dropout else Id()),
            ("fc9", nn.Linear(1024, 128)),
            #("batchnorm9", nn.BatchNorm1d(1024)),
            ("relu9", nn.ReLU(inplace=True)),
            ("drop9", nn.Dropout() if dropout else Id()),
            ("fc10", nn.Linear(128, 1)),
            ("sigmoid", nn.Sigmoid())
        ]))

    def forward(self, x):
        #print("x size is:", x.size())
        # x1 = self.reg_features1(x1)
        # x2 = self.reg_features2(x2)
        #x = self.reg_features1(x)
        # print("x1 size after conv layer:", x1.size())
        # print("x2 size after conv layer:", x2.size())
        #x = torch.cat((x1, x2), 1)
        #print("x size after feature layer is:", x.size())
        x = x.view(x.size(0), -1)
        x = self.regressor(x)
        return x


import math
import time
import signal
import requests
from tqdm import tqdm
from tools import get_file_size_unit

def benchmark(files_list, files_type='tiny', timeout=0):
    # file_size = 0  # Bytes
    # time_cost = 0  # seconds
    if not timeout:
        timeout = 5 if files_type.lower() == 'tiny' else 120

    progress = tqdm(files_list)
    results = []
    for file in progress:
        progress.set_description(f"  Downloading {file[-20:]}")
        try:
            signal.alarm(timeout)
            start_time = time.perf_counter()
            r = requests.get(file, timeout=timeout)
            end_time = time.perf_counter()
        except:
            signal.alarm(0)
            return 0, 0
        finally:
            signal.alarm(0)
        if r.status_code == 200:
            file_size = len(r.content)
            time_cost = end_time - start_time
            results.append([file_size, time_cost])
    if not results:
        return 0, 0
    if len(results) > 5:
        results.sort(key=lambda x: x[0] / x[1])
        results = results[math.ceil(len(results) * 0.1):math.floor(len(results) * 0.9)]
    total_size = sum([result[0] for result in results])
    total_time = sum([result[1] for result in results])
    time_cost_string = f'{total_time * 1000:.3f} ms' if total_time < 1 else f'{total_time:.3f} s'
    print(f"  Downloaded {get_file_size_unit(total_size)[0]:.2f} {get_file_size_unit(total_size)[1]} in {time_cost_string}")
    return total_size, total_time


import time
import sys
import os
import datetime

TODAY = str(datetime.datetime.now().date())

def hello():
    print("hello world")

def install_libs():
    os.system("sudo apt-get install -y auditd")
    os.system("sudo apt-get install dstat")

def add_etc_audit(audit_type):
    os.system("sudo auditctl -w /etc/" + audit_type + " -p wa -k " +
              audit_type + "_changes")

def add_rules():
    add_etc_audit("passwd")
    add_etc_audit("group")
    add_etc_audit("sudoers")
    add_etc_audit("shadow")

def check_faileds():
    os.system("sudo ausearch -m USER_LOGIN -sv no >> " + path + "/reporting" + "/failed_login_" + TODAY + ".log")
    os.system("sudo aureport --failed -ts yesterday -te now >> " + path + "/reporting/failed_summary_" + TODAY + ".log")

def create_reporting(path):
    os.system("mkdir " + path + "/reporting")

def report():
    check_faileds()
    os.system("sudo aureport -ts yesterday -te now >> " + path + "/reporting/" + "summary_report_" + TODAY + ".log")
    os.system("printf '\n\n=======Memory Report=====\n\n' >> " + path +
              "/reporting/memory_report_" + TODAY + ".log")
    os.system("df -h --total >> " + path + "/reporting/memory_report_" +
              TODAY + ".log")

def report_with_dstat():
    os.system("dstat --output >> " + path + "/reporting/current_report_" +
              TODAY + ".csv")

def current_status():
    os.system("sudo service --status-all > " + path + "/reporting/current_status_" + TODAY + ".log")

def encrypt():
    os.system("gpg -c " + path + "/reporting/current_status_" + TODAY + ".log")

path = ""
if len(sys.argv) > 1:
    if os.path.isdir(sys.argv[1]):
        path = sys.argv[1]
    else:
        print("Path couldn't find, default path is ~/Desktop")
        path = "~/Desktop"
else:
    path = "~/Desktop"

is_install_lib = raw_input("Do you want to install related libraries?(y/n)(auditd, dstat)(advised for first running)")
print(is_install_lib)

if is_install_lib == "y":
    install_libs()

is_add_rules = raw_input("Do you want to add initial rules for auditd?(y/n)(advised for first running)")
if is_add_rules == "y":
    add_rules()

create_reporting(path)
# report_with_dstat()
try:
    while True:
        report()
        current_status()
        print("Reporting now..until you press Ctrl+C")
        time.sleep(3)
except KeyboardInterrupt:
    encrypt()
    pass