## from https://peterroelants.github.io/posts/gaussian-process-kernel-fitting/

# Imports
import os
import sys
import warnings
warnings.simplefilter("ignore")

import numpy as np
import pandas as pd
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import tensorflow_probability as tfp

tf.logging.set_verbosity(tf.logging.ERROR)

import bokeh
import bokeh.io
import bokeh.plotting
import bokeh.models
from IPython.display import display, HTML

bokeh.io.output_notebook(hide_banner=True)

tfd = tfp.distributions
tfk = tfp.math.psd_kernels

np.random.seed(42)
tf.set_random_seed(42)
# tf.random.set_seed(42)  # tf2

# Load the data and clean it up
# we've already downloaded this data (see gaussian_processes_co2.R)
co2_df = pd.read_csv('~/bayesian_machine_learning_r/data/monthly_in_situ_co2_mlo.csv', \
    na_values='-99.99', \
    dtype=np.float64)
# drop missing values
co2_df.dropna(inplace=True)
# Remove whitespace from column names
co2_df.rename(columns=lambda x: x.strip(), inplace=True)

## rename the date and co2 column to fit with the rest of the code
co2_df.rename(columns={"date_num": "Date", "co2": "CO2"}, inplace = True)

## plot ------------------------------------------------------------------------
fig = bokeh.plotting.figure(
    width=600, height=300,
    x_range=(1958, 2020), y_range=(310, 420))
fig.xaxis.axis_label = 'Date'
fig.yaxis.axis_label = 'CO₂ (ppm)'
fig.add_layout(bokeh.models.Title(
    text='In situ air measurements at Mauna Loa, Observatory, Hawaii',
    text_font_style="italic"), 'above')
fig.add_layout(bokeh.models.Title(
    text='Atmospheric CO₂ concentrations',
    text_font_size="14pt"), 'above')
fig.line(
    co2_df.Date, co2_df.CO2, legend_label='All data',
    line_width=2, line_color='midnightblue')
fig.legend.location = 'top_left'
fig.toolbar.autohide = True
bokeh.plotting.show(fig)

# Split the data into observed and to predict
date_split_predict = 2008
df_observed = co2_df[co2_df.Date < date_split_predict]
print('{} measurements in the observed set'.format(len(df_observed)))
df_predict = co2_df[co2_df.Date >= date_split_predict]
print('{} measurements in the test set'.format(len(df_predict)))

# Define mean function which is the means of observations
observations_mean = tf.constant(
    [np.mean(df_observed.CO2.values)], dtype=tf.float64)
mean_fn = lambda _: observations_mean

## KERNEL ----------------------------------------------------------------------
# Define the kernel with trainable parameters.
# Note we transform some of the trainable variables to ensure
#  they stay positive.

# Use float64 because this means that the kernel matrix will have
#  less numerical issues when computing the Cholesky decomposition

## Long term smooth rising trend (Rasmussen eq 5.15)
# Smooth kernel hyperparameters
smooth_amplitude = tf.exp(
    tf.Variable(np.float64(3)), name='smooth_amplitude')
smooth_length_scale = tf.exp(
    tf.Variable(np.float64(3)), name='smooth_length_scale')
# Smooth kernel
smooth_kernel = tfk.ExponentiatedQuadratic(
    amplitude=smooth_amplitude,
    length_scale=smooth_length_scale)

## Allows for decay away from exact periodicity (Rasmussen eq. 5.16)
# Local periodic kernel hyperparameters
periodic_amplitude = tf.exp(
    tf.Variable(np.float64(0)), name='periodic_amplitude')
periodic_length_scale = tf.exp(
    tf.Variable(np.float64(1)), name='periodic_length_scale')
periodic_period = tf.exp(
    tf.Variable(np.float64(0)), name='periodic_period')
periodic_local_length_scale = tf.exp(
    tf.Variable(np.float64(2)), name='periodic_local_length_scale')
# Local periodic kernel
local_periodic_kernel = (
    tfk.ExpSinSquared(
        amplitude=periodic_amplitude,
        length_scale=periodic_length_scale,
        period=periodic_period) *
    tfk.ExponentiatedQuadratic(
        length_scale=periodic_local_length_scale))

# Short-medium term irregularities kernel hyperparameters
# (Rasmussen eq. 5.17)
irregular_amplitude = tf.exp(
    tf.Variable(np.float64(0)), name='irregular_amplitude')
irregular_length_scale = tf.exp(
    tf.Variable(np.float64(0)), name='irregular_length_scale')
irregular_scale_mixture = tf.exp(
    tf.Variable(np.float64(0)), name='irregular_scale_mixture')
# Short-medium term irregularities kernel
irregular_kernel = tfk.RationalQuadratic(
    amplitude=irregular_amplitude,
    length_scale=irregular_length_scale,
    scale_mixture_rate=irregular_scale_mixture)

## does not include a noise model (eq. 5.18) --> try adding this later

# Noise variance of observations
# Start out with a medium-to high noise
observation_noise_variance = tf.exp(
    tf.Variable(np.float64(1)), name='observation_noise_variance')

# Sum all kernels to single kernel containing all characteristics
kernel = (smooth_kernel + local_periodic_kernel + irregular_kernel)

## Setup the optimisation ------------------------------------------------------
# Define mini-batch data iterator
batch_size = 128

## tf1 version
batch_date, batch_co2 = (
    tf.data.Dataset.from_tensor_slices(
        (df_observed.Date.values.reshape(-1, 1), df_observed.CO2.values))
    .shuffle(buffer_size=len(df_observed))
    .repeat(count=None)
    .batch(batch_size)
    .make_one_shot_iterator()
    .get_next()
)

# Gaussian process with batch data to fit the kernel parameters
gp_batched = tfd.GaussianProcess(
    mean_fn=mean_fn,
    kernel=kernel,
    index_points=batch_date,
    observation_noise_variance=observation_noise_variance)

## tf2 version
# batch_co2_dataset = tf.data.Dataset.from_tensor_slices( \
#     (df_observed.Date.values.reshape(-1, 1), df_observed.CO2.values)) \
#         .shuffle(buffer_size=len(df_observed)) \
#             .repeat(count=None).batch(batch_size)

# iterator = iter(batch_co2_dataset)
# batch_date, batch_co2 = iterator.get_next()

# Gaussian process with batch data to fit the kernel parameters
# gp_batched = tfd.GaussianProcess(
#     mean_fn=mean_fn,
#     kernel=kernel,
#     index_points=batch_date,
#     observation_noise_variance=observation_noise_variance)

# NLL to minimize
neg_log_likelihood_batch = -gp_batched.log_prob(batch_co2)

# Adam optimizer to minimize NLL --> tf v1
optimize = tf.train.AdamOptimizer(
    learning_rate=0.002).minimize(neg_log_likelihood_batch)

# tf2
# optimize = tf.keras.optimizers.Adam(learning_rate=0.002)
# optimize.minimize(neg_log_likelihood_batch, var_list=variables)

# Gaussian process on all training data to monitor NLL
#  on full observed dataset.
gp_all_observed = tfd.GaussianProcess(
    mean_fn=mean_fn,
    kernel=kernel,
    index_points=df_observed.Date.values.reshape(-1, 1),
    observation_noise_variance=observation_noise_variance)

log_likelihood_all = -gp_all_observed.log_prob(
    df_observed.CO2.values)

# Fit hyperparameters

# Start session
session = tf.InteractiveSession()
session.run(tf.global_variables_initializer())

# Training loop
batch_nlls = []  # Batch NLL for plotting
full_ll = []  # Full data NLL for plotting
nb_iterations = 10001
for i in range(nb_iterations):
    # Run optimization for single batch
    _, nlls = session.run([optimize, neg_log_likelihood_batch])
    batch_nlls.append((i, nlls))
    # Evaluate on all observations
    if i % 100 == 0:
        # Evaluate on all observed data
        ll = session.run(log_likelihood_all)
        full_ll.append((i, ll))

# Plot NLL over iterations
fig = bokeh.plotting.figure(
    width=600, height=400,
    x_range=(0, nb_iterations), y_range=(50, 200))
fig.add_layout(bokeh.models.Title(
    text='Negative Log-Likelihood (NLL) during training',
    text_font_size="14pt"), 'above')
fig.xaxis.axis_label = 'iteration'
fig.yaxis.axis_label = 'NLL batch'
# First plot
fig.line(
    *zip(*batch_nlls), legend_label='Batch data',
    line_width=2, line_color='midnightblue')
# Seoncd plot
# Setting the second y axis range name and range
fig.extra_y_ranges = {
    'fig1ax2': bokeh.models.Range1d(start=130, end=250)}
fig.line(
    *zip(*full_ll), legend_label='All observed data',
    line_width=2, line_color='red', y_range_name='fig1ax2')
# Adding the second axis to the plot.
fig.add_layout(bokeh.models.LinearAxis(
    y_range_name='fig1ax2', axis_label='NLL all'), 'right')

fig.legend.location = 'top_right'
fig.toolbar.autohide = True
bokeh.plotting.show(fig)

# Show values of parameters found
variables = [
    smooth_amplitude,
    smooth_length_scale,
    periodic_amplitude,
    periodic_length_scale,
    periodic_period,
    periodic_local_length_scale,
    irregular_amplitude,
    irregular_length_scale,
    irregular_scale_mixture,
    observation_noise_variance
]
variables_eval = session.run(variables)

data = list([
    (var.name[:-2], var_eval)
    for var, var_eval in zip(variables, variables_eval)])
df_variables = pd.DataFrame(
    data, columns=['Hyperparameters', 'Value'])
display(HTML(df_variables.to_html(
    index=False, float_format=lambda x: f'{x:.4f}')))

# Posterior GP using fitted kernel and observed data
gp_posterior_predict = tfd.GaussianProcessRegressionModel(
    mean_fn=mean_fn,
    kernel=kernel,
    index_points=df_predict.Date.values.reshape(-1, 1),
    observation_index_points=df_observed.Date.values.reshape(-1, 1),
    observations=df_observed.CO2.values,
    observation_noise_variance=observation_noise_variance)

# Posterior mean and standard deviation
posterior_mean_predict = gp_posterior_predict.mean()
posterior_std_predict = gp_posterior_predict.stddev()

# Plot posterior predictions

# Get posterior predictions
μ = session.run(posterior_mean_predict)
σ = session.run(posterior_std_predict)

# Plot
fig = bokeh.plotting.figure(
    width=600, height=400,
    x_range=(2008, 2019), y_range=(380, 415))
fig.xaxis.axis_label = 'Date'
fig.yaxis.axis_label = 'CO₂ (ppm)'
fig.add_layout(bokeh.models.Title(
    text='Posterior predictions conditioned on observations before 2008.',
    text_font_style="italic"), 'above')
fig.add_layout(bokeh.models.Title(
    text='Atmospheric CO₂ concentrations',
    text_font_size="14pt"), 'above')
fig.circle(
    co2_df.Date, co2_df.CO2, legend_label='True data',
    size=2, line_color='midnightblue')
