from PIL import Image
from slugify import slugify
from .config import *
import os

def is_supported_album(path):
    folder_name = os.path.basename(path)
    return not folder_name.startswith(".") and os.path.isdir(path)

def extract_extension(path):
    return os.path.splitext(path)[1].lower()

def is_supported_photo(path):
    ext = extract_extension(path)
    return ext in Config.instance().supported_extensions

def find_unique_slug(slugs, lock, name):

    slug = slugify(name, allow_unicode=False, max_length=0,
                   word_boundary=True, separator="-", save_order=True)
    lock.acquire()
    if slug not in slugs:
        return slug
    count = 1
    while True:
        new_slug = slug + "-" + str(count)
        if new_slug not in slugs:
            slug = new_slug
            break
        count += 1

    slugs.add(slug)
    lock.release()

    return slug

def calculate_new_size(input_size, desired_size):
    if input_size[0] <= desired_size[0]:
        return input_size
    reduction_factor = input_size[0] / desired_size[0]
    return int(input_size[0] / reduction_factor), int(input_size[1] / reduction_factor)

def increase_w(left, top, right, bottom, w, h, target_ratio):
    # print("increase width")
    f_l = left
    f_r = right
    f_w = f_r - f_l
    f_h = bottom - top
    next_step_ratio = float((f_w+1)/f_h)
    # print("%d/%d = %f = %f" % (f_w, f_h, next_step_ratio, target_ratio))
    while next_step_ratio < target_ratio and f_l-1 > 0 and f_r+1 < w:
        f_l -= 1
        f_r += 1
        f_w = f_r - f_l
        next_step_ratio = float((f_w+1)/f_h)
        # print("%d/%d = %f = %f" % (f_w, f_h, next_step_ratio, target_ratio))
    return (f_l, top, f_r, bottom)

def increase_h(left, top, right, bottom, w, h, target_ratio):
    # print("increase height")
    f_t = top
    f_b = bottom
    f_w = right - left
    f_h = f_b - f_t
    next_step_ratio = float((f_w+1)/f_h)
    # print("%d/%d = %f = %f" % (f_w, f_h, next_step_ratio, target_ratio))
    while next_step_ratio > target_ratio and f_t-1 > 0 and f_b+1 < h:
        f_t -= 1
        f_b += 1
        f_w = f_b - f_t
        next_step_ratio = float((f_w+1)/f_h)
        # print("%d/%d = %f = %f" % (f_w, f_h, next_step_ratio, target_ratio))
    return (left, f_t, right, f_b)

def increase_size(left, top, right, bottom, w, h, target_ratio):
    # print("increase size")
    f_t = top
    f_b = bottom
    f_l = left
    f_r = right
    f_w = f_r - f_l
    original_f_w = f_r - f_l
    f_h = f_b - f_t
    # print("%d/%d = %f = %f" % (f_w, f_h, float((f_w + 1) / original_f_w), target_ratio))
    next_step_ratio = float((f_w + 1) / original_f_w)
    while next_step_ratio < target_ratio and f_t-1 > 0 and f_b+1 < h and f_l-1 > 0 and f_r+1 < w:
        f_t -= 1
        f_b += 1
        f_l -= 1
        f_r += 1
        f_w = f_r - f_l
        f_h = f_b - f_t
        next_step_ratio = float((f_w + 1) / original_f_w)
        # print("%d/%d = %f = %f" % (f_w, f_h, float((f_w + 1) / original_f_w), target_ratio))
    return (f_l, f_t, f_r, f_b)

def calculate_face_crop_dimensions(input_size, face_size, face_position):

    target_ratio = float(4/3)
    target_upsize_ratio = float(2.5)

    x = int(input_size[0] * float(face_position[0]))
    y = int(input_size[1] * float(face_position[1]))
    w = int(input_size[0] * float(face_size[0]))
    h = int(input_size[1] * float(face_size[1]))

    left = x - int(w/2) + 1
    right = x + int(w/2) - 1
    top = y - int(h/2) + 1
    bottom = y + int(h/2) - 1

    # try to increase
    if float(right - left + 1 / bottom - top - 1) < target_ratio:  # horizontal expansion needed
        left, top, right, bottom = increase_w(
            left, top, right, bottom, input_size[0], input_size[1], target_ratio)
    elif float(right - left + 1 / bottom - top - 1) > target_ratio:  # vertical expansion needed
        left, top, right, bottom = increase_h(
            left, top, right, bottom, input_size[0], input_size[1], target_ratio)

    # attempt to expand photo
    left, top, right, bottom = increase_size(
        left, top, right, bottom, input_size[0], input_size[1], target_upsize_ratio)

    return left, top, right, bottom

def apply_watermark(base_image_path, watermark_image, watermark_ratio):

    with Image.open(base_image_path) as base_image:
        width, height = base_image.size
        orig_watermark_width, orig_watermark_height = watermark_image.size
        watermark_width = int(width * watermark_ratio)
        watermark_height = int(
            watermark_width/orig_watermark_width * orig_watermark_height)
        watermark_image = watermark_image.resize(
            (watermark_width, watermark_height))
        transparent = Image.new(base_image.mode, (width, height), (0, 0, 0, 0))
        transparent.paste(base_image, (0, 0))

        watermark_x = width - watermark_width
        watermark_y = height - watermark_height
        transparent.paste(watermark_image, box=(
            watermark_x, watermark_y), mask=watermark_image)
        transparent.save(base_image_path)

def pick_album_thumbnail(album_photos):
    if len(album_photos) > 0:
        return album_photos[0].thumb
    return ''


import os
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from transformers import pipeline
from torch.utils.data import Dataset, Subset
from tqdm.auto import tqdm
import librosa
import random
import os
import sys
from dataset import CMU_MOSEIASRDataset, CMU_MOSEISLUDataset

def prepare_CMU_MOSEI_ASR_dataset(data_dir, num_class, preprocessor):
    train_data, dev_data, test_data = [], [], []
    df = pd.read_csv(data_dir + "/CMU_MOSEI_Labels.csv")
    for row in df.itertuples():
        filename = row.file + '_' + str(row.index) + '.wav'
        if num_class == 2:
            label = row.label2a
        else:
            # Avoid CUDA error: device-side assert triggered (due to negative label)
            label = row.label7 + 3
        if row.split == 0:
            train_data.append((filename, label))
        elif row.split == 1:
            dev_data.append((filename, label))
        elif row.split == 2:
            test_data.append((filename, label))

    return { "train": CMU_MOSEIASRDataset('train', train_data, data_dir, preprocessor),
            "dev": CMU_MOSEIASRDataset('dev', dev_data, data_dir, preprocessor),
            "test":  CMU_MOSEIASRDataset('test', test_data, data_dir, preprocessor)}

def prepare_CMU_MOSEI_SLU_dataset(data_dir, num_class):
    train_data, dev_data, test_data = [], [], []
    df = pd.read_csv(data_dir + "/CMU_MOSEI_Labels.csv")
    for row in df.itertuples():
        filename = row.file + '_' + str(row.index) + '.wav'
        if num_class == 2:
            label = row.label2a
        else:
            # Avoid CUDA error: device-side assert triggered (due to negative label)
            label = row.label7 + 3
        if row.split == 0:
            train_data.append((filename, label))
        elif row.split == 1:
            dev_data.append((filename, label))
        elif row.split == 2:
            test_data.append((filename, label))

    return { "train": CMU_MOSEISLUDataset('train', train_data, data_dir),
            "dev": CMU_MOSEISLUDataset('dev', dev_data, data_dir),
            "test":  CMU_MOSEISLUDataset('test', test_data, data_dir)}


import ctypes
import os
import time
import random
from bs4 import BeautifulSoup
import requests
import re
import send2trash

def setWallpaper(filepath):
    #checks that filepath given is an existing one
    if not os.path.isfile(filepath):
        return False

    #checks that file has image extension
    if not re.search('.jpg', filepath) and not re.search('.png', filepath):
        return False

    #configuration
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, filepath, 0)

    print('\nDone!')
    return True

def downloadWallpaper(downloadlink, directory):
    if downloadlink is None:
        return
    #makes an http request
    r = requests.get(downloadlink, allow_redirects=True)

    #retrieves filename from cd and creates save directory
    full_file_name = getFilename(r.headers.get('content-disposition'))
    full_file_name = os.path.join(directory, full_file_name) + '.jpg'

    #creates image file
    open(full_file_name, 'wb').write(r.content)
    time.sleep(1)

    setWallpaper(full_file_name)
    return

def getFilename(cd):
    #checks that content-diposition exists
    if not cd:
        return None

    #finds file name from content-disposition
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
        return None
    fname[0] = fname[0].strip('"')
    return fname[0]

def getWallpaperDownloadURL(link):

    #gets webpage html from given link
    result = requests.get(link)
    pagehtml = result.content

    #parses through html to find img elements
    soup = BeautifulSoup(pagehtml, 'html.parser')
    samples = soup.find_all('a', attrs={'title': 'Download photo'})

    #checks that at least one img element was found
    if not len(samples):
        print('No images found for keyword: ' + re.sub('https://unsplash.com/search/photos/', '', link))
        return None

    #chooses random image url to from list of img elements
    size = len(samples)
    x = random.choice(range(size))
    imglink = samples[x]['href']
    print('Setting desktop background to an image of ' + re.sub('https://unsplash.com/search/photos/', '', link))
    return imglink

def unsplashSearch(keyword):
    #creates unsplash search link randomly
    if keyword == 'random':
        randomlibrary = ['https://unsplash.com/t/wallpapers', 'https://unsplash.com/t/arts-culture',
                         'https://unsplash.com/t/textures-patterns', 'https://unsplash.com/t/architecture',
                         'https://unsplash.com/t/animals', 'https://unsplash.com/t/travel',
                         'https://unsplash.com/t/food-drink']
        link = random.choice(randomlibrary)

    #creates unsplash search link for given keyword
    else:
        keyword = keyword.replace(' ', '-')
        link = 'https://unsplash.com/search/photos/' + keyword

    return link

def getOldestFile(directory):
    #checks that path is existing directory
    if not os.path.isdir(directory):
        return None

    #gets filenames of images in directory
    imagelist = os.listdir(directory)

    if not len(imagelist):
        return None

    timelist = []
    pathlist = []

    #creates list with file times and corresponding path list
    for image in imagelist:
        path = os.path.join(directory, image)
        pathlist.append(path)
        timelist.append(os.path.getctime(path))

    #finds oldest file from minimum time
    targetimage = timelist.index(min(timelist))
    return pathlist[targetimage]