fig.line(
    df_predict.Date.values, μ, legend_label='μ (predictions)',
    line_width=2, line_color='firebrick')
# Prediction interval
band_x = np.append(
    df_predict.Date.values, df_predict.Date.values[::-1])
band_y = np.append(
    (μ + 2*σ), (μ - 2*σ)[::-1])
fig.patch(
    band_x, band_y, color='firebrick', alpha=0.4,
    line_color='firebrick', legend_label='2σ')

fig.legend.location = 'top_left'
fig.toolbar.autohide = True
bokeh.plotting.show(fig)
#


class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        '''
        dp => dp[pos] = current min
        dijatra
        '''
        height = len(heights)
        width = len(heights[0])
        heap = []
        dp = collections.defaultdict(lambda: float('inf'))

        # init
        heap.append((0, 0, 0))
        dp[0, 0] = 0

        # loop
        while heap:
            current_diff, x, y = heapq.heappop(heap)

            if x == height-1 and y == width-1:
                return current_diff

            for i, j in [x-1, y], [x+1, y], [x, y+1], [x, y-1]:
                if i < 0 or j < 0 or i >= height or j >= width:
                    continue

                diff = max(current_diff, abs(heights[i][j] - heights[x][y]))

                if diff < dp[i, j]:
                    heapq.heappush(heap, (diff, i, j))
                    dp[i, j] = diff


# Import the rebound module
import rebound
import os

filename = "simulationarchive.bin"
try:
    sim = rebound.Simulation.from_archive(filename)
    sim.simulationarchive_filename = filename
    print("Restarting from simulation archive. Last snapshot found at t=%.1f"%sim.t)
except:
    # Create new simualtion
    print("Creating new simulation.")
    sim = rebound.Simulation()
    sim.add(m=1) # star
    sim.add(m=1e-3, a=1, e=0.01) # planet 1
    sim.add(m=1e-3, a=2.5, e=0.01) # planet 2
    sim.integrator = "whfast"
    sim.dt = 3.1415*2.*6./365.25 # 6 days in units where G=1
    sim.move_to_com()
    sim.initSimulationArchive(filename, interval=2.*3.1415*1e5)

# Run a very long simulation.
# This can be interrupted at any time and then restarted.
sim.integrate(2.*3.1415*1e10) # 10 Gyr


class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        c = 0
        for i in s:
            c = c^ord(i)
        for i in t:
            c = c^ord(i)
        return chr(c)


from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage
from qa.models import Question
from django.core.urlresolvers import reverse
from qa.forms import AskForm, AnswerForm, SignupForm, LoginForm
from django.contrib.auth import login, logout

def test(request, *args, **kwargs):
	return HttpResponse('OK')

def paginate(request, qs):
	try:
		limit = int(request.GET.get('limit', 10))
	except ValueError:
		limit = 10
	if limit > 100:
		limit = 10

	try:
		page = int(request.GET.get('page', 1))
	except ValueError:
		raise Http404

	paginator = Paginator(qs, limit)
	try:
		page = paginator.page(page)
	except EmptyPage:
		page = paginator.page(paginator.num_pages)

	return page, paginator

def index(request):
	page, paginator = paginate(request, Question.objects.new())
	paginator.baseurl = reverse('index') + '?page='
	return render(request, 'index.html', {
		'questions': page.object_list,
		'page': page,
		'paginator': paginator,
	})

def question(request, pk):
	question = get_object_or_404(Question, id=pk)
	answers = question.answer_set.all()
	form = AnswerForm(initial={'question': str(pk)})
	return render(request, 'question.html', {
		'question': question,
		'answers': answers,
		'form': form,
	})

def ask(request):
	if request.method == 'POST':
		form = AskForm(request.POST)
		if form.is_valid():
			if request.user.is_anonymous():
				return HttpResponseRedirect('/login')

			form.user = request.user
			question = form.save()
			url = reverse('question', args=[question.id])
			return HttpResponseRedirect(url)
	else:
		form = AskForm()
	return render(request, 'asked_question.html', {
		'form': form
	})

def answer(request):
	if request.method == 'POST':
		form = AnswerForm(request.POST)
		if form.is_valid():
			if request.user.is_anonymous():
				return HttpResponseRedirect('/login')

			form.user = request.user
			answer = form.save()
			url = reverse('question', args=[answer.question.id])
			return HttpResponseRedirect(url)
	return HttpResponseRedirect('/')

def popular(request):
	page, paginator = paginate(request, Question.objects.popular())
	paginator.baseurl = reverse('popular') + '?page='
	return render(request, 'popular.html', {
		'questions': page.object_list,
		'page': page,
		'paginator': paginator,
	})

def new(request):
	return HttpResponse('OK')

def signup(request):
	if request.method == 'POST':
		form = SignupForm(request.POST)
		if form.is_valid():
			user = form.save()
			if user is not None:
				login(request, user)
				return HttpResponseRedirect('/')

	form = SignupForm()
	return render(request, 'signup.html', {
		'form': form
	})

def login_user(request):
	if request.method == 'POST':
		form = LoginForm(request.POST)
		if form.is_valid():
			user = form.save()
			if user is not None:
				login(request, user)
				return HttpResponseRedirect('/')

	form = LoginForm()
	return render(request, 'login.html', {
		'form': form
	})

def logout_user(request):
	logout(request)
	return HttpResponseRedirect('/')


import pandas as pd
data_new = pd.read_csv("~/Achyuth/web scraping/new.csv",sep=",", index_col=None).drop(columns="Unnamed: 9")
data_old = pd.read_csv("~/Achyuth/web scraping/old.csv", sep=",", index_col=None)
df_new = pd.DataFrame(data_new)
df_old = pd.DataFrame(data_old)
df_diff = df_new.merge(df_old,indicator=True, how='outer').loc[lambda x : x['_merge']=='left_only']
df_diff.to_csv('hehe.csv', index=False, encoding='utf-8')
#df_diff = df_new.compare(df_old)
#print(df_old)
#print(df_new)
#print("NEW DATA : \n",data_new)
#print("OLD DATA : \n",data_old)


import unittest
import datetime
from entities.Animal import Animal
from entities.Dono import Dono

class TestAnimal(unittest.TestCase):
    def setUp(self):
        self.dono = Dono(nome="Alice", sobrenome="Silva", cpf="123.456.789-00", numero_de_contato="123-456-7890", email="alice@example.com")

#    - Verificar se é possível cadastrar um novo animal para um cliente existente.
    def test_cadastrar_animal_com_todas_informacoes(self):
        animal = Animal(nome="Rex", especie="Cachorro", dono=self.dono, sexo="Macho", data_nascimento="2023-01-01")
        data_nascimento_esperada = datetime.date(2023, 1, 1)
        self.assertEqual(animal.nome, "Rex")
        self.assertEqual(animal.especie, "Cachorro")
        self.assertEqual(animal.dono, self.dono)
        self.assertEqual(animal.sexo, "Macho")
        self.assertEqual(animal.data_nascimento, data_nascimento_esperada)

#    - Garantir que o sistema não permita o cadastro de um animal sem um nome válido.
    def test_cadastrar_animal_sem_nome_valido(self):
        animal = Animal(nome="", especie="Cachorro", dono=self.dono, sexo="Macho", data_nascimento="2023-01-01")
        self.assertIsNone(animal.nome)

#   - Verificar se o sistema não aceita uma data de nascimento inválida para o animal.
    def test_cadastrar_animal_com_data_nascimento_invalida(self):
        animal = Animal(nome="Rex", especie="Cachorro", dono=self.dono, sexo="Macho", data_nascimento="invalida")
        self.assertIsNone(animal.data_nascimento)

#  - Garantir que o sistema permite associar um animal a um único dono.
    def test_associar_animal_a_um_unico_dono(self):
        outro_dono = Dono(nome="Bob", sobrenome="Johnson", cpf="987.654.321-00", numero_de_contato="987-654-3210", email="bob@example.com")
        animal = Animal(nome="Rex", especie="Cachorro", dono=self.dono, sexo="Macho", data_nascimento="2023-01-01")
        self.assertEqual(id(animal.dono), id(self.dono))
        animal.dono = outro_dono
        self.assertEqual(id(animal.dono), id(outro_dono))

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


import pyramid.httpexceptions as exc

class BlogException:
    @staticmethod
    def exception(code, message, field=None):
        exc.code = code
        json_output = {'status' : code, 'msg' : message}
        if field is not None:
        	json_output['field'] = field
        raise exc.exception_response(status_code=code, json_body=json_output)


from rest_framework import serializers, validators

from .models import Comment, Follow, Group, Post, User

class PostSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username'
    )

    class Meta:
        fields = '__all__'
        model = Post

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username'
    )

    class Meta:
        fields = '__all__'
        model = Comment
        read_only_fields = ['post', 'author']

class GroupSerializer(serializers.ModelSerializer):

    class Meta:
        fields = '__all__'
        model = Group

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(
        queryset=User.objects.all(),
        slug_field='username',
        default=serializers.CurrentUserDefault()
    )
    following = serializers.SlugRelatedField(
        slug_field='username',
        queryset=User.objects.all()
    )

    class Meta:
        fields = '__all__'
        model = Follow
        validators = [
            validators.UniqueTogetherValidator(
                queryset=Follow.objects.all(),
                fields=['user', 'following'],
                message='already subscribed'
            )
        ]

    def validate(self, data):
        if self.context.get('request').user == data['following']:
            raise serializers.ValidationError('subscibed to yourself denied')
        return data


import math

import nltk
from nltk.corpus import wordnet as wn
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize.punkt import PunktWordTokenizer

import sys
sys.path.insert(0, '../NLP_V3')
from database import *
from trained_model import *

file_out_text = open("testresult_header.py",'w')
result_header_map = {}

def remove_unnecessary(sentence):
	s1 = PunktWordTokenizer().tokenize(sentence)
	s2 = nltk.pos_tag(s1)
	useful = ["JJ","JJS","JJS","NN","NNS","NNP","NNPS","RB","RBR","RBS"]
	splitted = []
	# print s2
	for pairs in s2:
		if(pairs[1] in useful):
			splitted.append(pairs[0])
	return splitted

def get_non_nouns(sentence):
	s1 = PunktWordTokenizer().tokenize(sentence)
	s2 = nltk.pos_tag(s1)
	useful = ["JJ","JJS","JJS","RB","RBR","RBS"]
	splitted = []
	# print s2
	for pairs in s2:
		if(pairs[1] in useful):
			splitted.append(pairs[0])
	return splitted

def compute_for_aspect(aspect,sentence,ad_words):
	score = 0
	probability = 0
	count = 0
	for word in sentence:
		phrase = aspect + "|" + word
		if(phrase in probability_aspect_given_word.keys()):
			probability += probability_aspect_given_word[phrase]
			if(word in ad_words):
				score += score_aspect_and_word[phrase]
				count += 1
	# print(probability)
	if(count != 0):
		return [probability,(1.0*score)/(1.0*count)]
	else:
		return [probability,0]

feature_word_map = {}
score_map = {}