def manageFolder(directory):
    #checks if folder has too many files
    if len(os.listdir(directory)) > 7:
        f = getOldestFile(directory)
        if f is None:
            return
        elif re.search('unsplash', f):
            send2trash.send2trash(f)
    return


from meta_policy_search.policies.networks.mlp import create_mlp, forward_mlp
from meta_policy_search.policies.distributions.diagonal_gaussian import DiagonalGaussian
from meta_policy_search.policies.base import Policy
from meta_policy_search.utils import Serializable, logger
from meta_policy_search.utils.utils import remove_scope_from_name

import tensorflow as tf
import numpy as np
from collections import OrderedDict

class GaussianMLPPolicy(Policy):
    """
    Gaussian multi-layer perceptron policy (diagonal covariance matrix)
    Provides functions for executing and updating policy parameters
    A container for storing the current pre and post update policies

    Args:
        obs_dim (int): dimensionality of the observation space -> specifies the input size of the policy
        action_dim (int): dimensionality of the action space -> specifies the output size of the policy
        name (str): name of the policy used as tf variable scope
        hidden_sizes (tuple): tuple of integers specifying the hidden layer sizes of the MLP
        hidden_nonlinearity (tf.op): nonlinearity function of the hidden layers
        output_nonlinearity (tf.op or None): nonlinearity function of the output layer
        learn_std (boolean): whether the standard_dev / variance is a trainable or fixed variable
        init_std (float): initial policy standard deviation
        min_std( float): minimal policy standard deviation

    """

    def __init__(self, *args, init_std=1., min_std=1e-6, **kwargs):
        # store the init args for serialization and call the super constructors
        Serializable.quick_init(self, locals())
        Policy.__init__(self, *args, **kwargs)

        self.min_log_std = np.log(min_std)
        self.init_log_std = np.log(init_std)

        self.init_policy = None
        self.policy_params = None
        self.obs_var = None
        self.mean_var = None
        self.log_std_var = None
        self.action_var = None
        self._dist = None

        self.build_graph()

    def build_graph(self):
        """
        Builds computational graph for policy
        """
        with tf.variable_scope(self.name):
            # build the actual policy network
            self.obs_var, self.mean_var = create_mlp(name='mean_network',
                                                     output_dim=self.action_dim,
                                                     hidden_sizes=self.hidden_sizes,
                                                     hidden_nonlinearity=self.hidden_nonlinearity,
                                                     output_nonlinearity=self.output_nonlinearity,
                                                     input_dim=(None, self.obs_dim,)
                                                     )

            with tf.variable_scope("log_std_network"):
                log_std_var = tf.get_variable(name='log_std_var',
                                              shape=(1, self.action_dim,),
                                              dtype=tf.float32,
                                              initializer=tf.constant_initializer(self.init_log_std),
                                              trainable=self.learn_std
                                              )

                self.log_std_var = tf.maximum(log_std_var, self.min_log_std, name='log_std')

            # symbolically define sampled action and distribution
            self.action_var = self.mean_var + tf.random_normal(shape=tf.shape(self.mean_var)) * tf.exp(log_std_var)
            self._dist = DiagonalGaussian(self.action_dim)

            # save the policy's trainable variables in dicts
            current_scope = tf.get_default_graph().get_name_scope()
            trainable_policy_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=current_scope)
            self.policy_params = OrderedDict([(remove_scope_from_name(var.name, current_scope), var) for var in trainable_policy_vars])

    def get_action(self, observation):
        """
        Runs a single observation through the specified policy and samples an action

        Args:
            observation (ndarray) : single observation - shape: (obs_dim,)

        Returns:
            (ndarray) : single action - shape: (action_dim,)
        """
        observation = np.expand_dims(observation, axis=0)
        action, agent_infos = self.get_actions(observation)
        action, agent_infos = action[0], dict(mean=agent_infos['mean'][0], log_std=agent_infos['log_std'][0])
        return action, agent_infos

    def get_actions(self, observations):
        """
        Runs each set of observations through each task specific policy

        Args:
            observations (ndarray) : array of observations - shape: (batch_size, obs_dim)

        Returns:
            (ndarray) : array of sampled actions - shape: (batch_size, action_dim)
        """
        assert observations.ndim == 2 and observations.shape[1] == self.obs_dim

        sess = tf.get_default_session()
        actions, means, logs_stds = sess.run([self.action_var, self.mean_var, self.log_std_var],
                                             feed_dict={self.obs_var: observations})
        rnd = np.random.normal(size=means.shape)
        actions = means + rnd * np.exp(logs_stds)

        assert actions.shape == (observations.shape[0], self.action_dim)
        return actions, dict(mean=means, log_std=logs_stds)

    def log_diagnostics(self, paths, prefix=''):
        """
        Log extra information per iteration based on the collected paths
        """
        log_stds = np.vstack([path["agent_infos"]["log_std"] for path in paths])
        logger.logkv(prefix + 'AveragePolicyStd', np.mean(np.exp(log_stds)))

    def load_params(self, policy_params):
        """
        Args:
            policy_params (ndarray): array of policy parameters for each task
        """
        raise NotImplementedError

    @property
    def distribution(self):
        """
        Returns this policy's distribution

        Returns:
            (Distribution) : this policy's distribution
        """
        return self._dist

    def distribution_info_sym(self, obs_var, params=None):
        """
        Return the symbolic distribution information about the actions.

        Args:
            obs_var (placeholder) : symbolic variable for observations
            params (dict) : a dictionary of placeholders or vars with the parameters of the MLP

        Returns:
            (dict) : a dictionary of tf placeholders for the policy output distribution
        """
        if params is None:
            with tf.variable_scope(self.name):
                obs_var, mean_var = create_mlp(name='mean_network',
                                               output_dim=self.action_dim,
                                               hidden_sizes=self.hidden_sizes,
                                               hidden_nonlinearity=self.hidden_nonlinearity,
                                               output_nonlinearity=self.output_nonlinearity,
                                               input_var=obs_var,
                                               reuse=True,
                                               )
                log_std_var = self.log_std_var
        else:
            mean_network_params = OrderedDict()
            log_std_network_params = []
            for name, param in params.items():
                if 'log_std_network' in name:
                    log_std_network_params.append(param)
                else:# if 'mean_network' in name:
                    mean_network_params[name] = param

            assert len(log_std_network_params) == 1
            obs_var, mean_var = forward_mlp(output_dim=self.action_dim,
                                            hidden_sizes=self.hidden_sizes,
                                            hidden_nonlinearity=self.hidden_nonlinearity,
                                            output_nonlinearity=self.output_nonlinearity,
                                            input_var=obs_var,
                                            mlp_params=mean_network_params,
                                            )

            log_std_var = log_std_network_params[0]

        return dict(mean=mean_var, log_std=log_std_var)

    def distribution_info_keys(self, obs, state_infos):
        """
        Args:
            obs (placeholder) : symbolic variable for observations
            state_infos (dict) : a dictionary of placeholders that contains information about the
            state of the policy at the time it received the observation

        Returns:
            (dict) : a dictionary of tf placeholders for the policy output distribution
        """
        raise ["mean", "log_std"]


for _ in range(int(input())) :
  stk1 = []
  stk2 = []

  for ch in input() :
    if ch == "<" :
      if len(stk1) :
        stk2.append(stk.pop())
    elif ch == ">" :
      if len(stk2) :
        stk1.append(stk2.pop())
    elif ch == "-" :
      if len(stk1) :
        stk1.pop()
    else :
      stk1.append(ch)
  print(''.join(stk1) + ''.join(reversed(Stk2)))


#User function Template for python3

class Solution:
    def findK(self, matrix, n, m, k):
        # Write Your Code here
        c=len(matrix[0])
        r=len(matrix)
        ans=[]
        d=e=i=0
        while(True):
            for j in range(i,c-i):
                e=matrix[i][j]
                ans.append(e)
                d+=1
            if(d>=(r*c)):
                break
            for j in range(i+1,r-i):
                e=matrix[j][c-1-i]
                ans.append(e)
                d+=1
            if(d>=(r*c)):
                break
            for j in reversed(range(i,c-1-i)):
                e=matrix[r-1-i][j]
                ans.append(e)
                d+=1
            if(d>=(r*c)):
                break
            for j in reversed(range(i+1,r-1-i)):
                e=matrix[j][i]
                ans.append(e)
                d+=1
            if(d>=(r*c)):
                break
            i+=1
        return ans[k-1]

#{
 # Driver Code Starts

#Initial Template for Python 3

for _ in range(int(input())):
    n, m, k = map(int,input().split())
    a = [
            list(map(int,input().split()))
            for _ in range(n)
        ]

    ob = Solution()
    print(ob.findK(a,n,m,k))

# } Driver Code Ends

Find kth element of spiral matrix - GFG/find-kth-element-of-spiral-matrix.py


import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
import requests as requests
import time
import cfg as cfg
from log.log import log_error

def get(channel_id):
    #
    str_listing = getlisting(channel_id, 0)
    xml_listing = ET.fromstring(str_listing)
    #
    if check_enabled(xml_listing):
        return convert_to_dict(xml_listing)
    else:
        return {}

def convert_to_dict(data):
    json_channel = {}
    #
    lastitem = 'am'
    nextday_start = 0
    nextday_end = 0
    for programme in data:
        json_programme = {}
        #
        d = datetime.strptime(data.attrib['date'], '%d/%m/%Y').date()
        #
        t_start = datetime.strptime(programme.find('start').text, '%H%M').time()
        if lastitem == 'pm' and t_start.hour < 12:
            nextday_start = 1
        lastitem = 'am' if t_start.hour < 12 else 'pm'
        d_start = d + timedelta(days=nextday_start)
        start = datetime.combine(d_start, t_start)
        #
        t_end = datetime.strptime(programme.find('end').text, '%H%M').time()
        if nextday_start == 1 or t_end.hour < t_start.hour:
            nextday_end = 1
        d_end = d + timedelta(days=nextday_end)
        end = datetime.combine(d_end, t_end)
        #
        if start > datetime.now() or end > datetime.now():
            json_programme['start'] = start.isoformat(' ')
            json_programme['end'] = end.isoformat(' ')
            json_programme['title'] = programme.find('title').text
            try:
                json_programme['subtitle'] = programme.find('subtitle').text
            except:
                json_programme['subtitle'] = ''
            json_programme['desc'] = programme.find('desc').text
            #
            id = json_programme['start']
            json_channel[id] = json_programme
        #
    return json_channel

def check_enabled(data):
    if data.attrib['source'] == 'Disabled':
        return False
    else:
        return True