def understand_sentence(sentence,count):
	useless = [',',':','.',';','"',"'",')','(','[',']','{','}','|','>','<','\t','\n']
	for characters in useless:
		sentence = sentence.replace(characters,"")
	sentence = sentence.strip()
	sentence = sentence.lower()
	print(count)
	print(sentence)
	rel_words = remove_unnecessary(sentence)
	ad_words = get_non_nouns(sentence)

	sentence = sentence.split()
	lmtzr = WordNetLemmatizer()
	for word in sentence:
		word = lmtzr.lemmatize(word)
	power = {}

	for aspect in feature_list:
		power[aspect] = compute_for_aspect(aspect,sentence,ad_words)
	m_score = 0
	m_probability = 0
	m_aspect = "general"
	for aspect in feature_list:
		if power[aspect][0] > m_probability:
			m_aspect = aspect
			m_probability = power[aspect][0]
			m_score = power[aspect][1]
	print(m_aspect)

	if(m_aspect in score_map.keys()):
		score_map[m_aspect] += m_score
		feature_word_map[m_aspect] += rel_words
	else:
		score_map[m_aspect] = m_score
		feature_word_map[m_aspect] = rel_words
	result_header_map[count] = m_aspect

def my_read_file():
	count = 1
	file_in = open("testfile.txt","r")
	for line in file_in:
		understand_sentence(line,count)
		count += 1

my_read_file()

def print_output():
	file_out_text.write("result_header_map = " + str(result_header_map))

print_output()


from gcsa.attachment import Attachment
from .base_serializer import BaseSerializer

class AttachmentSerializer(BaseSerializer):
    type_ = Attachment

    def __init__(self, attachment):
        super().__init__(attachment)

    @staticmethod
    def _to_json(attachment: Attachment):
        res = {
            "fileUrl": attachment.file_url,
            "title": attachment.title,
            "mimeType": attachment.mime_type,
        }

        if attachment.file_id:
            res['fileId'] = attachment.file_id
        if attachment.icon_link:
            res['iconLink'] = attachment.icon_link

        return res

    @staticmethod
    def _to_object(json_attachment):
        return Attachment(
            file_url=json_attachment['fileUrl'],
            title=json_attachment.get('title', None),
            mime_type=json_attachment.get('mimeType', None),
            _icon_link=json_attachment.get('iconLink', None),
            _file_id=json_attachment.get('fileId', None)
        )


# ai_multiple_regression_housing.py
# This is multiple linear regression on the california hausing dataset.

from sklearn import metrics
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import ElasticNet, Lasso, Ridge
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Loading the Dataset
# Loading the Data
california = fetch_california_housing()

# Displaying the Dataset’s Description
print(california.DESCR)
print('--------------------')
print(california.data.shape)
print(california.target.shape)
print(california.feature_names)

# Exploring the Data with Pandas
pd.set_option('display.precision', 4)
pd.set_option('display.max_columns', 9)
pd.set_option('display.max_colwidth', None)
california_df = pd.DataFrame(california.data, columns=california.feature_names)
california_df['MedHouseValue'] = pd.Series(california.target)
print('--------------------')
print(california_df.head())
print('--------------------')
print(california_df.describe())

# Visualizing the Features
sample_df = california_df.sample(frac=0.1, random_state=17)
sns.set(font_scale=2)
sns.set_style('whitegrid')
for feature in california.feature_names:
    plt.figure(figsize=(16, 9))
    sns.scatterplot(data=sample_df, x=feature,
                    y='MedHouseValue', hue='MedHouseValue',
                    palette='cool', legend=False)
    plt.show()

# Splitting the Data for Training and Testing
X_train, X_test, y_train, y_test = train_test_split(
    california.data, california.target, random_state=11)
print('--------------------')
print(X_train.shape)
print(X_test.shape)

# Training the Model
linear_regression = LinearRegression()
linear_regression.fit(X=X_train, y=y_train)
print('--------------------')
for i, name in enumerate(california.feature_names):
    print(f'{name:>10}: {linear_regression.coef_[i]}')
print('--------------------')
print(linear_regression.intercept_)

# Testing the Model
predicted = linear_regression.predict(X_test)
expected = y_test
print('--------------------')
print(predicted[:5])
print(expected[:5])

# Visualizing the Expected vs. Predicted Prices
df = pd.DataFrame()
df['Expected'] = pd.Series(expected)
df['Predicted'] = pd.Series(predicted)
figure = plt.figure(figsize=(9, 9))
axes = sns.scatterplot(data=df, x='Expected', y='Predicted',
    hue='Predicted', palette='cool', legend=False)
start = min(expected.min(), predicted.min())
end = max(expected.max(), predicted.max())
axes.set_xlim(start, end)
axes.set_ylim(start, end)
line = plt.plot([start, end], [start, end], 'k--')
plt.show()

# Regression Model Metrics
print('--------------------')
print('Regression Model Metrics:')
print('Coefficient of determination (R2):')
print(metrics.r2_score(expected, predicted))
print('Mean squuared error (MSE):')
print(metrics.mean_squared_error(expected, predicted))

# Choosing the Best Model
print('--------------------')
estimators = {
    'LinearRegression': linear_regression,
    'ElasticNet': ElasticNet(),
    'Lasso': Lasso(),
    'Ridge': Ridge()
}
for estimator_name, estimator_object in estimators.items():
    kfold = KFold(n_splits=10, random_state=11, shuffle=True)
    scores = cross_val_score(estimator=estimator_object,
        X=california.data, y=california.target, cv=kfold,
        scoring='r2')
    print(f'{estimator_name:>16}: ' +
        f'mean of r2 scores={scores.mean():.3f}')


import os
from flask import Flask , render_template, request
app=Flask(__name__)

def evaluate_form(f):
    info_list = []
    count = 0
    for x,y in f.items():
        if x=="usr":
            info_list.append(["Your Name:", y])
        elif x in ["snork", "beach", "food", "nature", "walking"]:
            info_list.append(["Interest:", y])
        elif x=="optradio":
            info_list.append(["Your age:", y])
        elif x=="comment":
            info_list.append(["Your comment:", y])
        elif x=="remember":
            info_list.append(["", "We'll remember you"])
        print("{},{}".format(x,y))
        count +=1
    for x,y in info_list:
        print("{},{}".format(x,y))
    errors = []
    errors.append("Please attend to the following errors before this form can be submitted")
    errors.append("You have not supplied a valid name")
    return True, info_list

@app.route('/')
def main_index():
    return render_template('index.html')

@app.route('/places')
def places():
    return render_template('places.html')

@app.route('/gallery')
def gallery():
    return render_template('gallery.html')

@app.route('/contact')
def contact():
    return render_template('contact.html')

@app.route('/contactone', methods=["GET", "POST"])
def contactone():
    if request.method == "POST":
        myform = request.form
        response = evaluate_form(myform)
        if response[0] is True:
            return render_template('success.html', formdata=response[1])
        else:
            return render_template('contact_one.html', errorlist=response[1])
    else:
        return render_template('contact_one.html')

if __name__ == '__main__':
   app.run(debug=True)


import sqlite3

# Membuat koneksi ke database
conn = sqlite3.connect('contacts.db')

# Membuat tabel kontak
conn.execute('''CREATE TABLE IF NOT EXISTS contacts
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
             name TEXT NOT NULL,
             phone TEXT NOT NULL);''')

# Menambahkan kontak baru
def add_contact(name, phone):
    conn.execute("INSERT INTO contacts (name, phone) VALUES (?, ?)", (name, phone))
    conn.commit()

# Mencari kontak berdasarkan nama
def search_contact(name):
    cursor = conn.execute("SELECT * FROM contacts WHERE name=?", (name,))
    result = cursor.fetchone()
    return result

# Mengubah kontak yang ada
def update_contact(name, phone):
    conn.execute("UPDATE contacts SET phone=? WHERE name=?", (phone, name))
    conn.commit()

# Menghapus kontak yang ada
def delete_contact(name):
    conn.execute("DELETE FROM contacts WHERE name=?", (name,))
    conn.commit()

# Menampilkan semua kontak
def show_contacts():
    cursor = conn.execute("SELECT * FROM contacts")
    results = cursor.fetchall()
    for row in results:
        print("ID:", row[0])
        print("Name:", row[1])
        print("Phone:", row[2])
        print()

# Menutup koneksi ke database
def close():
    conn.close()

# Contoh penggunaan fungsi-fungsi CRUD
add_contact("Satriya", "0851111222")
add_contact("Bagus", "0895688812")

print("Daftar Kontak:")
show_contacts()

print("Mencari kontak dengan nama 'Satriya':")
result = search_contact("Satriya")
if result:
    print("ID:", result[0])
    print("Name:", result[1])
    print("Phone:", result[2])
else:
    print("Kontak tidak ditemukan")

print("Mengubah nomor telepon untuk kontak 'Bagus':")
update_contact("Bagus", "0852156125")

print("Daftar Kontak setelah diubah:")
show_contacts()

print("Menghapus kontak dengan nama 'Satriya':")
delete_contact("Satriya")

print("Daftar Kontak setelah dihapus:")
show_contacts()

# Menutup koneksi ke database
close()


from typing import Iterator
import itertools
import more_itertools
from torch import isin

from regex_ast import *
from regex_lexer import *

# expression -> term
# expression -> term | expression

# term -> step
# term -> step > term

# step -> factor
# step -> factor & step

# factor -> (expression)
# factor -> (expression)+
# factor -> (expression){symbol}
# factor -> (expression)*
# factor -> (expression)~
# factor -> matcher
# factor -> !matcher

# matcher -> symbol
# matcher -> _
# matcher -> .

def parse_expression(lex: more_itertools.peekable) -> RENode:
    left = parse_term(lex)
    token = lex.peek()
    if isinstance(token, OrT):
        next(lex)
        right = parse_expression(lex)
        or_terms = [left]
        if isinstance(right, Or):
            or_terms.extend(right.exprs)
        else:
            or_terms.append(right)
        return Or(or_terms)
    return left

def parse_term(lex: more_itertools.peekable) -> RENode:
    left = parse_step(lex)
    token = lex.peek()
    if isinstance(token, ThenT):
        next(lex)
        right = parse_term(lex)
        then_terms = [left]
        if isinstance(right, Then):
            then_terms.extend(right.exprs)
        else:
            then_terms.append(right)
        return Then(then_terms)
    return left

def parse_step(lex: more_itertools.peekable) -> RENode:
    left = parse_factor(lex)
    token = lex.peek()
    if isinstance(token, AndT):
        next(lex)
        right = parse_step(lex)
        and_terms = [left]
        if isinstance(right, And):
            and_terms.extend(right.exprs)
        else:
            and_terms.append(right)
        return And(and_terms)
    return left