def getlisting(channel_id, day):
    #
    # Use of bleb.org data requires API calls to be 2 seconds apart
    time.sleep(2)
    #
    headers = {'User-Agent': 'TV::Fetch::XML, {app_name} - {email}'.format(app_name=cfg.app_name,
                                                                           email=cfg.developer_email),
               'Connection': 'close',
               'content-type': 'text/xml; charset=utf-8'}
    #
    r = requests.get('http://www.bleb.org/tv/data/listings/{day}/{channel_id}.xml'.format(day=day,
                                                                                channel_id=channel_id),
                     headers=headers)
    #
    if r.status_code == requests.codes.ok:
        return r.content
    else:
        log_error('Request to bleb.org failed - {status}'.format(status=r.status_code))
        return None


from typing import Optional

from pydantic import BaseModel, validator

class Curso(BaseModel):
    id: Optional[int] = None
    titulo: str
    aulas: int
    horas: int

    @validator("titulo")
    def validar_titulo(cls, value: str):
        palavras = value.split(" ")
        if len(palavras) < 3:
            raise ValueError("O título deve ter pelo menos 3 palavras.")

        if value.islower():
            raise ValueError("O título deve ser capitalizado")

        return value

    @validator("aulas")
    def validar_aulas(cls, value: int):
        if value <= 12:
            raise ValueError("O nº de aulas deve ser maior que 12")

        return value

    @validator("horas")
    def validar_horas(cls, value: int):
        if value <= 10:
            raise ValueError("O nº de horas deve ser maior que 10")

        return value

cursos = [
    Curso(id=0, titulo="Programação para leigos", aulas=112, horas=58),
    Curso(id=1, titulo="Algoritmos e Lógica de Programação", aulas=87, horas=67),
]


from django.views.generic import DetailView, TemplateView

from archive.models import Post
from search.forms import SearchForm

class PostListView(TemplateView):
    template_name = 'posts/list.html'
    def get_context_data(self, **kwargs):
        data = super(PostListView, self).get_context_data(**kwargs)
        posts = Post.objects.filter(parent=None).order_by('-date_created')

        form = SearchForm(self.request.GET or None)
        if form.is_valid():
            posts = form.search()

        offset = int(self.request.GET.get('offset',0))

        data['posts'] = posts[offset:offset+15]
        return data

class PostDetailView(DetailView):
    context_object_name = 'post'
    model = Post
    template_name = 'posts/detail.html'


""" In this Python program the content in the file will get
    stored in another file in reverse order . """

file = open("C:\\Users\\jaspr\\OneDrive\\Desktop\\python in vs code\\abc.txt",'a')

with open("C:\\Users\\jaspr\\OneDrive\\Desktop\\python in vs code\\abc.txt",'r') as myfile:
    data = myfile.read()

data_1 = data[::-1]

file.write(data_1)

file.close()


import math

def Cantor(num):
    if num == 1:
        return True
    else:
        cantorSet = dict()
        while num not in cantorSet.keys():
            cantorSet.update({num: 0})
            num = round(num*3, 6)
            print(num)
            head = int(math.floor(num))
            if head == 1:
                return False
            else:
                num -= head
        return True

def main():
    while True:
        input_ = input()
        if input_ == 'END':
            break
        else:
            input_ = float(input_)
            if Cantor(input_):
                print("MEMBER")
            else:
                print("NON-MEMBER")

main()


f_xml = open('icd_fin.xml','r')
f_json = open('icd_json.json', 'w')

with f_xml as fx:
    x=0
    for line in fx:
        x =x+1
        nazwa = line[line.find('<nazwa>')+7:line.find('</nazwa>')]
        kod = line[line.find('<kod>')+5:line.find('</kod>')]
        new_line ='{ "pk":'+ str(x) +', "model": "app.Choroba", "fields": { "kod":"' +kod+ '", "nazwa":"' + nazwa+ '"  } }, \n'
        f_json.write(new_line)

    f_json.close()


#!/usr/bin/python3
""" The console
FileStorage class module
"""
import json
from models.base_model import BaseModel
from models.user import User
from models.place import Place
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.review import Review

class FileStorage:
    """
    Class that serializes object/instances to a JSON file
    and deserializes JSON file to objects/instances
    """

    __file_path = "file.json"
    __objects = {}

    def all(self):
        """
        function that returns the dictionary __objects
        """
        return FileStorage.__objects

    def save(self):
        """serialise"""
        new_dict = {}
        for key, value in FileStorage.__objects.items():
            new_dict[key] = value.to_dict()
        with open(FileStorage.__file_path, "w")as f:
            json.dump(new_dict, f)

    def new(self, obj):
        """set obj """
        obj_id = obj.id
        obj_name = obj.__class__.__name__
        FileStorage.__objects[obj_name + "." + str(obj_id)] = obj

    def reload(self):
        """ deserialised """
        self.__objects = {}
        try:
            with open(self.__file_path, "r") as f:
                data = json.load(f)
                for key, value in data.items():
                    cls = value["__class__"]
                    obj = eval(cls)(**value)
                    self.__objects[key] = obj
        except FileNotFoundError:
            pass


#To the fish image
#Extract the fish from the image and fill the whole contourn of the fish.
#(Region / Hole FIlling)

import cv2 as cv
import numpy as np

#Read image
img2 = cv.imread('Pescado.png')

#Image to grayscale
gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)

#Threshold the input image to binary
ret, th1 = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)

#Invert image
ret, th2 = cv.threshold(th1, 127, 255, cv.THRESH_BINARY_INV)

#Kernel
kernel = np.ones((5,5), np.uint8)