def parse_factor(lex: more_itertools.peekable) -> RENode:
    token = lex.peek()
    if isinstance(token, OpenT):
        next(lex)
        expression = parse_expression(lex)
        token = next(lex)
        assert isinstance(token, CloseT), 'expected )'
        token = lex.peek()
        if isinstance(token, RepeatT):
            next(lex)
            return Repeat(expression)
        elif isinstance(token, PlusT):
            next(lex)
            return Plus(expression)
        elif isinstance(token, OpenMulT):
            next(lex)
            token = next(lex)
            assert isinstance(token, SymbolT)
            number: str = token.symbol
            token = next(lex)
            assert isinstance(token, CloseMulT)
            return Multiple(expression, number)
        elif isinstance(token, ComplementT):
            next(lex)
            return Complement(expression)
        else:
            return expression
    elif isinstance(token, NotT):
        next(lex)
        return parse_matcher(lex, True)
    else:
        return parse_matcher(lex, False)

def parse_matcher(lex: more_itertools.peekable, negated: bool) -> RENode:
    token = next(lex)
    if isinstance(token, SymbolT):
        return Symbol(token.symbol, negated)
    elif isinstance(token, NonemptyT):
        return Nonempty(negated)
    elif isinstance(token, NonappearT):
        return Nonappear(negated)
    else:
        assert isinstance(token, AnyT), 'expected AnyT'
        return Any(negated)

def parse(src: str) -> RENode:
    lexed = more_itertools.peekable(lex(src))
    expr = parse_expression(lexed)
    token = next(lexed)
    if not isinstance(token, EndT):
        raise ValueError(
            f"root expression doesn't end with End, continues: {token}")
    return expr


print("Welcome to the quiz game")
ans=input("Are you ready to play \n")
score =0
total_q=4
if ans == "no":
    print("ok bye")
if ans == "yes":
    ans= input ("1)what is the name of our country? \n")
    if ans.lower() == "pakistan":
        score += 1
        print("correct")
    else:
        print("incorrect")

    ans= input ("2)what is the atomic number of carbon? \n")
    if ans == "6":
        score += 1
        print("correct")
    else:
        print("incorrect")

    ans= input ("3)5+8+6? \n")
    if ans == "19":
        score += 1
        print("correct")
    else:
        print("incorrect")

    ans= input ("4)which is the best programming language? \n")
    if ans.lower() == "python":
        score += 1
        print("correct")
    else:
        print("incorrect")
    print("Thankyou for playing", "your", score , "answers are correct")
    percentage= int((score/total_q)*100)
    print("congrates you got ", percentage ,"percent marks in quiz")


import networkx as nx
from pox.core import core
from util import get_key_from_value

class Graph:

    def __init__(self,componentLinkDiscovery):
        componentLinkDiscovery.addListeners(self)
        core.openflow.addListeners(self)
        self.graph_with_gw_node = None
        self.graph_without_gw = None

    def _handle_linkDiscovered(self,event):
        print("All links have been discovered, starting graph computation...\n")
        self.graph_with_gw_node = self.get_graph(route_to_gw=True)
        self.graph_without_gw = self.get_graph()

    def get_graph(self,route_to_gw = False):

        G = nx.Graph()
        gw_dpid = core.GatewayAccess.get_dpid_gw()
        gw_id = get_key_from_value(core.linkDiscovery.switch_id, gw_dpid)

        nodes = list()
        if route_to_gw:
            nodes = list(core.linkDiscovery.switch_id.keys())

        else:
            for sw_id in list(core.linkDiscovery.switch_id.keys()):
                if gw_id != sw_id:
                    nodes.append(sw_id)

        G.add_nodes_from(nodes)
        for link in core.linkDiscovery.links:
            sid1 = core.linkDiscovery.links[link].sid1
            sid2 = core.linkDiscovery.links[link].sid2
            weight = core.linkDiscovery.links[link].flow  # Get flows of the link
            if route_to_gw:
                G.add_edge(sid1,sid2,weight=weight)
            else:
                if not core.linkDiscovery.links[link].gw_link:
                    G.add_edge(sid1,sid2,weight=weight)
        print(G)
        print(G.edges.data())
        return G

    def update_weight(self, G, u, v, new_weight, decrement = False):
        if G.has_edge(u,v):
            G[u][v]["weight"] += new_weight if not decrement else -1 * new_weight
        else:
            print(f"Error:({u},{v}) not in graph")

def launch():
    core.register(Graph(core.linkDiscovery))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

from alipay.aop.api.constant.ParamConstants import *

class AlipayEcoMycarParkingAgreementQueryModel(object):

    def __init__(self):
        self._alipay_user_id = None
        self._car_number = None
        self._ver = None

    @property
    def alipay_user_id(self):
        return self._alipay_user_id

    @alipay_user_id.setter
    def alipay_user_id(self, value):
        self._alipay_user_id = value
    @property
    def car_number(self):
        return self._car_number

    @car_number.setter
    def car_number(self, value):
        self._car_number = value
    @property
    def ver(self):
        return self._ver

    @ver.setter
    def ver(self, value):
        self._ver = value

    def to_alipay_dict(self):
        params = dict()
        if self.alipay_user_id:
            if hasattr(self.alipay_user_id, 'to_alipay_dict'):
                params['alipay_user_id'] = self.alipay_user_id.to_alipay_dict()
            else:
                params['alipay_user_id'] = self.alipay_user_id
        if self.car_number:
            if hasattr(self.car_number, 'to_alipay_dict'):
                params['car_number'] = self.car_number.to_alipay_dict()
            else:
                params['car_number'] = self.car_number
        if self.ver:
            if hasattr(self.ver, 'to_alipay_dict'):
                params['ver'] = self.ver.to_alipay_dict()
            else:
                params['ver'] = self.ver
        return params

    @staticmethod
    def from_alipay_dict(d):
        if not d:
            return None
        o = AlipayEcoMycarParkingAgreementQueryModel()
        if 'alipay_user_id' in d:
            o.alipay_user_id = d['alipay_user_id']
        if 'car_number' in d:
            o.car_number = d['car_number']
        if 'ver' in d:
            o.ver = d['ver']
        return o


"""
This module contains code to find starting point on each main stream.
"""

from pathlib import Path
from shutil import copy2
from tempfile import TemporaryDirectory
from typing import Callable, Generator, List, Optional, Tuple, Union

import fiona
import geosardine as dine
import numpy as np
import rasterio
import whitebox
from rasterio.features import geometry_mask
from shapely import geometry, ops, speedups
from shapely.geometry import Point
from shapely.geometry.base import BaseGeometry
from tqdm.autonotebook import tqdm

from .custom_types import GeoJsonDict

speedups.disable()

wbt = whitebox.WhiteboxTools()

class StemTooShort(Exception):
    """Stream/Stem is too short to calculate volume. It is near the start vertex"""

    pass

class DifferentCRS(Exception):
    """two data have different CRS"""

    pass

class ProcessingData:
    """
    Contains processing data in temporary directory
    """

    def __init__(self, flow_direction: Path, flow_stream: Path) -> None:
        self.temp_folder = TemporaryDirectory()
        self.temp_path = Path(self.temp_folder.name)
        self.flow_direction = flow_direction
        self.flow_stream = flow_stream

        self.main_stem_rasterfile = self.temp_path / "main_stem.tif"
        self.main_stem_vectorfile = self.temp_path / "main_stem.shp"
        self.link_class_file = self.temp_path / "link_class.tif"

        self.link_class: Optional["dine.Raster"] = None

        self.generate()

    def generate(self) -> None:
        """generate processing data"""
        wbt.find_main_stem(
            self.flow_direction,
            self.flow_stream,
            self.main_stem_rasterfile,
            esri_pntr=True,
        )
        wbt.stream_link_class(
            self.flow_direction, self.flow_stream, self.link_class_file, esri_pntr=True
        )
        wbt.raster_streams_to_vector(
            self.main_stem_rasterfile,
            self.flow_direction,
            self.main_stem_vectorfile,
            esri_pntr=True,
        )

        self.link_class = dine.Raster.from_rasterfile(str(self.link_class_file))
        print("processing data has been generated")

    def save(self, output_directory: Path) -> None:
        """Copy processing data to outside temporary directory

        Parameters
        ----------
        output_directory : Path
            directory to copy processing data
        """
        for f in self.temp_path.glob("*"):
            if f.is_file():
                copy2(f.absolute(), output_directory)

    def cleanup(self) -> None:
        """remove  temporary directory"""
        self.temp_folder.cleanup()

def interpolate_points(
    polyline: geometry.LineString, distance: float = 0.25, upstream: int = 0
) -> Generator[geometry.Point, None, None]:
    """interpolate points along line

    Parameters
    ----------
    polyline : geometry.LineString
        stream
    distance : float, optional
        interpolation distance, by default 0.25
    upstream : int, optional
        [description], by default 0

    Yields
    -------
    Generator[geometry.Point, None, None]
        interpolated points
    """
    interpolate_distances = np.arange((polyline.length // distance) + 1)
    for interpolate_distance in interpolate_distances:
        yield polyline.interpolate(interpolate_distance)

def estimate_volume(array: np.ndarray, dsm_diff: dine.Raster) -> float:
    """estimate volume

    Parameters
    ----------
    array : np.ndarray
        clipped dsm difference of 2 epoch by buffered starting point
    dsm_diff : dine.Raster
        dsm difference of 2 epoch

    Returns
    -------
    float
        volume
    """
    return float(
        np.sum(array[(array > dsm_diff.no_data) & (array > 0)]) * dsm_diff.resolution[0]
    )

def calculate_volume_stem(
    stem: geometry.LineString,
    point: geometry.Point,
    dsm_diff: "dine.Raster",
    stream_buffer_size: float,
) -> float:
    """Calculate stem by buffering the stem

    Parameters
    ----------
    stem : geometry.LineString
        stream
    point : geometry.Point
        starting point
    dsm_diff : dine.Raster
        dsm difference of 2 epoch
    stream_buffer_size : float
        buffer length for stream

    Returns
    -------
    float
        volume

    Raises
    ------
    StemTooShort
        stem is below 5 times spatial resolution which will caused too small volume
    """
    splitted = ops.split(stem, point.buffer(0.1))
    if splitted[0].length < dsm_diff.resolution[0] * 5:
        raise StemTooShort
    mask = geometry_mask(
        [geometry.mapping(splitted[0].buffer(stream_buffer_size))],
        transform=dsm_diff.transform,
        out_shape=dsm_diff.shape[:2],
    )
    return float(
        (
            dsm_diff.array[
                (~mask.reshape(mask.shape[0], mask.shape[1], 1))
                & (dsm_diff > 0)
                & (dsm_diff != dsm_diff.no_data)
            ]
            * dsm_diff.resolution[0]
        ).sum()
    )

def find_starting_point(
    stem: geometry.LineString,
    distance: float,
    dsm_diff: "dine.Raster",
    link_class: "dine.Raster",
    stream_buffer_size: float,
) -> Tuple[Optional[geometry.Point], Optional[float]]:
    """find starting point over main stem

    Parameters
    ----------
    stem : geometry.LineString
        main stem
    distance : float
        interpolation distance
    dsm_diff : dine.Raster
        dsm difference of 2 epoch
    link_class : dine.Raster
        stream link class
    stream_buffer_size : float
        buffer length for stream

    Returns
    -------
    Tuple[Optional[geometry.Point], Optional[float]]
        Starting point and volume
        if geometry.Point & float, there is starting point
        if None & None, there isn't any starting point

    Raises
    ------
    ValueError
        Wrong type
    """

    if stem.length < 100:
        return None, None

    buffer_pixel = 5
    buffer_area = (buffer_pixel * 2) ** 2
    minimum_pixel = buffer_area * 0.5

    point_in_stem = interpolate_points(stem, distance)

    sp_candidates: List[geometry.Point] = []
    sp_candidates_junction: List[geometry.Point] = []
    for point in point_in_stem:
        point_diff = dsm_diff.xy_value(point.x, point.y)
        if point_diff != dsm_diff.no_data and point_diff >= 0:
            row, col = dsm_diff.xy2rowcol(point.x, point.y)

            bounding_box = np.array(
                [
                    row - buffer_pixel,
                    col - buffer_pixel,
                    row + buffer_pixel,
                    col + buffer_pixel,
                ]
            )

            deposition_pixel_count: int = np.sum(
                dsm_diff.array[
                    bounding_box[0] : bounding_box[2], bounding_box[1] : bounding_box[3]
                ]
                > 0
            )

            if (
                np.all(bounding_box > 0)
                and dsm_diff.array[row, col] > 0
                and deposition_pixel_count > minimum_pixel
            ):
                link_type = link_class.xy_value(point.x, point.y)

                if not isinstance(link_type, np.ndarray):
                    raise ValueError("Unexpected")

                if link_type[0] == 4:
                    sp_candidates_junction.append(point)
                else:
                    sp_candidates.append(point)
    starting_point = None
    if sp_candidates_junction:
        starting_point = sp_candidates_junction[-1]
    elif sp_candidates:
        starting_point = sp_candidates[-1]

    if starting_point is not None:
        try:
            volume: Optional[float] = calculate_volume_stem(
                stem, starting_point, dsm_diff, stream_buffer_size
            )
        except StemTooShort:
            row, col = dsm_diff.xy2rowcol(starting_point.x, starting_point.y)

            bounding_box = np.array(
                [
                    row - buffer_pixel,
                    col - buffer_pixel,
                    row + buffer_pixel,
                    col + buffer_pixel,
                ]
            )

            buffered_point = dsm_diff.array[
                bounding_box[0] : bounding_box[2], bounding_box[1] : bounding_box[3]
            ]
            volume = estimate_volume(
                buffered_point[buffered_point != dsm_diff.no_data],
                dsm_diff,
            )
    else:
        volume = None

    return starting_point, volume

def find_starting_points(
    input_earlier_dsm: str,
    input_later_dsm: str,
    input_flow_direction: str,
    input_flow_stream: str,
    max_percent_length: float,
    stream_buffer_size: float,
    return_processing_data: bool = False,
    progress_callback: Optional[Callable[[int, int], None]] = None,
) -> Tuple[List[Tuple[Point, float]], Optional[ProcessingData]]:
    """Batch find starting point for streams

    Parameters
    ----------
    input_earlier_dsm : str
        earlier dsm (first epoch) location
    input_later_dsm : str
        later dsm (second epoch) location
    input_flow_direction : str
        flow direction location d8-esri-style
    input_flow_stream : str
        flow stream location
    max_percent_length : float
        maximum percentage of stream to be included
    stream_buffer_size : float
        buffer length for stream
    return_processing_data : bool, optional
        return processing data as variable, by default False
    progress_callback : Optional[Callable[[int, int], None]], optional
        callback to be called after each loop, by default None

    Returns
    -------
    Tuple[List[Tuple[Point, float]], Optional[ProcessingData]]
        starting point, volume & processing data
        if Tuple[List[Tuple[Point, float]], ProcessingData], processing data is returned
        if Tuple[List[Tuple[Point, float]], None], processing data is not returned

    Raises
    ------
    ValueError
        Different CRS
    ValueError
        Wrong type
    e
        There is any exception raised
    """
    if progress_callback is not None:
        progress_callback(0, 0)

    processing_data = ProcessingData(
        Path(input_flow_direction), Path(input_flow_stream)
    )

    try:
        print(processing_data.main_stem_vectorfile)
        print("r", input_earlier_dsm, input_later_dsm)
        with fiona.open(processing_data.main_stem_vectorfile) as lines, rasterio.open(
            input_earlier_dsm
        ) as earlier_dsm, rasterio.open(input_later_dsm) as later_dsm:
            earlier_dsm = dine.Raster.from_rasterfile(input_earlier_dsm)
            later_dsm = dine.Raster.from_rasterfile(input_later_dsm)

            if later_dsm.epsg != earlier_dsm.epsg:
                raise ValueError("Both dsm should be in the same reference system")

            dsm_diff = later_dsm - earlier_dsm

            starting_points: List[Tuple[Point, float]] = []
            sp_coordinates: np.ndarray = np.empty((1, 2), dtype=np.float32)

            features: Tuple[Tuple[int, GeoJsonDict], ...] = tuple(
                lines.items(
                    bbox=(
                        later_dsm.x_min,
                        later_dsm.y_min,
                        later_dsm.x_max,
                        later_dsm.y_max,
                    )
                )
            )

            progress_total = len(features)

            for i, feature in tqdm(features, total=progress_total):

                line = feature["geometry"]["coordinates"]
                if later_dsm.xy_value(
                    *feature["geometry"]["coordinates"][0]
                ) < later_dsm.xy_value(*feature["geometry"]["coordinates"][-1]):
                    line = feature["geometry"]["coordinates"][::-1]

                stem = geometry.LineString(line)
                stem = ops.substring(stem, 0, stem.length * max_percent_length / 100)

                # if isinstance(stem, BaseGeometry) or processing_data.link_class is None:
                #     raise ValueError("Unexpected")

                starting_point, volume = find_starting_point(
                    stem, 0.25, dsm_diff, processing_data.link_class, stream_buffer_size
                )
                if starting_point is not None and volume is not None:
                    near_sp_exist = any(
                        (
                            np.abs(sp_coordinates[:, 0] - starting_point.x)
                            + np.abs(sp_coordinates[:, 1] - starting_point.y)
                        )
                        <= 3
                    )

                    if not near_sp_exist:
                        starting_points.append((starting_point, volume))

                if progress_callback is not None:
                    progress_callback(progress_total, i + 1)
            if return_processing_data:
                return starting_points, processing_data
            else:
                # processing_data.cleanup()
                return starting_points, None
    except Exception as e:
        processing_data.cleanup()
        raise e

def save2txt(
    starting_points: List[Tuple[Point, float]], output_location: Union[Path, str]
) -> None:
    """Save starting points and volume as csv

    Parameters
    ----------
    starting_points : List[Tuple[Point, float]]
        list of starting point as Point and volume
    output_location : Union[Path, str]
        location to save starting point
    """
    with open(output_location, "w") as out:
        for starting_point, volume in starting_points:
            out.writelines(f"{starting_point.x},{starting_point.y},{volume}\n")


from dataclasses import dataclass
import numpy as np

from .find_r_peaks import find_r_peaks
from .find_t_peak_ends import find_t_peak_ends
from .find_agreeing_points import Agree_reduce_method
from .constants import mean_s1_duration

@dataclass
class ECG_peaks:
    r_peaks: np.ndarray
    rpeaks_where_next_is_also_agreed: np.ndarray
    rpeaks_by_detector: dict
    downsampled_signal: np.ndarray
    downsampled_sample_rate: float

    t_peak_ends: np.ndarray
    t_peak_ends_by_detector: dict

def find_ecg_peaks(
    ecg,
    ecg_sample_rate,
    r_peak_agreement_time_threshold=0.1,
    r_peak_max_disagreers=2,
    r_peak_root_detector="xqrs",
    r_peak_agree_reduce_method=Agree_reduce_method.MAX,
    r_peak_max_num_detectors_with_between_point=2,
    t_peak_agreement_time_threshold=mean_s1_duration,
    t_peak_max_disagreers=1,
    t_peak_root_detector="cwt",
    t_peak_agree_reduce_method=Agree_reduce_method.MEDIAN,
):
    ecg_r_peaks = find_r_peaks(
        ecg,
        ecg_sample_rate,
        agreement_time_threshold=r_peak_agreement_time_threshold,
        max_disagreers=r_peak_max_disagreers,
        root_detector=r_peak_root_detector,
        agree_reduce_method=r_peak_agree_reduce_method,
        max_num_detectors_with_between_point=r_peak_max_num_detectors_with_between_point,
    )

    ecg_t_peak_ends = find_t_peak_ends(
        ecg,
        ecg_sample_rate,
        ecg_r_peaks.r_peaks,
        ecg_r_peaks.rpeaks_where_next_is_also_agreed,
        agreement_time_threshold=t_peak_agreement_time_threshold,
        max_disagreers=t_peak_max_disagreers,
        root_detector=t_peak_root_detector,
        agree_reduce_method=t_peak_agree_reduce_method,
    )

    return ECG_peaks(
        ecg_r_peaks.r_peaks,
        ecg_r_peaks.rpeaks_where_next_is_also_agreed,
        ecg_r_peaks.rpeaks_by_detector,
        ecg_r_peaks.downsampled_signal,
        ecg_r_peaks.downsampled_sample_rate,
        ecg_t_peak_ends.t_peak_ends,
        ecg_t_peak_ends.t_peak_ends_by_detector,
    )


from django.shortcuts import render

from core.models import *

from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
def collection(request, user=None, clist="collection"):
	f = {}
	ret = {}
	page = request.GET.get('page')
	q = request.REQUEST.get("q")

	if user:
		f["owned_by__owner"] = User.objects.get(username = user)
		f["owned_by__list"] = clist

	if q:
		f["title__contains"] = q
		ret["q"]=q

	s = Comic.objects.filter(**f)
	paginator = Paginator(s, 60)

	try:
		s = paginator.page(page)
	except PageNotAnInteger:
		s = paginator.page(1)
	except EmptyPage:
		s = paginator.page(paginator.num_pages)

	ret["collection"] = s

	if request.user.is_authenticated():
		ret["owneds"]= [c.ident for c in Comic.objects.filter(owned_by__owner = request.user)]
	return render(request, "list.html", ret)

@login_required
@csrf_exempt
def add(request):
	comic = Comic.objects.get(ident=request.REQUEST.get("comic"))
	c = Collection()
	c.owner = request.user
	c.comic = comic
	if request.REQUEST.get("list") == "wishlist":
		c.the_list = "wishlist"
	c.save()

	return HttpResponse("
added!
")

@login_required
@csrf_exempt
def rem(request):
	comic = Comic.objects.get(ident=request.REQUEST.get("comic"))
	Collection.objects.filter(comic = comic, owner = request.user).delete()

	return HttpResponse("
removed!
")

def profile(request):
	return HttpResponseRedirect("/collection/%s" % request.user.username)

from django.contrib.auth import logout as lo
def logout(request):
	lo(request)
	return HttpResponseRedirect("/")


# -*- coding: utf-8 -*-
import http.client
import json
import numpy as np

# srv endpoint
ENDPOINT = '10.11.10.131:7010'
conn = http.client.HTTPConnection(ENDPOINT)

# 需要导出的case_num
#case_nums = ['080BF4_080-020_1.2.840.113619.6.80.114374075989539.5865']
case_nums = list(np.load('./latest.npy'))
headers = {
    'Content-Type': "application/json",
    'Cache-Control': "no-cache",
}

form = {'case_nums': case_nums}
payload = json.dumps(form)

print('Exporting cases:', case_nums)

try:
    conn.request("POST", "/reports/file/export", payload, headers)

    res = conn.getresponse()
    data = res.read()

    print(data.decode("utf-8"))
except BaseException as e:
    print("Error exporting cases:", case_nums)
    print(repr(e))


# -*- coding:utf-8 -*-
import sys
import json
from . import text
from .table import MultiTable
import jmespath
import io

PY2 = sys.version_info[0] == 2

class Response(object):
    def __init__(self, args):
        self.args = args

    def __call__(self, command, response, stream=None):
        if stream is None:
            if not PY2:
                sys.stdout = io.TextIOWrapper(sys.stdout.buffer,
                                              encoding='utf-8')
            stream = sys.stdout
        if _has_filter_param(self.args)[0]:
            filter_value = _has_filter_param(self.args)[1]
            expression = jmespath.compile(filter_value)
            response = expression.search(response)
        try:
            self._format_response(command, response, stream)
        except IOError as e:
            pass
        finally:
            self._flush_stream(stream)

    def _flush_stream(self, stream):
        try:
            stream.flush()
        except IOError:
            pass

class JSONResult(Response):
    def _format_response(self, command, response, stream=None):
        if stream is None:
            if not PY2:
                sys.stdout = io.TextIOWrapper(sys.stdout.buffer,
                                              encoding='utf-8')
            stream = sys.stdout
        if response:
            ret = json.dumps(response, ensure_ascii=False, indent=4)
            if PY2:
                import platform
                if 'Windows' in platform.system():
                    print(ret.encode('GBK'))
                else:
                    print(ret.encode('utf8'))
            else:
                print(ret)
            stream.write('\n')

class TextResult (Response):
    def __call__(self, command, response, stream=None):
        if stream is None:
            if not PY2:
                sys.stdout = io.TextIOWrapper(sys.stdout.buffer,
                                              encoding='utf-8')
            stream = sys.stdout
        try:
            self._format_response(response, stream)
        finally:
            self._flush_stream(stream)

    def _format_response(self, response, stream):
        if _has_filter_param(self.args)[0]:
            filter_value = _has_filter_param(self.args)[1]
            expression = jmespath.compile(filter_value)
            response = expression.search(response)
        text.format_text(response, stream)

class TableResult (Response):
    def __init__(self, args, table=None):
        super(TableResult, self).__init__(args)
        self.table = MultiTable(initial_section=False,
                                column_separator='|')

    def _format_response(self, command, response, stream):
        if self._build_table(command, response):
            try:
                self.table.render(stream)
            except IOError:
                pass

    def _build_table(self, title, current, indent_level=0):
        if not current:
            return False
        if title is not None:
            self.table.new_section(title, indent_level=indent_level)
        if isinstance(current, list):
            if isinstance(current[0], dict):
                self._build_sub_table_from_list(current, indent_level, title)
            else:
                for item in current:
                    if self._scalar_type(item):
                        self.table.add_row([item])
                    elif all(self._scalar_type(el) for el in item):
                        self.table.add_row(item)
                    else:
                        self._build_table(title=None, current=item)
        elif isinstance(current, dict):
            self._build_sub_table_from_dict(current, indent_level)
        else:
            self.table.add_row([current])
        return True

    def _build_sub_table_from_dict(self, current, indent_level):

        headers, more = self._group_scalar_keys(current)
        if len(headers) == 1:
            self.table.add_row([headers[0], current[headers[0]]])
        elif headers:
            self.table.add_row_header(headers)
            self.table.add_row([current[k] for k in headers])
        for remaining in more:
            self._build_table(remaining, current[remaining],
                              indent_level=indent_level + 1)

    def _build_sub_table_from_list(self, current, indent_level, title):
        headers, more = self._group_scalar_keys_from_list(current)
        self.table.add_row_header(headers)
        first = True
        for element in current:
            if not first and more:
                self.table.new_section(title,
                                       indent_level=indent_level)
                self.table.add_row_header(headers)
            first = False

            self.table.add_row([element.get(header, '')
                                for header in headers])
            for remaining in more:

                if remaining in element:
                    self._build_table(remaining, element[remaining],
                                      indent_level=indent_level + 1)

    def _scalar_type(self, element):
        return not isinstance(element, (list, dict))

    def _group_scalar_keys_from_list(self, list_of_dicts):
        headers = set()
        more = set()
        for item in list_of_dicts:
            current_headers, current_more = self._group_scalar_keys(item)
            headers.update(current_headers)
            more.update(current_more)
        headers = list(sorted(headers))
        more = list(sorted(more))
        return headers, more

    def _group_scalar_keys(self, current):
        more = []
        headers = []
        for element in current:
            if self._scalar_type(current[element]):
                headers.append(element)
            else:
                more.append(element)
        headers.sort()
        more.sort()
        return headers, more

def _has_filter_param(args):
    has = False
    param = None
    if isinstance(args, dict):
        value = args.get('filter')
        if isinstance(value, list) and len(value) > 0:
            param = value[0]
            param = param.strip()
            if len(param) > 0:
                has = True
    return [has, param]

def get_result(output_type, result):
    if output_type is None:
        output_type = 'json'
    if output_type == 'json':
        return JSONResult(result)
    elif output_type == 'text':
        return TextResult(result)
    elif output_type == 'table':
        return TableResult(result)
    raise ValueError('Unknown output type: %s\nCurrently supported output '
                     'formats: "json", "text" and "table".' % output_type)

def display_result(command, response, output, result=None):
    if output is None:
        output = 'JSON'
    formatter = get_result(output, result)
    formatter(command, response)


import os, sys
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

requirements = [
    'Django>=1.11',
    'djangorestframework>=3.14.0',
    'Pillow>=4.2.1',
    'schema>=0.6.7',
    'jsonfield>=3.1.0'
]

if sys.version_info >= (3,8,0):
    requirements[0] = 'Django>=3.1'

setup(
    name='django-rest-framework-generator',
    version='0.6.0',
    packages=['drfs'],
    include_package_data=True,
    license='BSD License',
    description='Models, Serializers, Views generator for DRF',
    long_description=README,
    author='Gerasev Kirill',
    author_email='gerasev.kirill@gmail.com',
    install_requires=requirements,
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


"""
A base class for RNN.
"""
import torch.nn as nn

from seq2seq.util.base import Module

class BaseRNN(Module):
    r"""
    Applies a multi-layer RNN to an input sequence.
    Note:
        Do not use this class directly, use one of the sub classes.
    Args:
        vocab_size (int): size of the vocabulary
        max_len (int): maximum allowed length for the sequence to be processed
        hidden_size (int): number of features in the hidden state `h`
        input_dropout_p (float): dropout probability for the input sequence
        dropout_p (float): dropout probability for the output sequence
        n_layers (int): number of recurrent layers
        rnn_cell (str): type of RNN cell (Eg. 'LSTM' , 'GRU')

    Inputs: ``*args``, ``**kwargs``
        - ``*args``: variable length argument list.
        - ``**kwargs``: arbitrary keyword arguments.

    Attributes:
        SYM_MASK: masking symbol
        SYM_EOS: end-of-sequence symbol
    """
    SYM_MASK = "MASK"
    SYM_EOS = "EOS"

    def __init__(self, vocab_size, max_len, hidden_size,
                 input_dropout_p=0,
                 rnn_cell="gru",
                 **rnn_kwargs):
        super(BaseRNN, self).__init__()
        self.vocab_size = vocab_size
        self.max_len = max_len
        self.hidden_size = hidden_size
        self.input_dropout = nn.Dropout(p=input_dropout_p)
        self.rnn_cell = rnn_cell.lower()
        self.rnn_kwargs = rnn_kwargs

    def forward(self, *args, **kwargs):
        raise NotImplementedError()


def anagram_check(s, t):
    if len(s) != len(t):
        return False
    counts = [0] * 26
    for i in range(len(s)):
        counts[ord(s[i]) - ord('a')] += 1
        counts[ord(t[i]) - ord('a')] -= 1
    for i in range(26):
        if counts[i] != 0:
            return False
    return True


import sys
import unittest
try:
    from unittest.mock import MagicMock
except ImportError:
    from mock import MagicMock
import botocore

##############
# Parameters #
##############

# Define the default resource to report to Config Rules
DEFAULT_RESOURCE_TYPE = 'AWS::ECR::Repository'

#############
# Main Code #
#############

CONFIG_CLIENT_MOCK = MagicMock()
STS_CLIENT_MOCK = MagicMock()
ECR_CLIENT_MOCK = MagicMock()

class Boto3Mock():
    @staticmethod
    def client(client_name, *args, **kwargs):
        if client_name == 'config':
            return CONFIG_CLIENT_MOCK
        if client_name == 'sts':
            return STS_CLIENT_MOCK
        if client_name == 'ecr':
            return ECR_CLIENT_MOCK
        raise Exception("Attempting to create an unknown client")

sys.modules['boto3'] = Boto3Mock()

RULE = __import__('ECR_REPOSITORY_SCAN_ON_PUSH_CHECK')

class NotApplicable(unittest.TestCase):
    def test_scenario_1_not_applicable(self):
        list_repositories_result = {"repositories": []}

        ECR_CLIENT_MOCK.describe_repositories = MagicMock(return_value=list_repositories_result)
        rule_parameters = '{}'
        lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(rule_parameters), {})
        expected_response = [build_expected_response("NOT_APPLICABLE", '123456789012', 'AWS::::Account')]
        assert_successful_evaluation(self, lambda_result, expected_response, len(lambda_result))

class InvalidParameter(unittest.TestCase):
    def test_scenario_2_invalid_parameter(self):
        list_repositories_result = {"repositories": []}

        ECR_CLIENT_MOCK.describe_repositories = MagicMock(return_value=list_repositories_result)
        rule_parameters = '{\"Parameter\":\"Value\"}'
        lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(rule_parameters), {})
        expected_error_code = 'InvalidParameterValueException'
        expected_error_message = 'This rule is not configured to take any input parameters.'
        assert_customer_error_response(self, lambda_result, expected_error_code, expected_error_message)

class NonComplianceTest(unittest.TestCase):
    def test_scenario_3_compliant_resources_with_key(self):
        list_repositories_result = {"repositories":
            [
                {
                    "repositoryArn": "arn:aws:sns:us-east-1:123456789012:testRepository",
                    "imageScanningConfiguration": {"scanOnPush": False}
                }
            ]
        }

        ECR_CLIENT_MOCK.describe_repositories = MagicMock(return_value=list_repositories_result)
        rule_parameters = '{}'
        lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(rule_parameters), {})
        expected_response = [build_expected_response(
            'NON_COMPLIANT',
            'arn:aws:sns:us-east-1:123456789012:testRepository',
            annotation="The Amazon Elastic Container Registry repository is not configured to scan images on push."
        )]
        assert_successful_evaluation(self, lambda_result, expected_response, len(lambda_result))

class ComplianceTest(unittest.TestCase):
    def test_scenario_4_compliant_resources_with_key(self):
        list_repositories_result = {"repositories":
            [
                {
                    "repositoryArn": "arn:aws:sns:us-east-1:123456789012:testRepository",
                    "imageScanningConfiguration": {"scanOnPush": True}
                }
            ]
        }

        ECR_CLIENT_MOCK.describe_repositories = MagicMock(return_value=list_repositories_result)
        rule_parameters = '{}'
        lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(rule_parameters), {})
        expected_response = [build_expected_response(
            'COMPLIANT',
            'arn:aws:sns:us-east-1:123456789012:testRepository'
        )]
        assert_successful_evaluation(self, lambda_result, expected_response, len(lambda_result))

####################
# Helper Functions #
####################

def build_lambda_configurationchange_event(invoking_event, rule_parameters=None):
    event_to_return = {
        'configRuleName':'myrule',
        'executionRoleArn':'roleArn',
        'eventLeftScope': False,
        'invokingEvent': invoking_event,
        'accountId': '123456789012',
        'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',
        'resultToken':'token'
    }
    if rule_parameters:
        event_to_return['ruleParameters'] = rule_parameters
    return event_to_return

def build_lambda_scheduled_event(rule_parameters=None):
    invoking_event = '{"messageType":"ScheduledNotification","notificationCreationTime":"2017-12-23T22:11:18.158Z"}'
    event_to_return = {
        'configRuleName':'myrule',
        'executionRoleArn':'roleArn',
        'eventLeftScope': False,
        'invokingEvent': invoking_event,
        'accountId': '123456789012',
        'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',
        'resultToken':'token'
    }
    if rule_parameters:
        event_to_return['ruleParameters'] = rule_parameters
    return event_to_return

def build_expected_response(compliance_type, compliance_resource_id, compliance_resource_type=DEFAULT_RESOURCE_TYPE, annotation=None):
    if not annotation:
        return {
            'ComplianceType': compliance_type,
            'ComplianceResourceId': compliance_resource_id,
            'ComplianceResourceType': compliance_resource_type
            }
    return {
        'ComplianceType': compliance_type,
        'ComplianceResourceId': compliance_resource_id,
        'ComplianceResourceType': compliance_resource_type,
        'Annotation': annotation
        }

def assert_successful_evaluation(test_class, response, resp_expected, evaluations_count=1):
    if isinstance(response, dict):
        test_class.assertEquals(resp_expected['ComplianceResourceType'], response['ComplianceResourceType'])
        test_class.assertEquals(resp_expected['ComplianceResourceId'], response['ComplianceResourceId'])
        test_class.assertEquals(resp_expected['ComplianceType'], response['ComplianceType'])
        test_class.assertTrue(response['OrderingTimestamp'])
        if 'Annotation' in resp_expected or 'Annotation' in response:
            test_class.assertEquals(resp_expected['Annotation'], response['Annotation'])
    elif isinstance(response, list):
        test_class.assertEquals(evaluations_count, len(response))
        for i, response_expected in enumerate(resp_expected):
            test_class.assertEquals(response_expected['ComplianceResourceType'], response[i]['ComplianceResourceType'])
            test_class.assertEquals(response_expected['ComplianceResourceId'], response[i]['ComplianceResourceId'])
            test_class.assertEquals(response_expected['ComplianceType'], response[i]['ComplianceType'])
            test_class.assertTrue(response[i]['OrderingTimestamp'])
            if 'Annotation' in response_expected or 'Annotation' in response[i]:
                test_class.assertEquals(response_expected['Annotation'], response[i]['Annotation'])

def assert_customer_error_response(test_class, response, customer_error_code=None, customer_error_message=None):
    if customer_error_code:
        test_class.assertEqual(customer_error_code, response['customerErrorCode'])
    if customer_error_message:
        test_class.assertEqual(customer_error_message, response['customerErrorMessage'])
    test_class.assertTrue(response['customerErrorCode'])
    test_class.assertTrue(response['customerErrorMessage'])
    if "internalErrorMessage" in response:
        test_class.assertTrue(response['internalErrorMessage'])
    if "internalErrorDetails" in response:
        test_class.assertTrue(response['internalErrorDetails'])

def sts_mock():
    assume_role_response = {
        "Credentials": {
            "AccessKeyId": "string",
            "SecretAccessKey": "string",
            "SessionToken": "string"}}
    STS_CLIENT_MOCK.reset_mock(return_value=True)
    STS_CLIENT_MOCK.assume_role = MagicMock(return_value=assume_role_response)

##################
# Common Testing #
##################

class TestStsErrors(unittest.TestCase):

    def test_sts_unknown_error(self):
        RULE.ASSUME_ROLE_MODE = True
        RULE.evaluate_parameters = MagicMock(return_value=True)
        STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(
            {'Error': {'Code': 'unknown-code', 'Message': 'unknown-message'}}, 'operation'))
        response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})
        assert_customer_error_response(
            self, response, 'InternalError', 'InternalError')

    def test_sts_access_denied(self):
        RULE.ASSUME_ROLE_MODE = True
        RULE.evaluate_parameters = MagicMock(return_value=True)
        STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(
            {'Error': {'Code': 'AccessDenied', 'Message': 'access-denied'}}, 'operation'))
        response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})
        assert_customer_error_response(
            self, response, 'AccessDenied', 'AWS Config does not have permission to assume the IAM role.')