#Find contourns
blurred = cv.GaussianBlur(gray, (5,5), 0)
cnn1 = cv.Canny(gray, 220, 255)
cnn2 = cv.dilate(cnn1, None, iterations=1)
cnn3 = cv.erode(cnn2, None, iterations=1)
cnts,_ = cv.findContours(cnn3, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

#Fill image
res = cv.drawContours(th2, cnts, -1, (255, 255, 255), thickness= cv.FILLED)

#Concat images & print results
img_org = cv.hconcat([gray, th1, cnn1])
img_org2 = cv.hconcat([cnn2, cnn3, res])
img_org3 = cv.vconcat([img_org, img_org2])

cv.imwrite("Final_results.jpg", img_org3)
cv.imshow('Original_Image_Fish', img2)
cv.imshow('Contourn_Filling_Process', img_org3)

cv.waitKey(0)
cv.destroyAllWindows()


from Overlap import Overlap
from itertools import permutations
from Overlap import pick_Maximal_overlap, pick_maximal_overlap_with_precomputed_kmers
import time
from collections import defaultdict, Counter

# brute force
def NaiveSCS(reads):
    """ Returns shortest common superstring of given strings,
        assuming no string is a strict substring of another """
    shortest_superstring = None
    for s in permutations(reads): # returns every possible ordering in the list of reads as tuples
        sup = s[0]
        for i in range(len(reads) - 1):
            overlap_len = Overlap(s[i], s[i+1], min_length=1)
            sup += s[i+1][overlap_len:]
        if shortest_superstring is None or len(sup) < len(shortest_superstring):
            shortest_superstring = sup
    return shortest_superstring

def SCS_list(reads):
    # Returns list of all superstrings that are tied for shortest
    shortest_superstrings = set()
    shortest_superstring = NaiveSCS(reads)
    for s in permutations(reads): # returns every possible ordering in the list of reads as tuples
        shortest = NaiveSCS(s)
        if len(shortest) == len(shortest_superstring):
            shortest_superstrings.add(shortest)
    return shortest_superstrings

def GreedySCS(reads, k):
    """ Greedy shortest-common-superstring merge.
    Repeat until no edges (overlaps of length >= k)
    remain. """
    start = time.process_time()

    read_a, read_b, max_overlap_length = pick_Maximal_overlap(reads, k)
    while max_overlap_length > 0:
        reads.remove(read_a)
        reads.remove(read_b)
        reads.append(read_a + read_b[max_overlap_length:])
        read_a, read_b, max_overlap_length = pick_Maximal_overlap(reads, k)

    end = time.process_time()
    print(end-start)
    return ''.join(reads)

def FasterGreedySCS(reads, k=10): # uses precomputed kmers, the rest is the same as the GreedySCS
    start = time.process_time()

    read_a, read_b, max_overlap_length = pick_maximal_overlap_with_precomputed_kmers(reads, k)
    while max_overlap_length > 0:
        reads.remove(read_a)
        reads.remove(read_b)
        reads.append(read_a + read_b[max_overlap_length:])
        read_a, read_b, max_overlap_length = pick_maximal_overlap_with_precomputed_kmers(reads, k)

    end = time.process_time()
    print(end-start)
    return ''.join(reads)


name = input()
initial_points = 301
total_points = initial_points
won = False
unsuccessful = 0
successful = 0

command = input()

while command != "Retire":
    points_gain = 0
    points = int(input())
    if command == "Single":
        points_gain = points
    elif command == "Double":
        points_gain = 2 * points
    elif command == "Triple":
        points_gain = 3 * points

    if total_points < points_gain:
        unsuccessful += 1
    else:
        successful += 1

        total_points -= points_gain
        if total_points == 0:
            won = True
            break

    command = input()

if won:
    print(f"{name} won the leg with {successful} shots.")
else:
    print(f"{name} retired after {unsuccessful} unsuccessful shots.")


if __name__ == "__main__":
    import utils

    utils.import_depends()

from brokertest import TestBrokerCommand

class TestUpdateOS(TestBrokerCommand):
    def test_100_check_host_for_cm(self):

        command = "search host --host_environment prod --buildstatus ready" \
                  " --osname linux --osversion 6.1-x86_64 --archetype aquilon"
        out = self.commandtest(command.split())
        self.matchoutput(out, "aquilon91.aqd-unittest.ms.com",
                         command)

    def test_100_require_just(self):
        self.justificationmissingtest(["update_os", "--archetype", "aquilon", "--osname", "linux",
                                       "--osversion", "6.1-x86_64", "--lifecycle", "production"], auth=True,
                                      msgcheck=False)

    def test_110_not_require_just(self):
        self.noouttest(["update_os", "--archetype", "aquilon", "--osname", "linux",
                        "--osversion", "6.1-x86_64", "--comments", "'Comments are not "
                                                                   "harmful to change'"])

    def test_120_require_just_success(self):
        self.noouttest(["update_os", "--archetype", "aquilon", "--osname", "linux",
                        "--osversion", "6.1-x86_64", "--lifecycle", "production"] + self.valid_just_tcm)


def solution(s):
    s_len = len(s)
    answer = [''] * (s_len // 2)
    for i in range(s_len // 2):
        base = s[:i + 1] # 기준 문자열
        count = 1
        for j in range(i + 1, s_len, i + 1):
            new = s[j:i + j + 1] # 기준 뒤 문자열
            if base == new:
                count += 1
            else:
                if count != 1:
                    answer[i] += str(count)
                answer[i] += base
                count = 1
                base = new
        if count != 1:
            answer[i] += str(count)
        answer[i] += base

        s_len = min(len(answer[i]), s_len)

    return s_len

# 1. 문자열을 자르는 단위마다 결과를 array에 저장해주고, 결과로 나온 문자열의 길이를 비교해주기
# 2. 첫 번째 for 문에서는 기준 문자열을 base 변수에 넣어주었다. 문자열이 몇 번 반복되었는지 확인하기 위해 count 변수를 선언한다.
# 3. 두 번째 for 문에서는 그 다음 문자열을 new 변수에 넣어주었다.
# 3-1. base와 new가 같다면 기준 문자열은 변하지 않으며 count에 1을 더해준다. 다음 반복문에서 new를 그 다음 문자열로 업데이트해주어 다시 base와 비교한다.
# 3-2. base와 new가 다르다면 base를 결과 문자열에 더해주었다. (count가 1이 아닌 경우 count도 더해준다). new를 기준 문자열로 삼기 위해 base를 new로 업데이트해주고 count를 1로 초기화한다. 다음 반복문에서 new를 그 다음 문자열로 업데이트해주어 다시 base와 비교한다.
# 4. 두 번째 for문을 다 돌고 나온 결과 문자열의 길이를 비교하여 더 작은 길이로 업데이트해준다.

김민정/이것이 취업을 위한 코딩 테스트다 with Python/Chapter 04 구현/Part 03 알고리즘 유형별 기출문제/구현_문자열 압축.py

구현_문자열 압축.py


import cv2 as cv
from cv2 import waitKey
from numpy import int0, uint8

class Detect:
    def color_test(source):
        values = Detect.Settings.get_values()
        source = cv.GaussianBlur(source, (7, 7), 0)

        mask = Detect._create_mask(
            source,
            (
                values[Detect.Settings.H1],
                values[Detect.Settings.S1],
                values[Detect.Settings.V1],
            ),
            (
                values[Detect.Settings.H2],
                values[Detect.Settings.S2],
                values[Detect.Settings.V2]
            )
        )

        cv.imshow("threshold", mask)

    def _create_mask(source, hsv_min, hsv_max):
        hsv_min = Detect.Colors.cvstd(*hsv_min)
        hsv_max = Detect.Colors.cvstd(*hsv_max)

        hsv_image = cv.cvtColor(source, cv.COLOR_BGR2HSV)

        return cv.inRange(hsv_image, hsv_min, hsv_max)

    def demo(self, source, min_area=None, max_area=None):
        blur = cv.GaussianBlur(source, (7, 7), 0)

        mask_pink = Detect._create_mask(
            blur,
            Detect.Colors.PINK[0],
            Detect.Colors.PINK[1]
        )

        mask_blue = Detect._create_mask(
            blur,
            Detect.Colors.BLUE[0],
            Detect.Colors.BLUE[1]
        )

        mask_orange = Detect._create_mask(
            blur,
            Detect.Colors.ORANGE[0],
            Detect.Colors.ORANGE[1]
        )

        mask = mask_pink | mask_blue | mask_orange
        contours, _ = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

        if min_area == None and max_area == None:
            min_area = Detect.Settings.get_values()[Detect.Settings.MIN_AREA]
            max_area = Detect.Settings.get_values()[Detect.Settings.MAX_AREA]

        count = 0
        for contour in contours:
            rect = cv.minAreaRect(contour)
            box = cv.boxPoints(rect)
            box = int0(box)

            area = cv.contourArea(contour)
            if area >= min_area and area <= max_area:
                cv.drawContours(source, [box], -1, (255, 255, 255), 2)
                count += 1

        print(min_area, max_area, count)

        return str(count)

    def detect(
            self,
            source,
            thr_min,
            thr_max,
            blur,
            min_area,
            max_area
        ):

        image = source.copy()

        source = cv.cvtColor(source, cv.COLOR_BGR2GRAY)

        _, source = cv.threshold(source, thr_min, thr_max, cv.THRESH_BINARY)
        if blur:
            source = cv.medianBlur(source, blur)

        cv.imshow("image_thr", source)
        cv.waitKey()

        contours, _ = cv.findContours(source, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

        count = 0
        for contour in contours:
            rect = cv.minAreaRect(contour)
            box = cv.boxPoints(rect)
            box = int0(box)

            x1, y1 = box[0]
            x2, y2 = box[1]
            x3, y3 = box[2]

            a = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
            a **= 1/2

            b = (x3 - x1)*(x3 - x1) + (y3 - y1)*(y3 - y1)
            b **= 1/2

            area = a*b
            coeff = b/a

            if (
                (area > min_area and area < max_area) and
                (coeff > 1.01 and coeff < 1.04)
            ):
                print(a*b, b/a, "", sep="\n")
                cv.drawContours(image, [box], -1, (255, 255, 0), 2)
                cv.imshow("image", image)
                cv.waitKey()
                count += 1

        print(count)
        cv.imshow("image", image)
        cv.destroyAllWindows()

    class Settings:
        WIN_NAME = "settings"

        H1 = "H1"
        S1 = "S1"
        V1 = "V1"

        H2 = "H2"
        S2 = "S2"
        V2 = "V2"

        MIN_AREA = "MIN_AREA"
        MAX_AREA = "MAX_AREA"

        AREA = 5000

        def __init__(self):
            cv.namedWindow(self.WIN_NAME, cv.WINDOW_NORMAL)

            cv.createTrackbar(self.H1, self.WIN_NAME, 0, 360, self.void)
            cv.createTrackbar(self.S1, self.WIN_NAME, 0, 100, self.void)
            cv.createTrackbar(self.V1, self.WIN_NAME, 0, 100, self.void)

            cv.createTrackbar(self.H2, self.WIN_NAME, 0, 360, self.void)
            cv.createTrackbar(self.S2, self.WIN_NAME, 0, 100, self.void)
            cv.createTrackbar(self.V2, self.WIN_NAME, 0, 100, self.void)

            cv.createTrackbar(self.MIN_AREA, self.WIN_NAME, 0, self.AREA, self.void)
            cv.createTrackbar(self.MAX_AREA, self.WIN_NAME, 0, self.AREA, self.void)

        def get_values():
            return {
                Detect.Settings.H1: cv.getTrackbarPos(Detect.Settings.H1, Detect.Settings.WIN_NAME),
                Detect.Settings.S1: cv.getTrackbarPos(Detect.Settings.S1, Detect.Settings.WIN_NAME),
                Detect.Settings.V1: cv.getTrackbarPos(Detect.Settings.V1, Detect.Settings.WIN_NAME),

                Detect.Settings.H2: cv.getTrackbarPos(Detect.Settings.H2, Detect.Settings.WIN_NAME),
                Detect.Settings.S2: cv.getTrackbarPos(Detect.Settings.S2, Detect.Settings.WIN_NAME),
                Detect.Settings.V2: cv.getTrackbarPos(Detect.Settings.V2, Detect.Settings.WIN_NAME),

                Detect.Settings.MIN_AREA: cv.getTrackbarPos(Detect.Settings.MIN_AREA, Detect.Settings.WIN_NAME),
                Detect.Settings.MAX_AREA: cv.getTrackbarPos(Detect.Settings.MAX_AREA, Detect.Settings.WIN_NAME)
            }

        def set_values(values):
            cv.setTrackbarPos(Detect.Settings.H1, Detect.Settings.WIN_NAME, values[0][0])
            cv.setTrackbarPos(Detect.Settings.S1, Detect.Settings.WIN_NAME, values[0][1])
            cv.setTrackbarPos(Detect.Settings.V1, Detect.Settings.WIN_NAME, values[0][2])

            cv.setTrackbarPos(Detect.Settings.H2, Detect.Settings.WIN_NAME, values[1][0])
            cv.setTrackbarPos(Detect.Settings.S2, Detect.Settings.WIN_NAME, values[1][1])
            cv.setTrackbarPos(Detect.Settings.V2, Detect.Settings.WIN_NAME, values[1][2])

        def void(*args, **kwargs): pass

    class Colors:
        PINK = (
            (257, 13, 53),
            (360, 100, 100)
        )

        ORANGE = (
            (0, 51, 39),
            (54, 100, 100)
        )

        BLUE = (
            (170, 64, 63),
            (214, 100, 100)
        )

        def cvstd(H, S, V):
            return uint8([
                    (H/360) * 180,
                    (S/100) * 255,
                    (V/100) * 255
                ])

        def increase_brightness(source, value=30):
            hsv = cv.cvtColor(source, cv.COLOR_BGR2HSV)
            h, s, v = cv.split(hsv)

            lim = 255 - value
            v[v > lim] = 255
            v[v <= lim] += value

            hsv = cv.merge((h, s, v))
            return cv.cvtColor(hsv, cv.COLOR_HSV2BGR)

class SettingsProduction:
    #THR
    THRESHOLD_MIN = 150
    THRESHOLD_MAX = 255

    #BLUR
    BLUR = 3

    #AREA
    MIN_AREA = 4220
    MAX_AREA = 4740

    #PERI
    PERI_COEFF = 0.01

if __name__ == "__main__":
    detect = Detect()
    detect.Settings()

    Detect.Settings.set_values(Detect.Colors.ORANGE)

    camera = cv.VideoCapture(1)
    while True:
        res, source = camera.read()
        # source = cv.resize(source,
        #     (int(len(source[0])*1.5),
        #     int(len(source)*1.5))
        # )

        color_test = 0
        if not color_test:
            print(detect.demo(source))
        else:
            Detect.color_test(source)

        cv.imshow("source", source)

        if waitKey(1) == 27:
            cv.destroyAllWindows()
            break


import torch
import os
from PIL import Image
import matplotlib.pyplot as plt
import config
import cv2
import numpy as np

from transform_utils import convert_to_binary_inv,convert_to_binary,adapt_size
from torchvision import datasets, transforms

ToTensor=transforms.ToTensor()

def append_dir_bigset(package_x,package_y,basepath,item_y):
    path = os.listdir(basepath)
    for item in path:
        item_x=Image.open(basepath + item)
        item_x = np.array(item_x)
        # if True:
        #     print(item_x.shape)
        #
        #     plt.matshow(item_x)
        #     plt.show()
        package_x.append(torch.tensor(item_x,dtype=torch.uint8))
        package_y.append(torch.tensor(item_y,dtype=torch.uint8))
        # return

if __name__ =="__main__":

    package_x = list()
    package_y = list()
    base_dir = 'E:/bigset/Train/'
    if 1:
        for i in range(0,10):
            append_dir_bigset(package_x,package_y,base_dir+str(i)+"/",config.CLASS.index(str(i)))
    base_dir = 'E:/bigset/Validation/'
    if 1:
        for i in range(0,10):
            append_dir_bigset(package_x,package_y,base_dir+str(i)+"/",config.CLASS.index(str(i)))
    print(len(package_x),len(package_y))
    torch.save([package_x,package_y],'package_bigset.pth')


#!/usr/bin/python
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
import sys
import random

min = 0;
max = 255;
alignment = "2";

if len(sys.argv) == 2:
    max = int(sys.argv[1])

elif len(sys.argv) == 3:
    min = int(sys.argv[1])
    max = int(sys.argv[2])

elif len(sys.argv) == 4:
    min = int(sys.argv[1])
    max = int(sys.argv[2])
    alignment = sys.argv[3]
else:
    print( "%s [max]" % (sys.argv[0]) )
    print( "%s [min] [max]" % (sys.argv[0]) )
    print( "%s [min] [max] [align]" % (sys.argv[0]) )
    print( "by devast8a <devast8a[at]whitefirex.com>\n----------------------------------------\n\n" )

format = "0x%0" + alignment + ".X, "

random.seed()

a = []
for x in xrange(min, max+1):
    while 1:
        v = random.randint(min, max)
        if v not in a:
            a.append(v)
            break

    sys.stdout.write( format % (v) );
    if x % 8 == 7:
        sys.stdout.write( "\n" );


from django.shortcuts import render
from .forms import WatchlistForm
from django.views.generic import ListView, DeleteView
from .models import WatchList
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from stocks.stockquote import getQuotes
from django.db.models import Q
import json
from django.http import HttpResponse
from stocks.models import BSEStocks, NSEStocks

class StockListView(ListView):
    template_name = 'watchlist/watchlist.html'
    model = WatchList
    context_object_name = 'watchlist'

    def get(self, request):
        form = WatchlistForm()
        current_user = request.user

        symbol = current_user.watchlist_set.values_list('stock_name', flat=True)
        target_price = current_user.watchlist_set.values_list('target_price', flat=True)
        comment = current_user.watchlist_set.values_list('comment', flat=True)
        pk = current_user.watchlist_set.values_list('pk', flat=True)

        q = getQuotes(symbol)
        q.run()

        mylist = zip(symbol, q.stocknamelist, q.closepricelist, target_price, q.yearhighlist, q.yearlowlist, comment, pk)

        context = {
            'form': form,
            'title': 'Watchlist',
            'mylist': mylist,
        }
        return render(request, self.template_name, context)

    def post(self, request):
        form = WatchlistForm(request.POST)
        current_user = request.user

        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            stock_name = form.cleaned_data['stock_name']
            target_price = form.cleaned_data['target_price']
            comment = form.cleaned_data['comment']
            form = WatchlistForm()
            messages.success(request, f'The stock has been added to your watchlist!')

        symbol = current_user.watchlist_set.values_list('stock_name', flat=True)
        target_price = current_user.watchlist_set.values_list('target_price', flat=True)
        comment = current_user.watchlist_set.values_list('comment', flat=True)
        pk = current_user.watchlist_set.values_list('pk', flat=True)

        q = getQuotes(symbol)
        q.run()

        mylist = zip(symbol, q.stocknamelist, q.closepricelist, target_price, q.yearhighlist, q.yearlowlist, comment, pk)

        args = {
            'form': form,
            'title': 'Watchlist',
            'stock_name': symbol,
            'target_price': target_price,
            'comment': comment,
            'mylist': mylist
        }
        return render(request, self.template_name, args)

class DeleteView(SuccessMessageMixin, DeleteView):
    model = WatchList
    success_url = '/watchlist/'
    success_message = "deleted..."

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        stock_name = self.object.stock_name
        request.session['stock_name'] = stock_name
        message = request.session['stock_name'] + ' deleted successfully'
        messages.success(self.request, message)
        return super(DeleteView, self).delete(request, *args, **kwargs)

def find(request,s):
    res = []
    try:
        q= NSEStocks.objects.filter( Q(Symbol__istartswith=s ) )
        for i in q:
            s=s.upper()
            Symbol=i.Symbol.capitalize()
            if( Symbol.startswith(s) ):
                res.append(Symbol)
        print(res)

    except Exception as e:
        print("Error",e)

    return HttpResponse(json.dumps({"res":res}),content_type="application/json")


# Create a program that calculates what percentage you can cover of a 6-sided gift box (all sides are equal and square).
# First, you will receive the size of a side. Also, you will receive the sheets of paper you have.
# Last, you will receive how much area covers a single sheet of paper.
# First, you need to calculate the area of the gift box. Then you have to calculate how much area you can cover
# with the paper available. Keep in mind that every third sheet covers only 25% of the usual area.
# You have to calculate what percentage of the gift box you’ve covered. Percentage can exceed 100%!
# In the end, print the percentage of the area covered, formatted to the 2nd decimal place, in the following format:
# "You can cover {percentage}% of the box."

# Take input
box_side = float(input())
paper_sheets = int(input())
paper_area = float(input())

total_box_area = (box_side ** 2) * 6
third_sheets = paper_sheets // 3
total_covered_area = (paper_sheets - third_sheets) * paper_area + (third_sheets * 0.25 * paper_area)
covered_percentage = total_covered_area / total_box_area * 100

# Print result
print(f"You can cover {covered_percentage:.2f}% of the box.")

04. Mid Exam Tasks/01. Gift Box Coverage.py


'''
풀이

LIS가 무엇인가에 대해서는 다음을 참고하였다.
(https://namu.wiki/w/%EC%B5%9C%EC%9E%A5%20%EC%A6%9D%EA%B0%80%20%EB%B6%80%EB%B6%84%20%EC%88%98%EC%97%B4#rfn-1)
'''

# fast IO
from sys import stdin

# 수열 a의 크기와 수열 a를 입력받는다
sizeA = int(stdin.readline())
sequenceA = list(map(int, stdin.readline().split()))

# 마지막으로 큰 수를 저장하는 리스트 생성
maxList = []

# LIS의 증가 탐색
for a in sequenceA:
    i = 0
    while i < len(maxList) and a > maxList[i]:
        i += 1
    if i == len(maxList):
        maxList.append(a)
    else:
        maxList[i] = a

# 최장 증가 수열의 길이 출력
print(len(maxList))


from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
from tkinter import messagebox
import sqlite3

root=Tk()
root.geometry('800x790')
root.title("AMS")
root.iconbitmap('asd.ico')

def create():
    conn=sqlite3.connect('PKPDatabase.db')
    c=conn.cursor()
    c.execute("CREATE TABLE IF NOT EXISTS users(id integer primary key autoincrement,Firstname TEXT,Lastname TEXT,Fathername TEXT,Mothername TEXT,Dateofbirth TEXT,Villagename TEXT,Statename TEXT,Countryname TEXT,sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)")
    conn.commit()
    conn.close()
create()

#Title of Project
Title=Label(text="      ADHAR MANAGEMENT SYSTEM       ",bd=16,fg="#000000",font=('arial',35,'bold'),bg="OliveDrab1",relief='raise',width=32,height=1)
Title.pack()
SmallTitle=Label(text="Basic Details Form",bd=3,bg="Cyan",width=32,height=1,font=('arial',10,'bold'),relief=SUNKEN)
SmallTitle.place(x=270,y=100)

#Basic Informations

First_Name=Label(root, text="First Name:-", width=20, font=("bold"),fg="Cornflowerblue")
First_Name.place(x=50,y=200)
FNR=StringVar()
First_Name_Box=Entry(root,width=40,bg="honeydew2",textvariable=FNR)
First_Name_Box.place(x=300, y=200)

Last_Name=Label(root, text="Last Name:-  ", width=20, font=("bold"),fg="Cornflowerblue")
Last_Name.place(x=50,y=250)
LNR=StringVar()
Last_Name_Box=Entry(root,width=40,bg="honeydew2",textvariable=LNR)
Last_Name_Box.place(x=300, y=250)

Father_Name=Label(root, text="Father Name:-", width=20, font=("bold"),fg="Cornflowerblue")
Father_Name.place(x=50,y=300)
FFNR=StringVar()
Father_Name_Box=Entry(root,width=40,bg="honeydew2",textvariable=FFNR)
Father_Name_Box.place(x=300, y=300)

Mother_Name=Label(root, text="Mother Name:-", width=20, font=("bold"),fg="Cornflowerblue")
Mother_Name.place(x=50,y=350)
MMNR=StringVar()
Mother_Name_Box=Entry(root,width=40,bg="honeydew2",textvariable=MMNR)
Mother_Name_Box.place(x=300, y=350)

DOB=Label(root, text="Date Of Birth:-", width=20, font=("bold"),fg="Cornflowerblue")
DOB.place(x=50,y=400)
DOBR=StringVar()
DOB_Box=Entry(root,width=40,bg="honeydew2",textvariable=DOBR)
DOB_Box.place(x=300, y=400)

Religion=Label(root, text="Religion:-", width=20, font=("bold"),fg="Cornflowerblue")
Religion.place(x=50,y=450)
var=IntVar()
Radiobutton(root,text="Hindu",variable=var,value=1,bg="green yellow").place(x=300,y=450)
Radiobutton(root,text="Muslim",variable=var,value=2,bg="green yellow").place(x=370,y=450)
Radiobutton(root,text="Sikhs",variable=var,value=3,bg="green yellow").place(x=440,y=450)
Radiobutton(root,text="Christian",variable=var,value=4,bg="green yellow").place(x=500,y=450)

Gender=Label(root, text="Gender:-", width=20, font=("bold"),fg="Cornflowerblue")
Gender.place(x=50,y=500)
GenderList=['Male','Female','Other']
c=StringVar()
d=OptionMenu(root,c,*GenderList)
c.set("Select Gender")
d.place(x=300,y=500)

Language=Label(root, text="Language:-", width=20, font=("bold"),fg="Cornflowerblue")
Language.place(x=50,y=550)
v1=IntVar()
Checkbutton(root, text="Hindi", variable=v1,bg="pale green1").place(x=300,y=550)
v2=IntVar()
Checkbutton(root, text="English", variable=v2,bg="pale green1").place(x=370,y=550)
v3=IntVar()
Checkbutton(root, text="Sanskrit", variable=v3,bg="pale green1").place(x=440,y=550)
v4=IntVar()
Checkbutton(root, text="Urdu", variable=v4,bg="pale green1").place(x=520,y=550)

Village=Label(root, text="Village Name:-", width=20, font=("bold"),fg="Cornflowerblue")
Village.place(x=50,y=600)
VNBR=StringVar()
Village_Box=Entry(root,width=40,bg="wheat1",textvariable=VNBR)
Village_Box.place(x=300, y=600)

State=Label(root, text="State Name:-", width=20, font=("bold"),fg="Cornflowerblue")
State.place(x=50,y=650)
SNBR=StringVar()
State_Box=Entry(root,width=40,bg="wheat1",textvariable=SNBR)
State_Box.place(x=300, y=650)

Country=Label(root, text="Country Name:-", width=20, font=("bold"),fg="Cornflowerblue")
Country.place(x=50,y=700)
CNBR=StringVar()
Country_Box=Entry(root,width=40,bg="wheat1",textvariable=CNBR)
Country_Box.place(x=300, y=700)

#First Windows-------------------------------------------------------------------------------------------
def ImageWindows():
    top1=Toplevel()
    top1.geometry('500x500')
    top1.title("Image Windows")
    PassportSI = Label(top1, text="Passport Size Image:-", width=20, font=("bold"), fg="Cornflowerblue")
    PassportSI.place(x=5, y=5)
    def OpenImage():
        global my_image
        top1.filename = filedialog.askopenfilename(initialdir="D:\Tkinter\Python\TkinterPFiles", title="Select A Image",
        filetypes=(("PNG Image", "*.png"), ("All Image", "*.*")))

        my_image = ImageTk.PhotoImage(Image.open(top1.filename))
        my_image_label = Label(top1,image=my_image).place(x=100,y=70)
    my_btn = Button(top1,text="Select Image", command=OpenImage).place(x=250, y=7)

    btnC=Button(top1,text="Close Windows",bg="firebrick1",fg="Black",command=top1.destroy).place(x=200,y=470)
btn1=Button(root,text="Image Section",bg="dark orange",fg="Black",command=ImageWindows).place(x=10,y=750)

#Second Windows-------------------------------------------------------------------------------------------
def DevelopersWindows():
    top2=Toplevel()
    top2.title("Developers Windows")
    global my_img
    my_img = ImageTk.PhotoImage(Image.open("madeby.png"))
    my_label = Label(top2,image=my_img).pack()

    btnC=Button(top2,text="Close Windows",bg="firebrick1",fg="Black",command=top2.destroy).place(x=520,y=620)
btn2=Button(root,text="Developers Details",bg="dark orange",fg="Black",command=DevelopersWindows).place(x=690,y=750)

#Third Windows-------------------------------------------------------------------------------------------
def BMICheck():
    top3=Toplevel()
    top3.geometry("1350x650+0+0")
    top3.resizable(0, 0)
    top3.title("BMI")

    def BMI_Cal():
        BHeight = float(var2.get())
        BWeight = float(var1.get())
        BMI = str('%.2f' % (BWeight / (BHeight * BHeight)))
        lblBMIResult.config(text=BMI)

    var1 = DoubleVar()
    var2 = DoubleVar()

    Tops = Frame(top3, width=1350, height=50, bd=8, relief="raise")
    Tops.pack(side=TOP)
    f1 = Frame(top3, width=600, height=600, bd=8, relief="raise")
    f1.pack(side=LEFT)
    f2 = Frame(top3, width=300, height=700, bd=8, relief="raise")
    f2.pack(side=RIGHT)

    f1a = Frame(f1, width=600, height=200, bd=20, relief="raise")
    f1a.pack(side=TOP)
    f1b = Frame(f1, width=600, height=600, bd=20, relief="raise")
    f1b.pack(side=TOP)

    lblTitle = Label(Tops, text="          Body Mass Index        ", padx=16, pady=16, bd=16,
                     fg="#000000", font=('arial', 54, 'bold'),
                     bg="spring green", relief='raise', width=32, height=1)
    lblTitle.pack()

    lblWeight = Label(f1a, text="Select Weight in Kilograms ", font=('arial', 20, 'bold'), bd=20).grid(row=0, column=0)
    Bodyweight = Scale(f1a, variable=var1, from_=1, to=500, length=880, tickinterval=30, orient=HORIZONTAL)
    Bodyweight.grid(row=1, column=0)

    lblheight = Label(f1b, text="Enter Height in Meters Square", font=('arial', 20, 'bold'), bd=20).grid(row=0,
                                                                                column=0)
    txtheight = Entry(f1b, textvariable=var2, font=('arial', 16, 'bold'), bd=16, width=22, justify='center')
    txtheight.grid(row=1, column=0)

    lblBMIResult = Label(f1b, padx=16, pady=16, bd=16,
                         fg="#000000", font=('arial', 30, 'bold'),
                         bg="hot pink", relief='sunk', width=34, height=1)
    lblBMIResult.grid(row=2, column=0)

    lblBMITable = Label(f2, font=('arial', 20, 'bold'), text="BMI Table").grid(row=0, column=0)
    txtlblBMITable = Text(f2, height=12, width=38, bd=16, font=('arial', 12, 'bold'))
    txtlblBMITable.grid(row=1, column=0)

    txtlblBMITable.insert(END, 'Under weight \t\t' + "<19\n\n")
    txtlblBMITable.insert(END, 'Normal weight \t\t' + "19-24,9\n\n")
    txtlblBMITable.insert(END, 'Overweight \t\t' + "25-29,9\n\n")
    txtlblBMITable.insert(END, 'Obesity level I \t\t' + "30-34,9\n\n")
    txtlblBMITable.insert(END, 'Obesity level II\t\t' + "35-39,9\n\n")
    txtlblBMITable.insert(END, 'Obesity level III \t\t' + ">=40\n\n")

    btnBMI = Button(f2, text="Click to \nCheck Your \nBMI", padx=8, pady=8, bd=12, width=21,
                    font=('arial', 20, 'bold'), height=3, command=BMI_Cal)
    btnBMI.grid(row=2, column=0)

    btnC=Button(top3,text="Close Windows",bg="firebrick1",fg="Black",command=top3.destroy).place(x=520,y=620)
btn3=Button(root,text="Check BMI",bg="dark orange",fg="Black",command=BMICheck).place(x=100,y=750)

#Fourth Windows-------------------------------------------------------------------------------------------
def HelpWindows():
    top4=Toplevel()
    top4.geometry('500x500')
    top4.title("Help Desk Windows")

    SYQ= Label(top4, text="---Submit Your Query---", width=20,font=('arial',25,"bold"),bg="black",fg="White")
    SYQ.place(x=45,y=10)

    First_Name= Label(top4, text="First Name:-",font=('arial',15,'bold'),fg="lawn green")
    First_Name.place(x=10,y=100)
    First_Name_Box =Entry(top4,width=40,bg="aquamarine")
    First_Name_Box.place(x=200,y=100)

    Last_Name= Label(top4, text="Last Name:-", font=('arial', 15, 'bold'), fg="lawn green")
    Last_Name.place(x=10, y=130)
    Last_Name_Box = Entry(top4,width=40,bg="aquamarine")
    Last_Name_Box.place(x=200,y=130)

    Mobile_Number = Label(top4, text="Mobile Number:-", font=('arial', 15, 'bold'), fg="lawn green")
    Mobile_Number.place(x=10, y=160)
    Mobile_Number_Box = Entry(top4, width=40,bg="aquamarine")
    Mobile_Number_Box.place(x=200, y=160)

    Email_Id = Label(top4, text="Email Id:-", font=('arial', 15, 'bold'), fg="lawn green")
    Email_Id.place(x=10, y=190)
    Email_Id_Box = Entry(top4, width=40,bg="aquamarine")
    Email_Id_Box.place(x=200, y=190)

    AgeH = Label(top4, text="Age:-", font=('arial', 15, 'bold'), fg="lawn green")
    AgeH.place(x=10, y=220)
    v = IntVar()
    v.set(9)
    Age_Box=Spinbox(top4,from_=9,to=150, width=10, textvariable=v,bg="dark orange",bd=1)
    Age_Box.place(x=200, y=220)

    Query1 = Label(top4, text="Query:-", font=('arial', 15, 'bold'), fg="lawn green")
    Query1.place(x=10, y=250)
    Query_Box= Text(top4, height=9, width=30,bd=3,bg="misty rose")
    Query_Box.place(x=200, y=250)

    def SubmitPopPup():
        response = messagebox.askokcancel("Final Submissions!", "Confirm")
        Label(top4,text=response).pack()
    SubmitButton=Button(top4, text="Submit", font=('arial', 17, 'bold'), fg="maroon3",bg="snow3",command=SubmitPopPup)
    SubmitButton.place(x=200, y=420)

    btnC=Button(top4,text="Close Windows",bg="firebrick1",fg="Black",command=top4.destroy).place(x=400,y=470)
btn4=Button(root,text="Help Desk",bg="dark orange",fg="Black",command=HelpWindows).place(x=623,y=750)

#Fifth Windows-------------------------------------------------------------------------------------------
def AboutAC():
    top5=Toplevel()
    top5.geometry('350x500')
    top5.title("Aadhaar Card")

    ADCT= Label(top5, text="About Aadhaar Card", width=20, font=('arial', 18, "bold"), bg="Salmon", fg="White")
    ADCT.place(x=20, y=10)

    global my_imga
    my_imga = ImageTk.PhotoImage(Image.open("Aadhaarcard.png"))
    my_label = Label(top5,image=my_imga).place(x=20,y=50)

    ACDIWF=Text(top5,height=10,width=40, bg="light yellow")
    ACDIWF.insert(INSERT,"Aadhaar is a 12 digit individual identification number issued by the Unique Identification Authority of of India on behalf of the Government of India.The number serves as a proof of identity and address, anywhere in India.")
    ACDIWF.place(x=10,y=270)

    btnC=Button(top5,text="Close Windows",bg="firebrick1",fg="Black",command=top5.destroy).place(x=130,y=470)
btn5=Button(root,text="About Aadhaar Card",bg="dark orange",fg="Black",command=AboutAC).place(x=500,y=750)

#Sixth Windows-------------------------------------------------------------------------------------------
def PaymentSystem():
    top6=Toplevel()
    top6.geometry('500x400')
    top6.title("Payment System")

    PaymentH= Label(top6, text="Payment System", width=20, font=('arial', 23, "bold"), bg="green yellow", fg="White")
    PaymentH.place(x=55,y=10)

    Choose_Card = Label(top6, text="Choose Card:-", font=('arial', 15, 'bold'), fg="Blue")
    Choose_Card.place(x=10, y=100)
    var1=IntVar()
    Radiobutton(top6, text="Debit Card", variable=var1, value=1, bg="DarkGoldenrod1").place(x=180, y=100)
    Radiobutton(top6, text="Credit Card", variable=var1, value=2, bg="DarkGoldenrod1").place(x=270, y=100)
    Radiobutton(top6, text="Master Card", variable=var1, value=3, bg="DarkGoldenrod1").place(x=365, y=100)

    Card_Number = Label(top6, text="Card Number:-", font=('arial', 15, 'bold'), fg="Blue")
    Card_Number.place(x=10, y=135)
    RBFCN=StringVar()
    Card_Number_Box = Entry(top6, width=40, bg="Azure",textvariable=RBFCN)
    Card_Number_Box.place(x=200, y=140)

    Account_Number = Label(top6, text="Account Number:-", font=('arial', 15, 'bold'), fg="Blue")
    Account_Number.place(x=10, y=170)
    RBFAN=StringVar()
    Account_Number_Box = Entry(top6, width=40, bg="Azure",textvariable=RBFAN)
    Account_Number_Box.place(x=200, y=175)

    Account_Holder = Label(top6, text="Account Holder:-", font=('arial', 15, 'bold'), fg="Blue")
    Account_Holder.place(x=10, y=205)
    RBFAHN=StringVar()
    Account_Holder_Box = Entry(top6, width=40, bg="Azure",textvariable=RBFAHN)
    Account_Holder_Box.place(x=200, y=210)

    ExpireD= Label(top6, text="Expiration Date:-", font=('arial', 15, 'bold'), fg="Blue")
    ExpireD.place(x=10, y=240)
    RBFEN=StringVar()
    ExpireD_Box = Entry(top6, width=40, bg="Azure",textvariable=RBFEN)
    ExpireD_Box.place(x=200, y=245)

    CVC = Label(top6, text="CVC Code:-", font=('arial', 15, 'bold'), fg="Blue")
    CVC.place(x=10, y=275)
    RBFCVC=StringVar()
    CVC_Box = Entry(top6, width=40, bg="Azure",textvariable=RBFCVC)
    CVC_Box.place(x=200, y=280)
    def resetBF():
        RBFCN.set("")
        RBFAN.set("")
        RBFAHN.set("")
        RBFEN.set("")
        RBFCVC.set("")
        return

    SubmitPB = Button(top6, text="Submit", font=('arial', 15, 'bold'), fg="Red",bg="Bisque",command=resetBF)
    SubmitPB.place(x=200, y=330)

    btnC=Button(top6,text="Close Windows",bg="firebrick1",fg="Black",command=top6.destroy).place(x=400,y=370)
btn6=Button(root,text="Payment Method",bg="dark orange",fg="Black",command=PaymentSystem).place(x=172,y=750)

def savedata():
    conn=sqlite3.connect('PKPDatabase.db')
    c=conn.cursor()
    c.execute('INSERT INTO users(Firstname,Lastname,Fathername,Mothername,Dateofbirth,Villagename,Statename,Countryname) VALUES (?,?,?,?,?,?,?,?)',(FNR.get(),LNR.get(),FFNR.get(),MMNR.get(),DOBR.get(),VNBR.get(),SNBR.get(),CNBR.get()))
    conn.commit()
    print("Data Save Successfully")

SubmitButtonF1=Button(root,text="Submit",bg="yellow",fg="Black",bd=3,relief=RAISED,font=('arial',15,'bold'),command=savedata)
SubmitButtonF1.place(x=345,y=730)

root.mainloop()


# *coding:utf-8*

"""
Define Problem class. Unite several Model classes through Connections, forming one single Equation block. Used by Simulation class to perform the calculations.
"""

from .core.error_definitions import ExposedVariableError, AbsentRequiredObjectError
from .core.equation_block import EquationBlock
from .core.expression_evaluation import EquationNode
from collections import OrderedDict
from .core.variable import Variable
from .core.parameter import Parameter
from .model import Model
from .analysis import Analysis
#import numpy as np
#from .graph_creator import ConnectionGraph

import threading

_uid = threading.local()

def gen_rnd_str():

    if getattr(_uid, "uid", None) is None:
        _uid.tid = threading.current_thread().ident
        _uid.uid = 0
    _uid.uid += 1
    return str((_uid.tid, _uid.uid)[1])

class Problem:

    """
    Problem class definitions. Unite several Model objects into one single equation block for solving.
    """

    def __init__(self, name, description="", models={}, connections={}, variable_dict={}, parameter_dict={}):

        """
        Instantiate Problem.

        :ivar str name:
            Name for the current problem

        :ivar str description:
            Description of the current problem
        """

        self.name = name

        self.description = description

        self.models = OrderedDict(models)

        self.connections = OrderedDict(connections)

        self._equation_list = None

        self.equation_block = None

        self.initial_conditions = {}

        self.variable_dict = OrderedDict(variable_dict)

        self.parameter_dict = OrderedDict(parameter_dict)

        self.time_variable_name = None

        self.__extra_dof_differential__ = 0

        self.__time_variable_names__ = []

        #self.connection_graph = ConnectionGraph()

    def _infoProblemReport_(self):

        print(Analysis().problemReport(self))

    def setTimeVariableName(self, name):

        if isinstance(name, list) is False:

            name = [name]

        self.time_variable_name = name

    def setInitialConditions(self, condition):

        """
        Set initial condition for ODE and DAE systems.

        :param dict condition:
            Dictionary containing the initial condition for each Variable object that is differentiated
        """

        self.initial_conditions.update(condition)

    def _getProblemType(self):

        is_linear = len(self.equation_block._equation_groups['linear']) > 0

        is_nonlinear = len(self.equation_block._equation_groups['nonlinear']) > 0

        is_differential = len(self.equation_block._equation_groups['differential']) > 0

        # Check if the problem is D (strictly Differential), DAE (differential + linear or nonlinear), NLA (nonlinear) or LA (linear)

        is_D = is_differential==True and (is_linear==False and is_nonlinear==False)
        is_DAE = is_differential==True and (is_linear==True or is_nonlinear==True)
        is_NLA = is_differential==False and (is_nonlinear==True)
        is_LA = is_differential==False and (is_nonlinear==False and is_linear==True)

        if is_D:

            return "differential"

        elif is_DAE:

            return "differential-algebraic"

        elif is_NLA:

            return "nonlinear"

        elif is_LA:

            return "linear"

        else:

            return None

    def _buildEquationBlock(self):

        """
        Return the EquationBlock object for the models defined for the current problem.
        """

        #eqs_ = [ list(model_i.equations.values()) for model_i in self.models.values() ]

        #self._equation_list = (np.array(eqs_).ravel()).tolist()

        #================== OPTIMIZE THIS CODE SNIPPET ===================

        self._equation_list = []

        _var_dict = {}

        _var_list = []

        _var_name_list = []

        _param_dict = {}

        _param_list = []

        _param_name_list = []

        for model_i in list(self.models.values()):

            for eq_i in list(model_i.equations.values()):

                self._equation_list.append(eq_i)

                for obj_i in list(eq_i.objects_declared.values()):

                    if obj_i not in _var_list and isinstance(obj_i, Variable):

                        _var_dict[obj_i.name] = obj_i

                        _var_list.append(obj_i)

                        _var_name_list.append(obj_i.name)

                    elif obj_i not in _param_list and isinstance(obj_i, Parameter):

                        _param_dict[obj_i.name] = obj_i

                        _param_list.append(obj_i)

                        _param_name_list.append(obj_i.name)

        #=================================================================
        #Remove unused variables from self.variable_dict and self.param_dict

        variable_dict_ = OrderedDict({})

        _ = [variable_dict_.update({k:self.variable_dict[k]}) for k in self.variable_dict.keys() if k in _var_name_list]

        parameter_dict_ = OrderedDict({})

        _ = [parameter_dict_.update({k:self.parameter_dict[k]}) for k in self.parameter_dict.keys() if k in _param_name_list]

        self.equation_block = EquationBlock(equations=self._equation_list, variable_dict=variable_dict_, parameter_dict=parameter_dict_)

    def createConnection(self, model_1, model_2, output_vars, input_vars, expr=None, description=""):

        """
        Connect two Model objects creating a Connection for both models, linking the ouput variable of the former to the input variable of the later.

        If only variables were provided, perform the regular check for input and output variables, and assemble one equation (connectin mode). If ENODES were provided directly, pass the euation directly (input mode)
        """

        connection_mode, input_mode = False, False

        if isinstance(output_vars, EquationNode) and isinstance(input_vars, EquationNode):

            input_mode = True

        else:

            connection_mode = True

        if connection_mode is True:

            if isinstance(input_vars, list):

                input_var_is_declared= all(in_i in model_2.exposed_vars['input'] for in_i in input_vars)

            else:

                input_var_is_declared= input_vars in model_2.exposed_vars['input']

            if isinstance(output_vars, list):

                output_var_is_declared= all(out_i in model_1.exposed_vars['output'] for out_i in output_vars)

            else:

                output_var_is_declared= output_vars in model_1.exposed_vars['output']

            if output_var_is_declared and input_var_is_declared:

               # Creating connection equation in the second Model object

               #return self._createDirectConnection(model_1, output_var, model_2, input_var)

                if not isinstance(output_vars, list):

                    output_var_ = [output_vars]

                else:

                    output_var_ = output_vars

                if not isinstance(input_vars, list):

                    input_var_ = [input_vars]

                else:

                    input_var_ = input_vars

                if expr is None:

                    expr = sum([in_var_i.__call__() for in_var_i in input_var_]) - sum([out_var_i.__call__() for out_var_i in output_var_])

                # The process of connection creation

                self._createDirectConnection(model_1, output_var_, model_2, input_var_, expr, description)

                #Create connection beetween Model objects

                #self.createGraphModelConnection(model_1, model_2)

            else:

                raise ExposedVariableError(model_1.exposed_vars['output'], model_2.exposed_vars['input'], output_vars, input_vars)

        if input_mode is True:

            if isinstance(model_1, str) is True:

                if model_1 is "":
                    model_1 = gen_rnd_str()

                model_2.createEquation("conn_"+model_1+"-->"+model_2.name, "Connection from "+model_1+" to "+model_2.name, input_vars - output_vars, check_equation=False)

            elif isinstance(model_1, Model) is True:

                model_2.createEquation("conn_"+model_1.name+"-->"+model_2.name, "Connection from "+model_1.name+" to "+model_2.name, input_vars - output_vars, check_equation=False)

            else:

                raise AbsentRequiredObjectError("[Model, str]")

    def _createDirectConnection(self, out_model, out_vars, in_model, in_vars, expr, description):

        """
        Create a connection beetween one model an their output variable, and another model and other variable, which is an input for the later model
        """

        out_var_names = (",").join([out_i.name for out_i in out_vars])

        in_var_names = (",").join([in_i.name for in_i in in_vars])

        conn = in_model._createConnection(out_var_names+"--->"+in_var_names, description, out_vars, in_vars, out_model, expr)

        #in_model._createConnection(out_var.name+"--->"+in_var.name, description, out_var, in_var, out_model, expr)

        self.connections[out_var_names+"@"+out_model.name+" ---> "+in_var_names+"@"+in_model.name] = conn

        #return conn

    def _reloadModels(self, models_name=None):

        """
        Reload defined models, redefining their equations
        """

        if models_name is None:

            _ = [mod_i() for mod_i in self.models.values()]

        else:

            _ = [mod_i() for mod_i in self.models.values() if mod_i.name in models_name]

    '''
    def createGraphModelConnection(self, model_input, model_output):

        """
        Create a connection beetween two Model objects
        """

        self.connection_graph.add_edge(model_input.name, model_output.name)
    '''

    '''
    def drawConnectionGraph(self, file_name='output.png', show_model_headings=True):

        """
        Draw connection graph beetween models of the current problem, indicating the name of variables used to connect them
        """

        # Iterate through models and add heading as label if needed

        for model_i in list(self.models.values()):

            if show_model_headings is True:

                self.connection_graph.add_node(id_name = model_i.name, label = model_i._getModelOverviewForGraph())

            else:

                self.connection_graph.add_node(id_name = model_i.name)

        self.connection_graph.draw(file_name, show_model_headings)
    '''

    def addModels(self, model_list):

        """
        Add models to current problem

        :param [Model, list(Model)] mod_list:
            Model to be added to the current Problem.
        """

        if isinstance(model_list,list):

            # A list of models were supplied

            #self.models = OrderedDict( (modx.name,modx) for modx in model_list )

            _ = [self.addModels(modx) for modx in model_list]

        else:

            # A single model was supplied

            self.models[model_list.name] = model_list

            self.variable_dict.update(model_list.variables)

            self.parameter_dict.update(model_list.parameters)

    def resolve(self):

        """
        Resolve current Problem object, builing its EquationBlock object and resolving it
        """

        self._reloadModels()

        self._buildEquationBlock()

        self.equation_block()

        #_has_time_var_declared_ = [ any(eq_obj_i in eq_i.objects_declared for eq_obj_i in self.time_variable_name) for eq_i in self.equation_block._equation_groups['differential']]

        #if (self._getProblemType() is 'differential-algebraic') and  any( j is True for j in _has_time_var_declared_):

            #self.equation_block._var_list.extend(self.time_variable_name)

            #print("===> equation_block_var_list = ",self.equation_block._var_list)


from django import forms
from .models import *

class PostForm(forms.ModelForm):
    body = forms.CharField(required=False,
    widget=forms.widgets.Textarea(
            attrs={
                "placeholder": "What do you think ?...",
                "class": "textarea is-info is-medium",
                "id": "ptext",
                "onmouseover": "check()"
            }
        ),
        label="",
    )

    img = forms.ImageField(required=False,label = "", widget=forms.widgets.FileInput(attrs={"id" : "up"}))

    class Meta:
        model = Post
        exclude = ("user","approved" )


def anagrama(str1, str2):

    if len(str1) != len(str2):
        return False

    arrCadena = [0]*26

    for i in range(len(str1)):
        # print(str1[i], ord(str1[i]) - 97)
        arrCadena[ord(str1[i]) - 97] += 1
        arrCadena[ord(str2[i]) - 97] -= 1

    for i in range(len(arrCadena)):
        if arrCadena[i] != 0:
            return False

    return True

print(anagrama("hola", "aloh"))


import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import pyjokes
import pywhatkit
import os
import smtplib

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")

    elif hour>=12 and hour<18:
        speak("Good Afternoon!")

    else:
        speak("Good Evening!")

    speak("I am Alisha. how may i help you this time")

def takeCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        print("Say that again please...")
        return "None"
    return query

def sendmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password')
    server.sendmail('youremail@gmail.com', to, content)
    server.close()

if __name__ == "__main__":
    wishMe()
    while True:
        # if 1:
        query = takeCommand().lower()

        # Logic for executing tasks based on query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)
            speak("Hope that helps, i can tell you more if you ask me briefly")

        elif 'who is' in query:
            person = query.replace('who is', '')
            info = wikipedia.summary(person, 1)
            print(info)
            speak(info)
            speak("If you still want to know more, then try to be more precise.")

        elif 'hello' in query:
            speak('Hi there, Whats up')

        elif 'who are you' in query:
            speak('I am your friend, Alisha')

        elif 'our university ' in query:
            speak("It is situated near second stage")

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'college website' in query:
            speak("Opening in new tab")
            webbrowser.open("msruas.ac.in")

        elif 'students portal' in query:
            speak("why not! Here you go")
            webbrowser.open("ruasportal.msruas.ac.in")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open stack overflow' in query:
            webbrowser.open("stackoverflow.com")

        elif 'play' in query:
            song = query.replace('play', '')
            speak('playing you ' + song)
            pywhatkit.playonyt(song)

        elif 'joke' in query:
            speak(pyjokes.get_joke())
            speak("If you want to listen to more then say yes or else tell me when you are done")

        elif 'yes' in query:
            speak(pyjokes.get_joke())
            speak("do you still want to listen to more jokes")

        elif 'i am done' in query:
            speak("Hope i gave a smile on your face. keep smiling. As it is very good for your health")

        elif 'play music' in query:
            music_dir = 'D:\\Favourite\\songs\\good_vives'
            songs = os.listdir(music_dir)
            print(songs)
            os.startfile(os.path.join(music_dir, songs[0]))

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"Sir, the time is {strTime}")

        elif 'thank you' in query:
            speak("Its my pleasure to serve you, just speak out my name anytime you need me")

        elif 'email to Amar' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "djlovesallbut5467yo@gmail.com"
                sendmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my friend. I am not able to send this email")


"""
CP1404 - Daniel Keppie
Silver Service Taxi test
"""

from prac_08.silver_service_taxi import SilverServiceTaxi

def main():
    hummer = SilverServiceTaxi("Hummer", 200, 2)
    hummer.drive(18)
    print(hummer.__str__()+", with a total fare of ${}0".format(hummer.get_fare()))

main()


'''
38. Дані про направлення вітру (північний, південний, східний, західний) і
силі вітру за декаду листопада зберігаються в масиві. Визначити, скільки днів дув південний вітер з силою, що перевищує 8 м/с.
'''

import random #для заполнения массива

arr = [[0] * 10 for i in range(2)] #инициализация массива

directions = 'news' #направления ветра

for i in range(10): #для 10 дней
    arr[0][i] = random.choice(directions) #выбираем направление
    arr[1][i] = random.randrange(1, 16) #и скорость в диапазоне [1, 15]

print(arr)

count = 0 #количество дней

for i in range(10): #для всех дней
    if arr[0][i] == 's' and arr[1][i] > 8: #если ветер южный и скорость > 8
        count += 1 #увеличиваем количество на 1

print('\nsouth wind with speed > 8 m/s was', count, 'times')


from app import app
import dash_html_components as html
import dash_bootstrap_components as dbc
import router
from view import header_bar_view

layout = html.Div([
    header_bar_view.layout,
    router.layout,
])

app.layout = html.Div(layout)

if __name__ == '__main__':
    PORT = 5000
    app.run_server(
        port=PORT,
        host='0.0.0.0',
        debug=True,
    )


from rest_framework import serializers
from django.contrib.auth.models import User
from .models import (City, Country, Trip, Start_trip, Stop_trip, Driver_location,
                     Status_trip)

from datetime import date

import locale

locale.setlocale(locale.LC_TIME, 'es')

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('first_name', 'last_name')

class CitySerializer(serializers.ModelSerializer):

    class Meta:
        model = City
        fields = ('name',)

class CountrySerializer(serializers.ModelSerializer):

    class Meta:
        model = Country
        fields = ('name',)

class Start_tripSerializer(serializers.ModelSerializer):
    city = CitySerializer(many=False)

    class Meta:
        model = Start_trip
        fields = ('date', 'pickup_address', 'city', 'pickup_location_type',
                  'pickup_location_lat', 'pickup_location_long')

class Stop_tripSerializer(serializers.ModelSerializer):
    city = CitySerializer(many=False)

    class Meta:
        model = Stop_trip
        fields = ('date', 'pickup_address', 'city', 'pickup_location_type',
                  'pickup_location_lat', 'pickup_location_long')

class StatusSerializer(serializers.ModelSerializer):

    class Meta:
        model = Status_trip
        fields = ('name',)

class Driver_locationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Driver_location
        fields = ('type', 'lat', 'long')

class TripSerializer(serializers.ModelSerializer):
    start = Start_tripSerializer(source='start_trip', many=True)
    end = Stop_tripSerializer(source='stop_trip', many=True)
    driver_location = Driver_locationSerializer(source='driver_locationtrip', many=True)
    city = CitySerializer(many=False)
    country = CountrySerializer(many=False)
    status = StatusSerializer(many=False)
    passenger = UserSerializer(many=False,)
    driver = UserSerializer(many=False,)

    class Meta:
        model = Trip
        fields = ('start', 'end', 'city', 'country', 'passenger', 'driver',
                  'car', 'status', 'check_code', 'createdAt', 'updatedAt',
                  'price', 'driver_location', 'id')

class TripSerializerPut(serializers.ModelSerializer):

    class Meta:
        model = Trip
        fields = ('driver', 'car', 'updatedAt', 'status')


drinks_inventory = {
    "Henricks" : {"quantity": 3, "type": "Gin", "cost": 3.5, "strength" : 1},
    "Bombay Sapphire": {"quantity": 9,"type": "Gin", "cost": 3.50, "strength" : 1},
    "Chardonnay": {"quantity": 5,"type": "Wine", "cost": 5 ,"strength" : 2},
    "Pinot Noir": {"quantity": 8,"type": "Wine", "cost": 5, "strength" : 2},
    "Neck Oil": {"quantity": 4,"type": "Beer", "cost": 4.5, "strength" : 1},
    "Stella Artois": {"quantity": 0,"type": "Beer", "cost": 4.5, "strength" : 1},
    "Lemonade": {"quantity": 5,"type": "Soft", "cost": 2.5, "strength" : 0}
        }

food_inventory = {
    "Nachos" : {"quantity": 3, "cost": 3.5, "strength" : 1},
    "Fries": {"quantity": 9, "cost": 3.50, "strength" : 1},
    "Burger": {"quantity": 5, "cost": 5 ,"strength" : 2},
        }