#Super  and Overriding in classes:
class A:
    classvar1 = "I am a Class Variable in class A" #Class Variable
    def __init__(self):
        self.var1="I am inside Class A's Constructor "
        self.classvar1="Instance Var in Class A" #Instance Variable
        self.special="Special,"

class B(A):
    classvar1="I am a CLass Variable in Class B"
    def __init__(self):
        super().__init__() #Ye phele call hoga fir class ke speical,var1 or classvar1 ko access karega fir niche aayega or class A ke members
        # ko override karega and then fir class B ke var1 or classvar1 ko karega print.
        self.var1 = "I am inside Class B's Constructor"
        self.classvar1 = "Instance Var in Class B"
        # super().__init__()
        # print(super().classvar1)

a = A()
b = B()
print(b.special,b.var1,b.classvar1)

#Agar print(b.classvar1) se me print karau toh vo sabse phele class B me jake search karega ki koi instance variable hai, if hota hai toh
# print kare dega and if nahi hota hai toh class A me jake search karega, if waha bhi nahi hota toh fir class variable ko search karega Class B
# and Class B me agar class variable bhi na mile toh vo fir class A me jake class variable ko search karega or print kar dega.

'''
As you people might have noticed that we came across super and overriding keywords, a lot of time in a few of our previous tutorials,
but did not get into its detailed working. The reason for that was to give you an idea of concepts leading to the use of super() and
overriding first. In this tutorial, we are going to discuss it in detail, using the single inheritance as an example.

Yet being different concepts, they are often used together. The need for superclass arises when overriding is being done at a certain point
in our code. Overriding is an essential part of object-oriented programming since it makes the inheritance utilize its full power.
Overriding avoids duplication of code, and at the same time enhance or customize the part of it. It is a part of the inheritance mechanism.
Let us get a description of overriding first so that we can dive into the concept of super() later.

How to override class methods in Python?
Overriding occurs when a derived class or child class has the same method that has already been defined in the base or parent class.
Being the same methods with the same name and number of parameters, when called checks for the method first in a child class, and runs it
ignoring the method in the parent class because it is already overridden. In the case of Instance variables, the case is a little different.
When the method is called, the program will look for any instance variable having the same name as the one that is called in the child,
then in the parent, and after that, it comes again into child class if not found.

Where does super() fit in all this?

When we want to call an already overridden method, then the use of super function comes in. It is a built-in function, so no requirement
of any module import statement. What super does is, it allows us the use of the method of our superclass, that in the case of inheritance
is the parent class. Syntax of using super() is:

class Parent_Class(object):
      def __init__(self):
            pass

class Child_Class(Parent_Class):
     def __init__(self):
           super().__init__()

super() returns a temporary object of the superclass that then allows you to call that superclass’s methods. The primary use case of super()
is to extend the functionality of the inherited method.

We have discussed earlier that in case of method overriding, the previous method could not be called, but super makes an exception, and
thus we can partially or completely use the method of the parent class too. We can even use super() to call only a specific variable we used
in our overridden method. Calling the superclass built methods with super() saves us from rewriting those methods in our subclass, and
allows us to swap out superclasses with minimal code changes.

'''


## Download videos and music from youtube !!
import argparse
import subprocess

## Three diffrent commands
## -d = download single youtube video into mp3 format
## -t = download mutiple songs from a txt file
##youtube-dl --extract-audio --audio-format mp3 <video URL>
##youtube-dl -a video_links.txt

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument("-d", "--download",
						help="Download a youtube video into mp3 format.")
	parser.add_argument("-t", "--txt",
						help="Download from a txt file with urls.")

	args = parser.parse_args()
	if args.download:
		print ("Downloading {}".format(args.download))
		cmd = "youtube-dl --extract-audio --audio-format mp3 " + args.download
		sysoutput = subprocess.call(cmd, shell=True)
	elif args.txt:
		print("Downloading from {}".format(args.txt))
		cm = "youtube-dl --extract-audio --audio-format mp3 -a " + args.txt
		sysoutput = subprocess.call(cm, shell=True)
	else:
		print ("Something went wrong..")

if __name__== "__main__":
  main()

#Links sources
#https://docs.python.org/3/howto/argparse.html
#https://www.journaldev.com/16140/python-system-command-os-subprocess-call#python-ossystem-function
#https://www.slashgeek.net/2016/06/24/5-youtube-dl-tips-might-not-know/


from PIL import Image, ImageDraw, ImageFont
from utils import load_config, trim
from functools import lru_cache

import datetime
import json

class PlantCard:
  """Represent plant objects as PIL.Image instances, calculate
  and return rendered images.
  """
  def __init__(self, data):
    self.droplet, self.leaf = PlantCard.__get_base_icons()
    self.data = data

  @staticmethod
  @lru_cache(maxsize=None)
  def __get_config():
    return load_config()

  @staticmethod
  @lru_cache(maxsize=None)
  def __get_base_font(size=30):
    return ImageFont.truetype('fonts/SourceSansPro-Bold.ttf', size)

  @staticmethod
  @lru_cache(maxsize=None)
  def __get_base_icons():
    droplet = Image.open("images/droplet.png")
    droplet.thumbnail((100, 20), Image.ANTIALIAS)

    leaf = Image.open("images/leaf.png")
    leaf.thumbnail((100, 20), Image.ANTIALIAS)

    return (droplet, leaf)

  @staticmethod
  #@lru_cache(maxsize=None)
  def __trim(image):
    return trim(image)

  def generate_fertilizer_cycle(self):
    config = PlantCard.__get_config()
    epoch = config.get("epoch")

    month, day, year = [int(x) for x in epoch.split("/")]
    epoch = datetime.date(year, month, day)
    todays_date = datetime.date.today()

    delta = (todays_date - epoch).days
    cycle = int(self.data.get("fertilizer_cycle"))
    days_until_fertilize = cycle - (delta % cycle)

    canvas = Image.new('1', (350, 20))
    canvas.paste(self.leaf, (0, 0))

    draw_context = ImageDraw.Draw(canvas)
    draw_context.text((25, -10), str(days_until_fertilize), font=PlantCard.__get_base_font(), fill=255)

    return PlantCard.__trim(canvas)

  def generate_water_cycle(self):
    config = PlantCard.__get_config()
    epoch = config.get("epoch")

    month, day, year = [int(x) for x in epoch.split("/")]
    epoch = datetime.date(year, month, day)
    todays_date = datetime.date.today()

    delta = (todays_date - epoch).days
    cycle = int(self.data.get("water_cycle"))
    days_until_water = cycle - (delta % cycle)

    canvas = Image.new('1', (350, 20))
    canvas.paste(self.droplet, (0, 0))

    draw_context = ImageDraw.Draw(canvas)
    draw_context.text((25, -10), str(days_until_water), font=PlantCard.__get_base_font(), fill=255)

    return PlantCard.__trim(canvas)

  # Cache for 30 minutes in the future
  def generate_image(self, font):
    base_card = Image.new('1', (170, 250))

    ## Generate days until next watering, days until next fertilizing
    water_date = self.generate_water_cycle()
    fertilize_date = self.generate_fertilizer_cycle()

    ## Calculate fertilizing timer position based on width
    fertilize_x_pos = (base_card.size[0] - fertilize_date.size[0]) - 10

    ## Place watering timer, fertilizer timer
    base_card.paste(water_date, (10, 220))
    base_card.paste(fertilize_date, (fertilize_x_pos, 220))

    ## Center and draw ID
    draw_context = ImageDraw.Draw(base_card)

    id_text_width, id_text_height = draw_context.textsize(self.data.get("ID"), font)
    id_x_pos = (base_card.size[0] / 2) - (id_text_width / 2)

    draw_context.text(xy=(id_x_pos, 25), text=self.data.get("ID"), font=font, fill=255)

    ## Center and draw name
    name_text_width, name_text_height = draw_context.textsize(self.data.get("name"), PlantCard.__get_base_font(15))
    name_x_pos = (base_card.size[0] / 2) - (name_text_width / 2)
    name_y_pos = id_text_height + 10 + 25
    draw_context.text(xy=(name_x_pos, name_y_pos), text=self.data.get("name"), font=PlantCard.__get_base_font(15), fill=255)

    return base_card

  def __repr__(self):
    return "<PlantCard {}.{}>".format(
      self.data.get("ID"),
      self.data.get("name")
    )


from nthp_api.nthp_build import database, schema

def get_history_records() -> list[schema.HistoryRecord]:
    """
    Return the history record collection.
    """
    records_query = database.HistoryRecord.select()
    return [
        schema.HistoryRecord(
            year=record.year,
            year_id=record.academic_year,
            title=record.title,
            description=record.description,
        )
        for record in records_query
    ]


import sys
from io import StringIO
import contextlib
from referee.main import *

sys.argv =  ["referee", "-v 0","ACCESS_GRANTED", "minimax_ab"]

exp_score = 50
t_weight = 100
f_weight = 1
e_weight = 1

def test_score(rounds):
    upper = 0
    lower = 0
    draw = 0
    result = []
    for x in range(0,rounds):
        out = main()
        result.append(out)
        print(out)
        if "upper" in out:
            upper +=1
        elif "lower" in out:
            lower +=1
        else:
            draw += 1
        print("turn: ", x)
        print("Upper win: ", upper)
        print("lower win:", lower)
        print("draw: ", draw)
    print(result)
    print("Upper win: ", upper)
    print("lower win:", lower)
    print("draw: ", draw)
    return upper+0.5*draw

def learn_weight(weight, exp_score):
    hist = 0
    score = 0
    test_weight = weight
    step_size = 10
    increase = True
    while(score < exp_score):
        score = test_score(100)
        if (score<hist):

            if increase:
                weight -= step_size/2
                increase = False
            else:
                weight += step_size/2
                increase = True
        hist = score

test_score(100)


import cv2
import numpy as np
import random

height = 512
width = 512

canvas = np.zeros((height, width, 3), dtype=np.uint8)
origin = [int(width/2), int(height/2)]

# Points for Handles
p0 = np.array([0, -150]) + origin
p1 = np.array([-224, 200]) + origin
p2 = np.array([192, 0]) + origin
p3 = np.array([232, 192]) + origin

# Lerp for handles
def lerp(start, end, dt):
    lerp_list = []
    t = 1
    while t >= 0:
        x = int(start[0] + (end[0] - start[0]) * t)
        y = int(start[1] + (end[1] - start[1]) * t)
        lerp_list.append([x, y])
        t = round(t-dt, 2)
    return lerp_list

# Lerp for spline
def lerp_cont(l1: list, l2: list):
    lerp_list = []
    fraction = []
    for pt in range(len(l1)):
        t = pt/(len(l1)-1)
        x = int(l1[pt][0] + (l2[pt][0] - l1[pt][0]) * t)
        y = int(l1[pt][1] + (l2[pt][1] - l1[pt][1]) * t)
        lerp_list.append([x, y])
        fraction.append(round(t, 2))
    return lerp_list, fraction

# LERP Functions
dt = .02
lp0 = lerp(p0, p1, dt)
lp1 = lerp(p3, p2, dt)
spline, fraction = lerp_cont(lp0, lp1)

# Draw Spline
for i in range(len(lp0)):
    canvas = cv2.line(canvas, lp0[i], lp1[i], (32, 32, 0), 1, lineType=cv2.LINE_AA)
for i in range(len(lp0)):
    canvas = cv2.circle(canvas, spline[i], 2, (255, 255, 0), -1, lineType=cv2.LINE_AA)

# Draw Handles
canvas = cv2.circle(canvas, lp0[0], 2, (255, 255, 0), -1, lineType=cv2.LINE_AA)
canvas = cv2.circle(canvas, lp1[0], 2, (255, 255, 0), -1, lineType=cv2.LINE_AA)
canvas = cv2.circle(canvas, lp0[-1], 2, (255, 255, 0), -1, lineType=cv2.LINE_AA)
canvas = cv2.circle(canvas, lp1[-1], 2, (255, 255, 0), -1, lineType=cv2.LINE_AA)
canvas = cv2.line(canvas, p0, p1, (255, 255, 255), 1, lineType=cv2.LINE_AA)
canvas = cv2.line(canvas, p2, p3, (255, 255, 255), 1, lineType=cv2.LINE_AA)
#cv2.imwrite(f"{i}.png", canvas)
cv2.imshow('Spline', canvas)
cv2.waitKey(32)

cv2.imshow('Spline', canvas)
cv2.waitKey(100000)


import numpy

class Connection:

    def __init__(self, from_node, to_node, weight, enabled, recursive):
        self.from_node = from_node
        self.to_node = to_node
        self.weight = weight
        self.id_tuple = (from_node.id, to_node.id)
        self.enabled = enabled
        self.recursive = recursive
        if not recursive:
            self.to_node.incoming_signals += 1

    def transmit(self, value):
        if not self.enabled:
            return
        if self.recursive:
            self.to_node.input_value += value
        else:
            self.to_node.set_value(value * self.weight)


class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        l,r = 0, len(colors) - 1
        res = 1

        while l < r:
            if not colors[l] == colors[r]: # Different colored house
                res = max(res,r - l) # Save distance between two houses
                l += 1               # Increment left pointer
                r = len(colors) - 1  # Reset right pointer to end of list
            else: # House color same
                r -= 1               # Check by decrementing right pointer

        return res        # Return res

Solutions/Easy/2078 two furthest houses with different colors.py


""" rotate.py
    demonstrate rotating a sprite
    draw bounding rectangle to illustrate
    sprite size change
"""

import pygame
pygame.init()

class Ship(pygame.sprite.Sprite):
    def __init__(self, screen):
        self.screen = screen
        pygame.sprite.Sprite.__init__(self)
        self.imageMaster = pygame.image.load("ship.bmp")
        self.imageMaster = self.imageMaster.convert()
        self.image = self.imageMaster
        self.rect = self.image.get_rect()
        self.rect.center = (320, 240)
        self.dir = 0

    def update(self):
        oldCenter = self.rect.center
        self.image = pygame.transform.rotate(self.imageMaster, self.dir)
        self.rect = self.image.get_rect()
        self.rect.center = oldCenter

    def turnLeft(self):
        self.dir += 45
        if self.dir > 360:
            self.dir = 45

    def turnRight(self):
        self.dir -= 45
        if self.dir < 0:
            self.dir = 315

def main():
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("Show sprite bounding box")

    background = pygame.Surface(screen.get_size())
    background.fill((0, 0, 0))

    ship = Ship(background)
    allSprites = pygame.sprite.Group(ship)

    clock = pygame.time.Clock()
    keepGoing = True
    while keepGoing:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    ship.turnLeft()
                elif event.key == pygame.K_RIGHT:
                    ship.turnRight()

        #do an old-fashioned background blit
        screen.blit(background, (0, 0))

        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)

        #draw a rect on the screen
        pygame.draw.rect(screen, (255, 255, 255), ship.rect, 3)

        pygame.display.flip()

if __name__ == "__main__":
    main()


#!/usr/bin/python3
"""
add_attribute function

Adds a new attribute to an object if the object
allows dynamic attribute creation.

"""

def add_attribute(obj, attribute, value):
    """
    Args:
        obj (object): The object to which the attribute will be added.
        attribute (str): The name of the attribute to be added.
        value: The value to be assigned to the new attribute.

    Raises:
        TypeError: If the object does not allow dynamic attribute creation,
        either by having no '__dict__' attribute or having '__slots__'.
    """
    if '__dict__' not in dir(obj):
        raise TypeError("can't add new attribute")
    if '__slots__' in dir(obj):
        raise TypeError("can't add new attribute")
    else:
        setattr(obj, attribute, value)


from django.shortcuts import render
from forms import UserProfileForm
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.models import User
# Create your views here.

@login_required
def edit_profile(request):
    if request.method=='POST':
        form=UserProfileForm(request.POST, request.FILES,instance=request.user.profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/profile/'+str(request.user.id)+'/')
        else:
            args={}
            args.update(csrf(request))
            args['form']=form
            return render(request,'userprofile/edit_profile.html',args)
    user=request.user
    profile=user.profile
    args={}
    args.update(csrf(request))
    args['form']=UserProfileForm(instance=profile)
    return render(request,'userprofile/edit_profile.html',args)

def profile(request,user_id):
    user=User.objects.get(id=user_id)
    args={}
    args['user']=user
    return render(request,'userprofile/profile.html',args)