"""
Due to uncertainty about how to best structure things and the size of the app,
the models and views were split into multiple individual files instead of
the traditional models.py and views.py files.

This file contains the front page view, plus utilities for working with
requests, responses and errors.
"""

import hashlib
from random import random

from urllib import quote
from django.conf import settings
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils.safestring import mark_safe

from apps.gcd.views.pagination import DiggPaginator

from apps.stddata.models import Language
from apps.stats.models import CountStats
from apps.indexer.models import Error

ORDER_ALPHA = "alpha"
ORDER_CHRONO = "chrono"

def index(request):
    """Generates the front index page."""

    stats = CountStats.objects.filter(language__isnull=True,
                                      country__isnull=True)
    language = None
    stats_for_language = []

    # We only want to show English-specific anything if English was
    # explicitly passed in the URL.  Otherwise we use the English-language
    # page but without anything specific to only the English contents of
    # the database.
    code = request.LANGUAGE_CODE
    if code and (code != 'en' or request.GET.get('lang') == 'en'):
        try:
            language = Language.objects.get(code=code)
            stats_for_language = CountStats.objects.filter(language=language)
        except Language.DoesNotExist:
            pass

    if (not code) or code not in settings.FRONT_PAGE_LANGUAGES:
        # Make certain that we pick an actual existing page, but
        # leave the language stats matching what was requested.
        code = 'en'
    base_path = 'managed_content/gcd/%s/' % code

    template_vars = {}
    for template in ('front_page_title', 'front_page_main', 'front_page_lower',
                     'fb_feed'):
        template_vars[template] = '%s/%s.html' % (base_path, template)

    template_vars.update({
        'stats': stats,
        'language': language,
        'stats_for_language': stats_for_language,
        'CALENDAR': settings.CALENDAR,
    })
    return render_to_response('gcd/index.html', template_vars,
                              context_instance=RequestContext(request))

class ResponsePaginator(object):
    """
    Uses DiggPaginator from
    http://bitbucket.org/miracle2k/djutils/src/tip/djutils/pagination.py.
    We could reconsider writing our own code.
    """
    def __init__(self, queryset, vars=None, template=None, per_page=100,
                 callback_key=None, callback=None, view=None):
        """
        Either template or view should be set
        """
        if template is None and view is None:
            raise ValueError
        self.template = template
        self.vars = vars and vars or {}
        self.callback_key = callback_key
        self.callback = callback
        self.view = view
        self.p = DiggPaginator(queryset, per_page, body=7, padding=2, tail=1)

    def paginate(self, request):
        page_num = 1
        self.vars['pagination_type'] = 'num'
        redirect = None
        if ('page' in request.GET):
            try:
                page_num = int(request.GET['page'])
                if page_num > self.p.num_pages:
                    redirect = self.p.num_pages
                elif page_num < 1:
                    redirect = 1
            except ValueError:
                if 'alpha_paginator' in self.vars and \
                  request.GET['page'][:2] == 'a_':
                    self.alpha_paginator = self.vars['alpha_paginator']
                    try:
                        alpha_page_num = int(request.GET['page'][2:])
                        if alpha_page_num > self.alpha_paginator.num_pages:
                            redirect = 'a_%d' % self.alpha_paginator.num_pages
                        elif page_num < 1:
                            redirect = 'a_1'
                        else:
                            alpha_page = \
                              self.alpha_paginator.page(alpha_page_num)
                            self.vars['pagination_type'] = 'alpha'
                            self.vars['alpha_page'] = alpha_page
                            issue_count = self.alpha_paginator.number_offset
                            for i in range(1,alpha_page_num):
                                issue_count += \
                                  self.alpha_paginator.page(i).count
                            page_num = int(issue_count/self.p.per_page) + 1
                    except ValueError:
                        redirect = 1
                else:
                    redirect = 1

        if redirect is not None:
            args = request.GET.copy()
            args['page'] = redirect
            return HttpResponseRedirect(quote(request.path.encode('UTF-8')) +
                                        u'?' + args.urlencode())

        page = self.p.page(page_num)
        self.vars['items'] = page.object_list
        self.vars['paginator'] = self.p
        self.vars['page'] = page
        self.vars['page_number'] = page_num

        if self.callback_key is not None:
            self.vars[self.callback_key] = self.callback(page)

        if self.view:
            return self.view()

        return render_to_response(self.template, self.vars,
                                  context_instance=RequestContext(request))

def paginate_response(request, queryset, template, vars, per_page=100,
                      callback_key=None, callback=None):
    return ResponsePaginator(queryset, vars=vars, template=template,
                             per_page=per_page,
                             callback_key=callback_key,
                             callback=callback).paginate(request)


import time

time.time()

objective = int(input("Enter a Number, which may have a square root:  "))
result = 0

while (result ** 2) < objective:
    result += 1

if (result ** 2) == objective:
    print(f"The Square root of the number {objective} is: {result}")
else:
    print(f"There isn't a exact square root of the number {objective}")

print(f"This Program took {time.time()} seconds")


from sensel import sensel

FRAMERATE = 2000
SCAN_DETAILS = ["High (125Hz)", "Medium (250Hz)", "Low (1000Hz)"]

class SenselException(Exception):
    def __init__(self, message):
        self.message = message

class Morph():
    def __init__(self):
        self.handle = None
        (error, self.device_list) = sensel.getDeviceList()
        if self.device_list.num_devices != 0:
            (error, self.handle) = sensel.openDeviceByID(
                self.device_list.devices[0].idx)
        if self.handle is None:
            raise SenselException(f"Sensel Error: {error}")
        else:
            (error, self.info) = sensel.getSensorInfo(self.handle)
            print(
                f"Device {bytearray(self.device_list.devices[0].serial_num).decode('utf-8')} Found"
            )
            error = sensel.setDynamicBaselineEnabled(self.handle, 0)
            print(f"setDynamicBaselineEnabled False: {error}")
            error, detail = sensel.getScanDetail(self.handle)
            print(f"Scan Detail: {SCAN_DETAILS[detail]}")
            error = sensel.setMaxFrameRate(self.handle, FRAMERATE)
            print(f"setMaxFramerate {FRAMERATE}: {error}")
            error, framerate = sensel.getMaxFrameRate(self.handle)
            print(f"Max Framerate: {framerate}")
            print("Width: " + str(self.info.width) + "mm")
            print("Height: " + str(self.info.height) + "mm")
            self.cols = self.info.num_cols
            self.rows = self.info.num_rows
            print("Cols: " + str(self.cols))
            print("Rows: " + str(self.rows))
            error = sensel.setFrameContent(self.handle,
                                           sensel.FRAME_CONTENT_CONTACTS_MASK)
            print(f"setFrameContent {error}")
            (error, self.frame) = sensel.allocateFrameData(self.handle)
            print(f"allocateFrameData {error}")
            error = sensel.startScanning(self.handle)
            print(f"startScanning {error}")

    def read_frames(self, print=False):
        error = sensel.readSensor(self.handle)
        (error, num_frames) = sensel.getNumAvailableFrames(self.handle)
        frames = []
        for i in range(num_frames):
            error = sensel.getFrame(self.handle, self.frame)
            frames.append(self.frame)
            if print:
                self.print_frames()
        return frames

    def print_frames(self):
        if self.frame.n_contacts > 0:
            print("\nNum Contacts: ", self.frame.n_contacts)
            for n in range(self.frame.n_contacts):
                c = self.frame.contacts[n]
                print("Contact ID: ", c.id)
                if c.state == sensel.CONTACT_START:
                    sensel.setLEDBrightness(self.handle, c.id, 100)
                elif c.state == sensel.CONTACT_END:
                    sensel.setLEDBrightness(self.handle, c.id, 0)

    def close(self):
        error = sensel.freeFrameData(self.handle, self.frame)
        error = sensel.stopScanning(self.handle)
        error = sensel.close(self.handle)


roman = ['M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I']
num = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

rom_to_num = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
num_to_rom = {1:"I", 5:"V", 10:"X", 50:"L", 100:"C", 500:"D", 1000:"M"}

def num_to_roman(n):
	result = []
	for i in range(len(roman)):
		count = int(n / num[i])
		result.append(roman[i] * count)
		n -= num[i] * count

	r = "".join(result)
	return r

def roman_to_num(r):
	count = 0
	for i in range(len(r)):
		try:
			if(rom_to_num[r[i+1]] > rom_to_num[r[i]]):
				count -= rom_to_num[r[i]]
			else:
				count += rom_to_num[r[i]]

		except:
			count += rom_to_num[r[i]]
	return count

import random

for i in range(1,3999):
	x = num_to_roman(i)
	if(i != roman_to_num(x)):
		print("WOOPS {} {}".format(x, i))

with open("roman_numerals.txt", "w") as file:
	count = 0
	for i in range(100):
		x = random.randint(1,3999)
		count += x
		s = num_to_roman(x)
		file.write(s + ",")

	print(count)


# https://ithelp.ithome.com.tw/articles/10194003
import pandas as pd
import numpy as np

seriesObj = pd.Series(range(10), index=['a', 'a', 'b', 'b', 'b','c','c','c','c','c'])
# print(seriesObj['c'])

df = pd.DataFrame(np.random.randn(4, 2), index=['a', 'a', 'b', 'b'])
# print(df.ix['b'])

titanic = pd.read_csv('./train.csv')
# print(titanic)
fliter = (titanic['Sex'] == 'male')
# titanic[fliter]
print(titanic[fliter])


import sqlalchemy as _sql
from application import db as _db

class Attendance(_db.Model):
    """
    Composite Keys: StudentId + TimeSlotId + Day:
    Once the combination is added then next value cannot be added with the same combination, neither can this combination
    be updated.
    """
    __tablename__ = 'Attendance'
    Id = _sql.Column(_sql.Integer, primary_key=True, autoincrement=True)
    StudentId = _sql.Column(_sql.Integer, _sql.ForeignKey('Student.Id'), nullable=False)
    TimeSlotId = _sql.Column(_sql.Integer, _sql.ForeignKey('TimeSlot.Id'), nullable=False)
    Day = _sql.Column(_sql.Date, nullable=False)
    Timestamp = _sql.Column(_sql.DateTime(timezone=True), index=True, default=_sql.func.now())


# sarah kingan
# CSC162
# summer 2015
# LAB08
#
# Write a recursive function to compute the Fibonacci
# sequence. How does the performance of the recursive
# function compare to that of an iterative version?
#
# http://www.codeskulptor.org/#user40_a09EvnV82b_3.py
#
#
#
import time

def FibRec(n):
    if n <= 2: return 1
    return FibRec(n-1) + FibRec(n-2)

def FibIt(n):
    fibTable = [0,1]
    for i in range(2,n+1):
        fibTable.append(fibTable[i-1] + fibTable[i-2])
    return fibTable[n]

def timeIt(function,n):
    start = time.time()
    function(n)
    end = time.time()
    return end - start

def main():
    print("\t".join(["n","Recursion","Iteration"]))
    for n in range(10,30,2):
        recTime = timeIt(FibRec,n)
        itTime = timeIt(FibIt,n)
        print ("\t".join([str(n),str(recTime),str(itTime)]))

main()


# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from scipy import stats
import os
import importlib
import DeepNetPI
import DataGen
import utils
os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # avoids a warning

importlib.reload(DeepNetPI)
importlib.reload(DataGen)
importlib.reload(utils)

from DataGen import DataGenerator
from DeepNetPI import TfNetwork
from utils import *
import numpy as np
import tensorflow as tf
import datetime

start_time = datetime.datetime.now()

# inputs
type_in = 'x_cubed_gap' 	# data type to use - drunk_bow_tie x_cubed_gap ~boston concrete
loss_type = 'qd_soft' 		# loss type to train on - qd_soft mve mse (mse=simple point prediction)
n_samples = 100		# if generating data, how many points to generate
h_size = [50]	# number of hidden units in network: [50]=layer_1 of 50, [8,4]=layer_1 of 8, layer_2 of 4
alpha = 0.05		# data points captured = (1 - alpha)
n_epoch = 3000		# number epochs to train for
optim = 'adam' 		# opitimiser - SGD adam
l_rate = 0.02		# learning rate of optimiser
decay_rate=0.95		# learning rate decay
soften = 160. 		# hyper param for QD_soft
lambda_in = 15. 	# hyper param for QD_soft
sigma_in=0.4 		# initialise std dev of NN weights
is_run_test=False	# if averaging over lots of runs - turns off some prints and graphs
n_ensemble=5		# number of individual NNs in ensemble
n_bootstraps=1 		# how many boostrap resamples to perform
n_runs=20 if is_run_test else 1
is_batch=True 		# train in batches?
n_batch=100 		# batch size
lube_perc=90. 		# if model uncertainty method = perc - 50 to 100
perc_or_norm='norm' # model uncertainty method - perc norm (paper uses norm)
is_early_stop=False # stop training early (didn't use in paper)
is_bootstrap=False if n_bootstraps == 1 else True
train_prop=0.9 		# % of data to use as training

out_biases=[3.,-3.] # chose biases for output layer (for mve is overwritten to 0,1)
activation='relu' 	# NN activation fns - tanh relu

# plotting options
is_use_val=True
save_graphs=False
show_graphs=False if is_run_test else True
show_train=False if is_run_test else True
is_y_rescale=False
is_y_sort=False
is_print_info=True
var_plot=0 # lets us plot against different variables, use 0 for univariate
is_err_bars=True
is_norm_plot=False
is_boundary=True # boundary stuff ONLY works for univariate - turn off for larger
is_bound_val=False # plot validation points for boundary
is_bound_train=True # plot training points for boundary
is_bound_indiv=True # plot individual boundary estimates
is_bound_ideal=True # plot ideal boundary
is_title=True # show title w metrics on graph
bound_limit=6. # how far to plot boundary

# resampling
bootstrap_method='replace_resample' # whether to boostrap or jacknife - prop_of_data replace_resample
prop_select=0.8 # if jacknife (=prop_of_data), how much data to use each time

# other
in_ddof=1 if n_runs > 1 else 0 # this is for results over runs only

# pre calcs
if alpha == 0.05:
	n_std_devs = 1.96
elif alpha == 0.10:
	n_std_devs = 1.645
elif alpha == 0.01:
	n_std_devs = 2.575
else:
	raise Exception('ERROR unusual alpha')

results_runs = []
run=0
for run in range(0,n_runs):
	# generate data
	Gen = DataGenerator(type_in=type_in)
	X_train, y_train, X_val, y_val = Gen.CreateData(n_samples=n_samples,seed_in=run,
		train_prop=train_prop, bound_limit=bound_limit, n_std_devs=n_std_devs)

	# print('\n--- view data ---')
	# Gen.ViewData(n_rows=5, hist=False, plot=False)

	X_boundary = []
	y_boundary = []
	y_pred_all = []
	X_train_orig, y_train_orig = X_train, y_train
	for b in range(0,n_bootstraps):

		# bootstrap sample
		if is_bootstrap:

			np.random.seed(b)
			if bootstrap_method=='replace_resample':
				# resample w replacement method
				id = np.random.choice(X_train_orig.shape[0], X_train_orig.shape[0], replace=True)
				X_train = X_train_orig[id]
				y_train = y_train_orig[id]

			elif bootstrap_method=='prop_of_data':
				# select x% of data each time NO resampling
				perm = np.random.permutation(X_train_orig.shape[0])
				X_train = X_train_orig[perm[:int(perm.shape[0]*prop_select)]]
				y_train = y_train_orig[perm[:int(perm.shape[0]*prop_select)]]

		i=0
		while i < n_ensemble:
			is_failed_run = False

			tf.reset_default_graph()
			sess = tf.Session()

			# info
			if is_print_info:
				print('\nrun number', run+1, ' of ', n_runs,
					' -- bootstrap number', b+1, ' of ', n_bootstraps,
					' -- ensemble number', i+1, ' of ', n_ensemble)

			# load network
			NN = TfNetwork(x_size=X_train.shape[1], y_size=2, h_size=h_size,
				type_in="pred_intervals", alpha=alpha, loss_type=loss_type,
				soften=soften, lambda_in=lambda_in, sigma_in=sigma_in, activation=activation, bias_rand=False, out_biases=out_biases)

			# train
			NN.train(sess, X_train, y_train, X_val, y_val,
				n_epoch=n_epoch, l_rate=l_rate, decay_rate=decay_rate,
				resume_train=False, print_params=False, is_early_stop=is_early_stop,
				is_use_val=is_use_val, optim=optim, is_batch=is_batch, n_batch=n_batch,
				is_run_test=is_run_test,is_print_info=is_print_info)

			# visualise training
			if show_train:
				NN.vis_train(save_graphs, is_use_val)

			# make predictions
			y_loss, y_pred, y_metric, y_U_cap, y_U_prop, \
				y_L_cap, y_L_prop, y_all_cap, y_all_prop \
				= NN.predict(sess, X=X_val,y=y_val,in_sess=True)

			# check whether the run failed or not
			if np.abs(y_loss) > 20.:
			# if False:
				is_failed_run = True
				print('\n\n### one messed up! repeating ensemble ###')
				continue # without saving!
			else:
				i+=1 # continue to next

			# save prediction
			y_pred_all.append(y_pred)

			# predicting for boundary, need to do this for each model
			if is_boundary:
				X_boundary.append(np.linspace(start=-bound_limit,stop=bound_limit, num=500)[:,np.newaxis])
				t, y_boundary_temp, t, t, t, t, t, t, t = NN.predict(sess, X=X_boundary[i-1],
					y=np.zeros_like(X_boundary[i-1]),in_sess=True)
				y_boundary.append(y_boundary_temp)

			sess.close()

	# we may have predicted with gauss_like or qd_soft, here we need to get estimates for
	# upper/lower pi's AND gaussian params no matter which method we used (so can compare)
	y_pred_all = np.array(y_pred_all)

	if loss_type == 'qd_soft':
		y_pred_gauss_mid, y_pred_gauss_dev, y_pred_U, \
			y_pred_L = pi_to_gauss(y_pred_all, lube_perc, perc_or_norm, n_std_devs)

	elif loss_type == 'gauss_like': # work out bounds given mu sigma
		y_pred_gauss_mid_all = y_pred_all[:,:,0]
		# occasionally may get -ves for std dev so need to do max
		y_pred_gauss_dev_all = np.sqrt(np.maximum(np.log(1.+np.exp(y_pred_all[:,:,1])),10e-6))
		y_pred_gauss_mid, y_pred_gauss_dev, y_pred_U, \
			y_pred_L = gauss_to_pi(y_pred_gauss_mid_all, y_pred_gauss_dev_all, n_std_devs)

	elif loss_type == 'mse': # as for gauss_like but we don't know std dev so guess
		y_pred_gauss_mid_all = y_pred_all[:,:,0]
		y_pred_gauss_dev_all = np.zeros_like(y_pred_gauss_mid_all)+0.01
		y_pred_gauss_mid, y_pred_gauss_dev, y_pred_U, \
			y_pred_L = gauss_to_pi(y_pred_gauss_mid_all, y_pred_gauss_dev_all, n_std_devs)

	# work out metrics
	y_U_cap = y_pred_U > y_val.reshape(-1)
	y_L_cap = y_pred_L < y_val.reshape(-1)
	y_all_cap = y_U_cap*y_L_cap
	PICP = np.sum(y_all_cap)/y_L_cap.shape[0]
	MPIW = np.mean(y_pred_U - y_pred_L)
	y_pred_mid = np.mean((y_pred_U,y_pred_L),axis=0)
	MSE = np.mean(np.square(Gen.scale_c*(y_pred_mid - y_val[:,0])))
	RMSE = np.sqrt(MSE)
	CWC = np_QD_loss(y_val, y_pred_L, y_pred_U, alpha, soften, lambda_in)
	neg_log_like = gauss_neg_log_like(y_val, y_pred_gauss_mid, y_pred_gauss_dev, Gen.scale_c)
	residuals = residuals = y_pred_mid - y_val[:,0]
	shapiro_W, shapiro_p = stats.shapiro(residuals[:])
	results_runs.append((PICP, MPIW, CWC, RMSE, neg_log_like, shapiro_W, shapiro_p))

	# concatenate for graphs
	title = 'PICP=' + str(round(PICP,3))\
				+ ', MPIW=' + str(round(MPIW,3)) \
				+ ', qd_loss=' + str(round(CWC,3)) \
				+ ', NLL=' + str(round(neg_log_like,3)) \
				+ ', alpha=' + str(alpha) \
				+ ', loss=' + NN.loss_type \
				+ ', data=' + type_in + ',' \
				+ '\nh_size=' + str(NN.h_size) \
				+ ', bstraps=' + str(n_bootstraps) \
				+ ', ensemb=' + str(n_ensemble) \
				+ ', RMSE=' + str(round(RMSE,3)) \
				+ ', soft=' + str(NN.soften) \
				+ ', lambda=' + str(NN.lambda_in)

	# visualise
	if show_graphs:
		# error bars
		if is_err_bars:
			plot_err_bars(X_val, y_val, y_pred_U, y_pred_L,
				is_y_sort, is_y_rescale, Gen.scale_c, save_graphs,
				title, var_plot, is_title)

		# visualise boundary
		if is_boundary:
			y_bound_all=np.array(y_boundary)
			plot_boundary(y_bound_all, X_boundary, y_val, X_val,
				y_train, X_train, loss_type,
				Gen.y_ideal_U, Gen.y_ideal_L, Gen.X_ideal, Gen.y_ideal_mean, is_bound_ideal,
				is_y_rescale, Gen.scale_c, save_graphs,
				in_ddof, perc_or_norm, lube_perc, n_std_devs,
				is_bound_val, is_bound_train, is_bound_indiv,
				title, var_plot, is_title)

		# normal dist stuff
		if is_norm_plot:
			title = 'shapiro_W=' + str(round(shapiro_W,3)) + \
				', data=' + type_in +', loss=' + NN.loss_type + \
				', n_val=' + str(y_val.shape[0])
			fig, (ax1,ax2) = plt.subplots(2)
			ax1.set_xlabel('y_pred - y_val') # histogram
			ax1.hist(residuals,bins=30)
			ax1.set_title(title, fontsize=10)
			stats.probplot(residuals[:], plot=ax2) # QQ plot
			ax2.set_title('')
			fig.show()

# sumarise results, print for paste to excel
print('\n\nn_samples, h_size, n_epoch, l_rate, decay_rate, soften, lambda_in, sigma_in')
print(n_samples, h_size, n_epoch, l_rate, decay_rate, soften, lambda_in, sigma_in)
print('\n\ndata=',type_in, 'loss_type=',loss_type)
results_runs = np.array(results_runs)
metric_names= ['PICP', 'MPIW', 'CWC', 'RMSE', 'NLL', 'shap_W', 'shap_p']
print('runs\tboots\tensemb')
print(n_runs, '\t', n_bootstraps, '\t', n_ensemble)
print('\tavg\tstd_err\tstd_dev')
for i in range(0,len(metric_names)):
	avg = np.mean(results_runs[:,i])
	std_dev = np.std(results_runs[:,i], ddof=in_ddof)
	std_err = std_dev/np.sqrt(n_runs)
	print(metric_names[i], '\t', round(avg,3),
		'\t', round(std_err,3),
		'\t', round(std_dev,3))

# timing info
end_time = datetime.datetime.now()
total_time = end_time - start_time
print('seconds taken:', round(total_time.total_seconds(),1),
	'\nstart_time:', start_time.strftime('%H:%M:%S'),
	'end_time:', end_time.strftime('%H:%M:%S'))


from django.urls import path, re_path

from . import views

urlpatterns = [
    # 执行ansible script/ playbook
    path('v1/tasks/exec/command', views.ExecCommandApiView.as_view()),

    # 获取脚本和playbook
    path('v1/tasks/scripts_playbook', views.ScriptPlaybookApiView.as_view()),
    path('v1/tasks/scripts_playbook/<str:filename>/', views.ScriptPlaybookApiView.as_view()),
]


from flask import render_template, redirect, url_for, abort, flash, request,\
    current_app, make_response
from flask_login import login_required, current_user
from flask_sqlalchemy import get_debug_queries
from . import main
from .forms import EditProfileForm, EditProfileAdminForm, PostForm,PostForm1,\
    CommentForm,CommentForm1,InsuranceForm1,InsuranceForm
from .. import db
from ..models import Permission, Role, User, Post, Comment,Insurance
from ..decorators import admin_required, permission_required

@main.after_app_request
def after_request(response):
    for query in get_debug_queries():
        if query.duration >= current_app.config['FLASKY_SLOW_DB_QUERY_TIME']:
            current_app.logger.warning(
                'Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n'
                % (query.statement, query.parameters, query.duration,
                   query.context))
    return response

@main.route('/shutdown')
def server_shutdown():
    if not current_app.testing:
        abort(404)
    shutdown = request.environ.get('werkzeug.server.shutdown')
    if not shutdown:
        abort(500)
    shutdown()
    return 'Shutting down...'

@main.route('/', methods=['GET', 'POST'])
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE) and form.validate_on_submit():
        post = Post( name = form.name.data, phnumber = form.phnumber.data,\
        jobaddress = form.jobaddress.data, author=current_user._get_current_object())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts,
                           show_followed=show_followed, pagination=pagination)

@main.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    page = request.args.get('page', 1, type=int)
    pagination = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('user.html', user=user, posts=posts,
                           pagination=pagination)

@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user._get_current_object())
        db.session.commit()
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)

@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        db.session.commit()
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user)

@main.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(meetway=form.meetway.data,meetcase=form.meetcase.data,\
                          meetdate=form.meetdate.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items

    ### 问题1：怎么让不同的表单在同一个网页中传递给两个视窗函数？

    return render_template('post.html', posts=[post], form=form,
                           comments=comments, pagination=pagination)

@main.route('/post2/<int:id>', methods=['GET', 'POST'])
def post2(id):
    post = Post.query.get_or_404(id)
    form = CommentForm1()
    if form.validate_on_submit():
        comment = Comment(meetway=form.meetway.data,meetcase=form.meetcase.data,\
                          meetdate=form.meetdate.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been published.')
        return redirect(url_for('.post2', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items

    ### 问题1：怎么让不同的表单在同一个网页中传递给两个视窗函数？

    return render_template('post2.html', posts=[post], form=form,
                           comments=comments, pagination=pagination)

@main.route('/post1/<int:id>', methods=['GET', 'POST'])
def insurance(id):
    post = Post.query.get_or_404(id)
    #insurance = Insurance.query.get_or_404(id)
    form = InsuranceForm1()
    if form.validate_on_submit():
        insurance = Insurance(insurname=form.insurname.data,toubaoriqi=form.toubaoriqi.data,\
                          baofei=form.baofei.data,baoer=form.baoer.data, \
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(insurance)
        db.session.commit()
        flash('你的保单已经提交！')
        return redirect(url_for('.insurance', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.insurancese.count() - 1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.insurancese.order_by(Insurance.timestamp.asc()).paginate(page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],error_out=False)
    insurancese = pagination.items
    return render_template('post1.html', posts=[post], form=form,insurancese=insurancese, pagination=pagination)

@main.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit(id):
    post = Post.query.get_or_404(id)
    if current_user != post.author and \
            not current_user.can(Permission.ADMIN):
        abort(403)
    form = PostForm1()
    if form.validate_on_submit():
       #post.body = form.body.data
        post.name = form.name.data
        post.phnumber = form.phnumber.data
        post.career = form.career.data
        post.company = form.company.data
        post.jobaddress = form.jobaddress.data
        post.families = form.families.data
        post.connects = form.connects.data
        post.source = form.source.data
        post.homeaddress =form.homeaddress.data
        post.income = form.income.data
        post.insurance = form.insurance.data
        post.bobies = form.bobies.data
        post.liking = form.liking.data
        post.married = form.married.data

        db.session.add(post)
        db.session.commit()
        flash('The post has been updated.')
        return redirect(url_for('.post', id=post.id))
    #form.body.data = post.body
    form.name.data = post.name
    form.phnumber.data = post.phnumber
    form.career.data = post.career
    form.company.data = post.company
    form.jobaddress.data = post.jobaddress
    form.families.data = post.families
    form.connects.data = post.connects
    form.source.data = post.source
    form.homeaddress.data = post.homeaddress
    form.income.data = post.income
    form.insurance.data = post.insurance
    form.bobies.data = post.bobies
    form.liking.data = post.liking
    form.married.data = post.married
    return render_template('edit_post.html', form=form)

@main.route('/editcc/<int:id>', methods=['GET', 'POST'])
@login_required
def editcc(id):
    comment = Comment.query.get_or_404(id)
    #if current_user != post.author and \
            #not current_user.can(Permission.ADMIN):
        #abort(403)
    #form = PostForm1()
    form = CommentForm()
    if form.validate_on_submit():
        comment.meetway = form.meetway.data
        comment.meetcase = form.meetcase.data
        comment.meetdate = form.meetdate.data
        comment.meetadress = form.meetadress.data
        comment.meettimese = form.meettimese.data
        comment.beetway = form.beetway.data
        comment.newsabout = form.newsabout.data
        comment.thisthink=form.thisthink.data
        comment.fation = form.fation.data
        comment.planbook = form.planbook.data
        comment.badthing = form.badthing.data
        comment.donething = form.donething.data
        comment.nexttime = form.nexttime.data
        comment.todo = form.todo.data

        db.session.add(comment)
        db.session.commit()
        flash('The post has been updated.')
        return redirect(url_for('.post', id=comment.id))

    form.meetway.data = comment.meetway
    form.meetcase.data = comment.meetcase
    form.meetdate.data = comment.meetdate
    form.meetadress.data = comment.meetadress
    form.meettimese.data = comment.meettimese
    form.beetway.data = comment.beetway
    form.newsabout.data = comment.newsabout
    form.thisthink.data = comment.thisthink
    form.fation.data = comment.fation
    form.planbook.data = comment.planbook
    form.badthing.data = comment.badthing
    form.donething.data = comment.donething
    form.nexttime.data = comment.nexttime
    form.todo.data = comment.todo
    return render_template('edit_cc.html', form=form)

@main.route('/editii/<int:id>', methods=['GET', 'POST'])
@login_required
def editii(id):
    insurance = Insurance.query.get_or_404(id)
    #if current_user != post.author and \
            #not current_user.can(Permission.ADMIN):
        #abort(403)
    #form = PostForm1()
    form = InsuranceForm()
    if form.validate_on_submit():
        insurname = form.insurname.data
        baodanhao = form.baodanhao.data
        toubaoriqi = form.toubaoriqi.data
        shengxiaoriqi = form.shengxiaoriqi.data
        baodanzhuangtai = form.baodanzhuangtai.data
        jiaofeifangshi = form.jiaofeifangshi.data
        jiaofeiqi = form.jiaofeiqi.data
        baoxianqijian = form.baoxianqijian.data
        shixiaoriqi = form.shixiaoriqi.data
        baofei = form.baofei.data
        baoer = form.baoer.data
        banknumber = form.banknumber.data
        bankname = form.bankname.data
        nextgetmoney = form.nextgetmoney.data
        tbname =  form.tbname.data
        bbname =  form.bbname.data
        syname =  form.syname.data
        jjname = form.syname.data

        db.session.add(insurance)
        db.session.commit()
        flash('The post has been updated.')
        return redirect(url_for('.editii', id=insurance.id))

    form.insurname.data = insurance.insurname
    form.baodanhao.data = insurance.baodanhao
    form.toubaoriqi.data = insurance.toubaoriqi
    form.shengxiaoriqi.data = insurance.shengxiaoriqi
    form.baodanzhuangtai.data = insurance.baodanzhuangtai
    form.jiaofeifangshi.data = insurance.jiaofeifangshi
    form.jiaofeiqi.data = insurance.jiaofeiqi
    form.baoxianqijian.data =insurance.baoxianqijian
    form.shixiaoriqi.data = insurance.shixiaoriqi
    form.baofei.data = insurance.baofei
    form.baoer.data = insurance.baoer
    form.banknumber.data = insurance.banknumber
    form.bankname.data = insurance.bankname
    form.nextgetmoney.data=insurance.nextgetmoney
    form.tbname.data = insurance.tbname
    form.bbname.data = insurance.bbname
    form.syname.data = insurance.syname
    form.syname.data = insurance.jjname

    return render_template('edit_11.html', form=form)

@main.route('/follow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def follow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    if current_user.is_following(user):
        flash('You are already following this user.')
        return redirect(url_for('.user', username=username))
    current_user.follow(user)
    db.session.commit()
    flash('You are now following %s.' % username)
    return redirect(url_for('.user', username=username))

@main.route('/unfollow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def unfollow(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    if not current_user.is_following(user):
        flash('You are not following this user.')
        return redirect(url_for('.user', username=username))
    current_user.unfollow(user)
    db.session.commit()
    flash('You are not following %s anymore.' % username)
    return redirect(url_for('.user', username=username))

@main.route('/followers/<username>')
def followers(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followers.paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    follows = [{'user': item.follower, 'timestamp': item.timestamp}
               for item in pagination.items]
    return render_template('followers.html', user=user, title="Followers of",
                           endpoint='.followers', pagination=pagination,
                           follows=follows)

@main.route('/followed_by/<username>')
def followed_by(username):
    user = User.query.filter_by(username=username).first()
    if user is None:
        flash('Invalid user.')
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = user.followed.paginate(
        page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
        error_out=False)
    follows = [{'user': item.followed, 'timestamp': item.timestamp}
               for item in pagination.items]
    return render_template('followers.html', user=user, title="Followed by",
                           endpoint='.followed_by', pagination=pagination,
                           follows=follows)

@main.route('/all')
@login_required
def show_all():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_followed', '', max_age=30*24*60*60)
    return resp

@main.route('/followed')
@login_required
def show_followed():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_followed', '1', max_age=30*24*60*60)
    return resp

@main.route('/moderate')
@login_required
@permission_required(Permission.MODERATE)
def moderate():
    page = request.args.get('page', 1, type=int)
    pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('moderate.html', comments=comments,
                           pagination=pagination, page=page)

@main.route('/moderate/enable/<int:id>')
@login_required
@permission_required(Permission.MODERATE)
def moderate_enable(id):
    comment = Comment.query.get_or_404(id)
    comment.disabled = False
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('.moderate',
                            page=request.args.get('page', 1, type=int)))

@main.route('/moderate/disable/<int:id>')
@login_required
@permission_required(Permission.MODERATE)
def moderate_disable(id):
    comment = Comment.query.get_or_404(id)
    comment.disabled = True
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('.moderate',
                            page=request.args.get('page', 1, type=int)))


application_title = "TCM"
main_python_file = "Main.py"

import sys
from cx_Freeze import setup, Executable

base = None
if sys.platform == "win32":
    base = "Win32GUI"

includes = ["atexit","re", "PyQt4", "sip", "PyQt4.QtCore", "src/TCM/TCM.py"]

setup(
        name = application_title,
        version = "0.1",
        description = "TCM",
        options = {"build_exe" : {"includes" : includes }},
        executables = [Executable(main_python_file, base = base)])


import numpy as np
from vg.compat import v2 as vg

def inflection_points(points, rise_axis, run_axis):
    """
    Find the list of vertices that preceed inflection points in a curve. The
    curve is differentiated with respect to the coordinate system defined by
    `rise_axis` and `run_axis`.

    Interestingly, `lambda x: 2*x + 1` should have no inflection points, but
    almost every point on the line is detected. It's because a zero or zero
    crossing in the second derivative is necessary but not sufficient to
    detect an inflection point. You also need a higher derivative of odd
    order that's non-zero. But that gets ugly to detect reliably using sparse
    finite differences. Just know that if you've got a straight line this
    method will go a bit haywire.

    rise_axis: A vector representing the vertical axis of the coordinate system.
    run_axis: A vector representing the the horiztonal axis of the coordinate system.

    returns: a list of points in space corresponding to the vertices that
    immediately preceed inflection points in the curve
    """
    vg.shape.check(locals(), "points", (-1, 3))
    vg.shape.check(locals(), "rise_axis", (3,))
    vg.shape.check(locals(), "run_axis", (3,))

    coords_on_run_axis = points.dot(run_axis)
    coords_on_rise_axis = points.dot(rise_axis)

    # Take the second order finite difference of the curve with respect to the
    # defined coordinate system
    finite_difference_1 = np.gradient(coords_on_rise_axis, coords_on_run_axis)
    finite_difference_2 = np.gradient(finite_difference_1, coords_on_run_axis)

    # Compare the product of all neighboring pairs of points in the second
    # derivative. If a pair of points has a negative product, then the second
    # derivative changes sign between those points. These are the inflection
    # points.
    is_inflection_point = np.concatenate(
        [finite_difference_2[:-1] * finite_difference_2[1:] <= 0, [False]]
    )

    return points[is_inflection_point]

def point_of_max_acceleration(points, rise_axis, run_axis, subdivide_by_length=None):
    """
    Find the point on a curve where the curve is maximally accelerating
    in the direction specified by `rise_axis`. `run_axis` is the horizontal
    axis along which slices are taken.

    Args:
        points (np.arraylike): A stack of points, as `kx3`. For best
            results, trim these to the area of interest before calling.
        rise_axis (np.arraylike): The vertical axis, as a 3D vector.
        run_axis (np.arraylike): The horizonal axis, as a 3D vector.
        subdivide_by_length (float): When provided, the maximum space
            between each point. The idea is keep the slice width small,
            however this constraint is applied in 3D space, not along
            the `run_axis`. For best results pass a value that is small
            relative to the changes in the geometry. When `None`, the
            points are used without modification.
    """
    from ..polyline._polyline_object import Polyline

    k = vg.shape.check(locals(), "points", (-1, 3))
    vg.shape.check(locals(), "rise_axis", (3,))
    vg.shape.check(locals(), "run_axis", (3,))

    if k < 2:
        raise ValueError("At least two points are required")

    if subdivide_by_length is not None:
        subdivided = Polyline(v=points, is_closed=False).subdivided_by_length(
            subdivide_by_length
        )
        points = subdivided.v

    coords_on_run_axis = points.dot(run_axis)
    coords_on_rise_axis = points.dot(rise_axis)

    finite_difference_1 = np.gradient(coords_on_rise_axis, coords_on_run_axis)
    finite_difference_2 = np.gradient(finite_difference_1, coords_on_run_axis)

    # `np.argmax(finite_difference_2)` produces false positives where the first
    # derivative of the next point is positive. Exclude these bogus points.
    valid_points = np.logical_and(
        np.roll(finite_difference_1, 1) > 0,
        np.roll(finite_difference_1, -1) > 0,
    )
    valid_points[0] = False
    valid_points[-1] = False

    try:
        index = np.argmax(finite_difference_2[valid_points])
    except ValueError:
        return None

    return points[valid_points][index]


import sys

# On import le module sys puis on verifie si un argument est entré si non on affichera un message d'erreur
if len(sys.argv) < 2:
    print("erreur .")
    sys.exit(1)
# Si l'argument donné n'est pas un nombre entier on affichera un message d'erreur
if not sys.argv[1].isdigit():
    print("erreur .")
    sys.exit(1)
# On converti la valeur de l'argument en nombre entier et on calcul la racine carré de l'argument
nombre = int(sys.argv[1])
resultat = int(nombre ** 0.5)
# On affiche le resultat de la racine carré
print(resultat)


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use("Qt5Agg")

colors = ['#FFB6B9', '#FAE3D9', '#BBDED6', '#61C0BF', "#CCA8E9", "#F67280"]
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 500)

df = sns.load_dataset("titanic")

def check_df(dataframe, head=5, tail=5):
    print("*" * 70)
    print(" Shape ".center(70, "*"))
    print("*" * 70)
    print(dataframe.shape)

    print("*" * 70)
    print(" Types ".center(70, "*"))
    print("*" * 70)
    print(dataframe.dtypes)

    print("*" * 70)
    print(" Head ".center(70, "*"))
    print("*" * 70)
    print(dataframe.head(head))

    print("*" * 70)
    print(" Tail ".center(70, "*"))
    print("*" * 70)
    print(dataframe.tail(tail))

    print("*" * 70)
    print(" NA ".center(70, "*"))
    print("*" * 70)
    print(dataframe.isnull().sum())

    print("*" * 70)
    print(" Quantiles ".center(70, "*"))
    print("*" * 70)
    print(dataframe.describe([.01, .05, .1, .5, .9, .95, .99]).T)

    print("*" * 70)
    print(" Duplicate Rows ".center(70, "*"))
    print("*" * 70)
    print(dataframe.duplicated().sum())

    print("*" * 70)
    print(" Uniques ".center(70, "*"))
    print("*" * 70)
    print(dataframe.nunique())

check_df(df)

def grab_col_names(dataframe, cat_th=10, car_th=25):
    cat_cols = [col for col in dataframe.columns if dataframe[col].dtype == "O"]
    cat_but_car = [col for col in dataframe.columns if
                   dataframe[col].nunique() > car_th and dataframe[col].dtype == "O"]

    num_cols = [col for col in dataframe.columns if dataframe[col].dtype != "O"]
    num_but_cat = [col for col in dataframe.columns if
                   dataframe[col].dtype != "O" and dataframe[col].nunique() < cat_th]
    num_cols = [col for col in num_cols if col not in num_but_cat]

    cat_cols = num_but_cat + cat_cols
    cat_cols = [col for col in cat_cols if col not in cat_but_car]

    print("".center(150, '~'))
    print(f"Observations: {dataframe.shape[0]}")
    print(f"Features: {dataframe.shape[1]}")
    print(f"Shape of dataset: {dataframe.shape}")
    print("".center(150, '~'))
    print(f"Categorical Variables: \n\n{cat_cols}")
    print("".center(150, '~'))
    print(f"\n\nNumerical Variables: \n\n{num_cols}")
    print("".center(150, '~'))
    print(f"\n\nNumber of Categorical Variables: \n\n{len(cat_cols)}")
    print("".center(150, '~'))
    print(f"\n\nNumber of Numerical Variables: \n\n{len(num_cols)}")
    print("".center(150, '~'))
    return cat_cols, num_cols, cat_but_car

def cat_summary(dataframe, cat_col, target, plot=True):

    print(pd.DataFrame({cat_col: dataframe[cat_col].value_counts(),
                        "Ratio": 100 * dataframe[cat_col].value_counts() / len(dataframe),
                        "Target_Median": dataframe.groupby(cat_col)[target].median(),
                        "Target_Mean": dataframe.groupby(cat_col)[target].mean(),
                       "Target_Sum:": dataframe.groupby(cat_col)[target].sum()}))
    print("".center(100, "#"))
    if target in cat_cols:
        sns.set_style("whitegrid")
        sns.countplot(data=dataframe, x=cat_col, hue=target, palette=colors)
        plt.title(f"Count plot of {cat_col.capitalize()}")
        plt.show(block=True)
    else:
        sns.set_style("whitegrid")
        sns.catplot(data=dataframe, x=cat_col, y=target, kind="box", palette=colors)
        plt.title(f"Box Plot of {cat_col.capitalize()}")
        plt.show(block=True)

cat_cols, num_cols, cat_but_car = grab_col_names(df)

for col in cat_cols:
    cat_summary(df, col, "survived")

def cat_plots(dataframe, cat_col):
    print("".center(100, "#"))
    print(dataframe[cat_col].value_counts())

    plt.figure(figsize=(15, 10))
    plt.suptitle(cat_col.capitalize(), size=16)
    plt.subplot(1, 2, 1)
    plt.title("Percentages")
    plt.pie(dataframe[cat_col].value_counts().values.tolist(),
            labels=dataframe[cat_col].value_counts().keys().tolist(),
            labeldistance=1.1,
            wedgeprops={'linewidth': 3, 'edgecolor': 'white'},
            colors=colors,
            autopct='%1.0f%%')

    plt.subplot(1, 2, 2)
    plt.title("Countplot")
    sns.countplot(data=dataframe, x=cat_col, palette=colors)
    plt.tight_layout(pad=3)
    plt.show(block=True)

for col in cat_cols:
    cat_plots(df, col)

def num_summary(dataframe, col_name, target):
    quantiles = [.01, .05, .1, .5, .9, .95, .99]
    print(dataframe[col_name].describe(quantiles).T)
    plt.figure(figsize=(15, 10))
    plt.suptitle(col_name.capitalize(), size=16)
    plt.subplot(1, 3, 1)
    plt.title("Histogram")
    sns.histplot(dataframe[col_name], color="#FFB6B9")
    plt.subplot(1, 3, 2)
    plt.title("Box Plot")
    sns.boxplot(data=dataframe, y=col_name, color="#F67280")
    if target in num_cols:
        plt.subplot(1, 3, 3)
        plt.title("Scatter Plot")
        sns.scatterplot(x=target, y=col_name, data=dataframe, color="#CCA8E9")
    else:
        plt.subplot(1, 3, 3)
        sns.histplot(data=dataframe, x=col_name,label=col_name, hue=target, kde=True, color=colors)
    plt.show(block=True)

for col in num_cols:
    num_summary(df, col, "survived")

def high_correlated_cols(dataframe, target, plot=True, corr_th=0.7):
    corr = dataframe.corr()
    corr_matrix = corr.abs()
    msk = np.triu(corr)
    drop_list = [col for col in num_cols if dataframe[[col, target]].corr().abs().loc[col, target] > corr_th]
    if plot:
        sns.heatmap(corr, mask=msk, annot=True, linecolor="black", cmap=colors)
        plt.yticks(rotation=0, size=10)
        plt.xticks(rotation=75, size=10)
        plt.title('\nCorrelation Map\n', size=15)
        plt.show()
    return drop_list

drop_list = high_correlated_cols(df, "survived")


from django.shortcuts import render

from django.http.response import JsonResponse
from rest_framework import generics
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
from .models import Storer, Feedback
from .serializers import StorerSerializer, FeedbackSerializer
from django.http import HttpResponse
import json
import pprint

# Create your views here.

class StorerView(generics.CreateAPIView):
    queryset = Storer.objects.all()
    serializer_class = StorerSerializer

class FeedbackView(generics.CreateAPIView):
    queryset = Feedback.objects.all()
    serializer_class = FeedbackSerializer

def evaluator_view(request):
    feedback_view = FeedbackView()
    feedback_lst = feedback_view.queryset
    # doc_id_str = [feedback.doc_id for feedback in feedback_lst]
    original_author_id_str = [feedback.original_author_id.original_author_id for feedback in feedback_lst]
    editor_id_str = [feedback.editor_id for feedback in feedback_lst]
    feedback_correctness = [[feedback.feedback[key][1] for key in feedback.feedback] for feedback in feedback_lst]
    feedback_str = [[feedback.feedback[key][0] for key in feedback.feedback] for feedback in feedback_lst]
    feedback_score = [feedback.score for feedback in feedback_lst]
    # print(answer_str)
    context = {'queryset': []}
    for i in range(len(original_author_id_str)):
        original_author, editor = original_author_id_str[i], editor_id_str[i]
        scores = feedback_score[i]
        for j in range(len(feedback_correctness[i])):
            correct = feedback_correctness[i][j]
            feedback_string = feedback_str[i][j]
            context['queryset'].append({
                'original_author': original_author if j == 0 else '',
                'editor': editor if j == 0 else '',
                'feedback': feedback_string,
                'correctness': correct,
                'final_score': scores if j == len(feedback_correctness[i])-1 else ''
            })
    return render(request, "data_summary.html", context)

def home(request):
    feedback_view = FeedbackView()
    feedback_lst = feedback_view.queryset
    doc_id_str = [feedback.doc_id for feedback in feedback_lst]
    original_author_id_str = [feedback.original_author_id for feedback in feedback_lst]
    feedback_id = [[key for key in feedback.feedback] for feedback in feedback_lst]
    feedback_correctness = [[feedback.feedback[key][1] for key in feedback.feedback] for feedback in feedback_lst]
    feedback_str = [[feedback.feedback[key][0] for key in feedback.feedback] for feedback in feedback_lst]
    contain_error_str = [feedback.score for feedback in feedback_lst]
    # print(answer_str)
    return HttpResponse(feedback_str)

def create_view(request):
    return StorerView.as_view()(request)

@csrf_exempt
def save_data(request):
    body = request.body.decode("utf-8")
    load_data = json.loads(body)
    assignment = Storer(doc_id=load_data["docid"], original_author_id=load_data["userid"], answers=load_data["answers"], contains_error=load_data["contains_error"])
    feedback = Feedback(doc_id=assignment, original_author_id=assignment, editor_id=load_data["editor_id"],
                        feedback=load_data["feedback"], score=load_data["score"])
    assignment.save()
    feedback.save()
    return HttpResponse("Got save data request")


n = int(input())
M = 0
C = 0
for i in range(n):
    m, c = map(int, input().split())
    if m > c:
        M += 1
    elif m < c:
        C += 1
if M > C:
    print('Mishka')
elif M < C:
    print('Chris')
else:
    print('Friendship is magic!^^')

5. iterable objects-for/2. for-range/task10.py


import itertools
import math

import numpy as np
import torch

from . import data_utils
import copy

from collections import OrderedDict
from . import iterators

class CountingIteratorDtn(object):
    """Wrapper around an iterable that maintains the iteration count.

    Args:
        iterable (iterable): iterable to wrap

    Attributes:
        count (int): number of elements consumed from this iterator
    """

    def __init__(self, iterable):
        self.iterable = iterable
        self.count = 0
        self.itr = iter(self)
        self.len = len(iterable)

    def __len__(self):
        return self.len

    def __iter__(self):
        for x in self.iterable:
            self.count += 1
            yield x

    def __next__(self):
        try:
            data = next(self.itr)
        except StopIteration:
            self.count = 0
            self.itr = iter(self)
            data = next(self.itr)
        return data

    def has_next(self):
        """Whether the iterator has been exhausted."""
        return self.count < len(self)

    def skip(self, num_to_skip):
        """Fast-forward the iterator by skipping *num_to_skip* elements."""
        next(itertools.islice(self.itr, num_to_skip, num_to_skip), None)
        self.len -= num_to_skip
        return self

class EpochBatchIteratorDtn(object):
    """A multi-epoch iterator over a :class:`torch.utils.data.Dataset`.

    Compared to :class:`torch.utils.data.DataLoader`, this iterator:

    - can be reused across multiple epochs with the :func:`next_epoch_itr`
      method (optionally shuffled between epochs)
    - can be serialized/deserialized with the :func:`state_dict` and
      :func:`load_state_dict` methods
    - supports sharding with the *num_shards* and *shard_id* arguments

    Args:
        dataset (~torch.utils.data.Dataset): dataset from which to load the data
        collate_fn (callable): merges a list of samples to form a mini-batch
        batch_sampler (~torch.utils.data.Sampler): an iterator over batches of
            indices
        seed (int, optional): seed for random number generator for
            reproducibility (default: 1).
        num_shards (int, optional): shard the data iterator into N
            shards (default: 1).
        shard_id (int, optional): which shard of the data iterator to
            return (default: 0).
        num_workers (int, optional): how many subprocesses to use for data
            loading. 0 means the data will be loaded in the main process
            (default: 0).
    """

    def __init__(
        self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0,
        num_workers=0,
    ):
        assert isinstance(dataset, OrderedDict)
        self.dataset = dataset
        self.collate_fn = collate_fn
        self.frozen_batches = OrderedDict()
        for domain in batch_sampler.keys():
            self.frozen_batches[domain] = tuple(batch_sampler[domain])
        self.seed = seed
        self.num_shards = num_shards
        self.shard_id = shard_id
        self.num_workers = num_workers

        self.epoch = 0
        self.count_sum = 0
        self._cur_epoch_itr = None
        self._next_epoch_itr = None
        self._supports_prefetch = getattr(dataset[list(batch_sampler.keys())[0]], \
                                                  'supports_prefetch', False)

    def __len__(self):

        return sum(len(frozen_batch) for (domain, frozen_batch) in self.frozen_batches.items())

    def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False):
        """Return a new iterator over the dataset.

        Args:
            shuffle (bool, optional): shuffle batches before returning the
                iterator (default: True).
            fix_batches_to_gpus: ensure that batches are always
                allocated to the same shards across epochs. Requires
                that :attr:`dataset` supports prefetching (default: False).
        """
        if self._next_epoch_itr is not None:
            self._cur_epoch_itr = self._next_epoch_itr
            self._next_epoch_itr = None
        else:
            self.epoch += 1
            self._cur_epoch_itr = self._get_iterator_for_epoch(
                self.epoch, shuffle, fix_batches_to_gpus=fix_batches_to_gpus,
            )
        return self._cur_epoch_itr

    def end_of_epoch(self):
        """Returns whether the most recent epoch iterator has been exhausted"""
        count = 0
        leng = 0
        for domain in self.dataset.keys():
            count += self._cur_epoch_itr[domain].count
            leng += len(self._cur_epoch_itr[domain])
        return not count <leng

    @property
    def iterations_in_epoch(self):
        """The number of consumed batches in the current epoch."""
        if self._cur_epoch_itr is not None:
            return sum(self._cur_epoch_itr[domain].count for domain in self._cur_epoch_itr.keys())
        elif self._next_epoch_itr is not None:
            return sum(self._next_epoch_itr[domain].count for domain in self._next_epoch_itr.keys())
        return 0

    def state_dict(self):
        """Returns a dictionary containing a whole state of the iterator."""
        domain_count = OrderedDict()
        if self._cur_epoch_itr is not None:
            for domain in self._cur_epoch_itr.keys():
                domain_count[domain] = self._cur_epoch_itr[domain].count
        elif self._next_epoch_itr is not None:
            for domain in self._next_epoch_itr.keys():
                domain_count[domain] = self._next_epoch_itr[domain].count
        else:
            for domain in self.dataset.keys():
                domain_count[domain] = 0
        return {
            'epoch': self.epoch,
            'iterations_in_epoch': self.iterations_in_epoch,
            'domain_count': domain_count
        }

    def load_state_dict(self, state_dict):
        """Copies the state of the iterator from the given *state_dict*."""
        self.epoch = state_dict['epoch']
        itr_pos = state_dict.get('iterations_in_epoch', 0)
        domain_count = OrderedDict()
        for domain in self.dataset.keys():
            domain_count[domain] = 0

        if itr_pos > 0:
            # fast-forward epoch iterator
            itr = self._get_iterator_for_epoch(self.epoch, state_dict.get('shuffle', True))
            self._next_epoch_itr = OrderedDict()
            for domain in self.dataset.keys():
                if domain_count[domain] < len(itr[domain]):
                    self._next_epoch_itr[domain] = itr[domain].skip(domain_count[domain])

    def _get_iterator_for_epoch(self, epoch, shuffle, fix_batches_to_gpus=False):

        def shuffle_batches(batches, seed):
            # set seed based on the seed and epoch number so that we get
            # reproducible results when resuming from checkpoints
            with data_utils.numpy_seed(seed):
                np.random.shuffle(batches)
            return batches

        # if self._supports_prefetch:
        if self._supports_prefetch:
            batches = copy.deepcopy(self.frozen_batches)

            if shuffle and not fix_batches_to_gpus:
                for domain in self.frozen_batches.keys():
                    batches[domain] = shuffle_batches(list(batches[domain]), self.seed + epoch)
            for domain in self.frozen_batches.keys():
                batches[domain] = list(iterators.ShardedIterator(
                batches[domain], self.num_shards, self.shard_id, fill_value=[]))
                self.dataset[domain].prefetch([i for s in batches[domain] for i in s])

            if shuffle and fix_batches_to_gpus:
                for domain in self.frozen_batches.keys():
                    batches[domain] = shuffle_batches(batches[domain], self.seed + epoch + self.shard_id)

        else:
            batches = OrderedDict()
            if shuffle:
                for domain in self.frozen_batches.keys():
                    batches[domain] = shuffle_batches(list(copy.deepcopy(self.frozen_batches[domain])), self.seed + epoch)
            else:
                for domain in self.frozen_batches.keys():
                    batches[domain] = copy.deepcopy(self.frozen_batches[domain])
            for domain in self.frozen_batches.keys():
                batches[domain] = iterators.ShardedIterator(batches[domain], self.num_shards, self.shard_id, fill_value=[])
        countingiterator = OrderedDict()

        for domain in self.frozen_batches.keys():
            countingiterator[domain] = CountingIteratorDtn(torch.utils.data.DataLoader(
                                                        self.dataset[domain],
                                                        collate_fn=self.collate_fn[domain],
                                                        batch_sampler=batches[domain],
                                                        num_workers=self.num_workers,))
        return countingiterator

class GroupedIteratorDtn(object):
    """Wrapper around an iterable that returns groups (chunks) of items.

    Args:
        iterable (iterable): iterable to wrap
        chunk_size (int): size of each chunk
    """

    def __init__(self, iterable, chunk_size):
        self._len = int(math.ceil(len(iterable) / float(chunk_size)))
        self.itr = iterable
        self.chunk_size = chunk_size

    def __len__(self):
        return self._len

    def __iter__(self):
        return self

    def __next__(self):
        chunk = []
        try:
            for _ in range(self.chunk_size):
                chunk.append(next(self.itr))
        except StopIteration as e:
            if len(chunk) == 0:
                raise e
        return chunk


import hashlib
import os

IMAGE_PATH="Google_Search2"
DUPLICATES_PATH="Duplicates"
def file_hash(filepath):
	with open(filepath,'rb') as f:
		return hashlib.md5(f.read()).hexdigest()

file_list=os.listdir(IMAGE_PATH)
print(len(file_list))

duplicates={}
flag=0
for filename in file_list:
	fhash=file_hash(IMAGE_PATH+"/"+filename)
	if(fhash in duplicates.keys()):
		duplicates[fhash].append(filename)
		flag=1
	else:
		duplicates[fhash]=[filename]
if(flag==1):
	print("DUPLICATES : ")
	if(DUPLICATES_PATH not in os.listdir()):
		os.system("mkdir "+DUPLICATES_PATH)
	index=1
	for k in duplicates.keys():
		if(len(duplicates[k])>1):
			print("SET "+str(index))
			orig_file=duplicates[k][0]
			os.system("cp "+IMAGE_PATH+"/"+orig_file+" "+DUPLICATES_PATH+"/"+orig_file)
			print(orig_file,end=' ')
			for j in range(1,len(duplicates[k])):
				dup_file=duplicates[k][j]
				os.system("cp "+IMAGE_PATH+"/"+orig_file+" "+DUPLICATES_PATH+"/CopyOf"+orig_file)
				os.remove(IMAGE_PATH+"/"+dup_file)
				print(dup_file,end=' ')
			print(" ")
			index+=1


import os
import torch
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from skimage import io, transform
# You might want to change path to the corresponding one
# IMPORTANT: offset the file right!!
path_train_index ="data/anno_fine/train.txt"
path_train_label ="data/anno_fine/train_cate.txt"
path_test_index = "data/anno_fine/test.txt"
path_test_label = "data/anno_fine/test_cate.txt"
path_root_dir_images= "data/images/"

class FashionTrainDataset(Dataset):

    def __init__(self, csv_file = path_train_index, label_file= path_train_label, root_dir = path_root_dir_images, transform=None):
        """
        Args:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        self.landmarks_frame = pd.read_csv(csv_file)
        self.label_frame= pd.read_csv(label_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.landmarks_frame)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        img_name = os.path.join(self.root_dir,
                                self.landmarks_frame.iloc[idx, 0])
        image = io.imread(img_name)
        landmarks = self.label_frame.iloc[idx, 0]
        if self.transform:
            image = self.transform(image)
        return image,landmarks

class FashionTestDataset(Dataset):

    def __init__(self, csv_file = path_test_index, label_file= path_test_label, root_dir = path_root_dir_images, transform=None):
        """
        Args:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        self.landmarks_frame = pd.read_csv(csv_file)

        self.label_frame= pd.read_csv(label_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.landmarks_frame)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        img_name = os.path.join(self.root_dir,
                                self.landmarks_frame.iloc[idx, 0])
        image = io.imread(img_name)
        landmarks = self.label_frame.iloc[idx, 0]
        #landmarks = np.array([landmarks])
        #landmarks = landmarks.astype('float').reshape(-1, 2)
        if self.transform:
            image = self.transform(image)
        return image,landmarks

#transformz = transforms.Compose([
 #       transforms.ToTensor(),
  #      transforms.RandomResizedCrop(224),
   #     transforms.Normalize((0.5), (0.5))
    #])
#data=FashionTrainDataset(transform= transformz)
#print(data[0][1])


"""
Functions for working with the books database.
"""
__author__ = 'Jeffrey Hogan'

import books

REVIEWS_PER_PAGE = 15;

QUERIES = {
    'reviews_count': '''
        SELECT COUNT(*) FROM review;
    ''',
    'reviews_by_book_count': '''
        SELECT COUNT(*) FROM review WHERE book_id = %s;
    ''',
    'select_reviews_where': '''
        SELECT review_id, book_core.core_id, book_id, book_title, reviewer, login_name, to_char(date_reviewed,'Mon. DD, YYYY'), review_text
        FROM review
        JOIN book_core ON review.book_id = book_core.core_id
        JOIN book USING (book_id)
        JOIN booknet_user ON reviewer = user_id
        %s
        LIMIT %s OFFSET %s
    '''
}

def get_total_pages(cur,query):
    cur.execute(query)
    total_books = cur.fetchone()[0];
    total_pages = (total_books / REVIEWS_PER_PAGE) + 1;
    return total_pages

def get_spotlight_reviews(cur, amount):
    return get_review_range(cur,0,amount)

def get_review_range(cur,start,amount):

    total_pages = get_total_pages(cur, QUERIES['reviews_count'])
    query = QUERIES['select_reviews_where'] % ('', '%s', '%s')
    cur.execute(query, (amount, start))
    review_info = []
    for  review_id, core_id, book_id, book_title, reviewer, login_name, date_reviewed, review_text in cur:
        review_info.append({'core_id':core_id, 'id':review_id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'), 'reviewer':reviewer, 'reviewer_name': login_name, 'date_reviewed': date_reviewed, 'review_text':review_text})

    return total_pages, review_info

def get_reviews_by_book(cur, start, amount, bid, current_user_id):

    total_pages = get_total_pages(cur, QUERIES['reviews_by_book_count'] % bid)
    query = QUERIES['select_reviews_where'] % ('WHERE review.book_id = %s', '%s', '%s')
    book_info = books.get_book(cur,bid,current_user_id)

    cur.execute(query, (bid, amount, start))

    review_info = {'book_info': book_info, 'reviews': []}
    for  review_id, core_id, book_id, book_title, reviewer, login_name, date_reviewed, review_text in cur:
        review_info['reviews'].append({'core_id':core_id, 'id':review_id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'), 'reviewer':reviewer, 'reviewer_name': login_name, 'date_reviewed': date_reviewed, 'review_text':review_text})

    return total_pages, review_info

def get_review(cur,review_id):
    cur.execute('''
        SELECT review_id, core_id, book_id, book_title, reviewer, login_name, to_char(date_reviewed,'Mon. DD, YYYY'), review_text
        FROM review
        JOIN book USING (book_id)
        JOIN book_core USING (core_id)
        JOIN booknet_user ON reviewer = user_id
        WHERE review_id = %s
    ''', (review_id,))
    review_info = {}
    for  review_id, core_id, book_id, book_title, reviewer, login_name, date_reviewed, review_text in cur:
        review_info = {'core_id':core_id, 'id':review_id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'),
                       'user_id':reviewer, 'reviewer': login_name, 'date_reviewed': date_reviewed, 'review_text':review_text}

    review_info['book'] = books.get_book(cur, review_info['book_id'])
    return review_info

###################### Modifications ##################################################################################
def add_review(cur, book_id, user_id, form):
    message = []
    entry_status = True
    review_id = 0
    try:
        message.append(books.add_rating(cur, book_id, form['rating'], user_id))
    except KeyError:
        # no rating entered
        pass

    try:
        cur.execute('''
          INSERT INTO review (book_id, reviewer, review_text, date_reviewed)
          VALUES(%s, %s, %s, current_timestamp)
          RETURNING review_id
        ''', (book_id, user_id, form['review_input']))
        if cur.rowcount == 1:
            message.append("Review of saved!")
            review_id = cur.fetchone()[0]
        else:
            message.append("Unknown error!")
            entry_status = False
    except KeyError:
        message.append("No review text provided!")
        entry_status = False
    # except:
    #     message = "Unknown error!"
    #     entry_status = False

    return entry_status, message, review_id


# Date 31/03/2020
# @author Spyros Patmanidis
#
# References
# https://leetcode.com/problems/coin-change/
#
############### Coin Change ###############
# You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest
# number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the
# coins, return -1.
#
# Example 1:
# Input: coins = [1, 2, 5], amount = 11
# Output: 3
# Explanation: 11 = 5 + 5 + 1
#
# Example 2:
# Input: coins = [2], amount = 3
# Output: -1
#
# Note:
# You may assume that you have an infinite number of each kind of coin.
#
# Complexity Analysis
# Time: O(N * C), where N = # of different coins and C is the amount you want to make up.
# Space: O(C).

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        if amount == 0: return 0
        dp = [0] + [float('inf')] * amount
        for c in coins:
            for j in range(c, amount+1):
                dp[j] = min(dp[j], dp[j-c] + 1)
        return dp[-1] if dp[-1] != float('inf') else -1

def main():
    sol = Solution()
    coins, amount = [1, 2, 5], 11
    print(sol.coinChange(coins, amount))
    coins, amount = [2], 3
    print(sol.coinChange(coins, amount))

if __name__ == "__main__":
    main()


import numpy as np
import matplotlib.pyplot as plt

from matplotlib import cm
from matplotlib.colors import LogNorm
from matplotlib.animation import FuncAnimation as FA

plt.rc("font", family="serif", size=16)
plt.rc("mathtext", fontset="cm")
plt.rc("lines", lw=2)
plt.rc("axes", grid=True)

def drdl(u,r):
    return 2*r + u - u*r

eps=1
def dudl(u,r):
    return (eps - 3*u)*u

u = np.linspace(0, .5)
r = np.linspace(-.5, .5)

u, r = np.meshgrid(u, r)
v, w = dudl(u, r), drdl(u, r)

fig, ax = plt.subplots()
ax.streamplot(u, r, v, w,  density=2., linewidth=1)
ax.set_xlabel("$u$")
ax.set_ylabel("$r$")

plt.show()


# Preguntando si dos valores son iguales
a = 4
b = 5

resultado = (a == b)
print(f'Resultado == : {resultado}')

# Preguntando si dos valores son distintos

resultado = (a != b)
print(f'resultado de != : {resultado}')

# Operador de mayor que
resultado = (a > b)
print(f'resultado de > : {resultado}')

# Determinando si un número es par
entrada = int(input('Proporciona un número: '))

if (entrada % 2 == 0):
    print('El número es par')
else:
    print('El número es impar')

# Determinando si es mayor de edad

edad = int(input('Proporciona tu edad: '))

if (edad >= 18):
    print(f'Eres mayor de edad')
else:
    print(f'Eres menor de edad')


# Ref: https://github.com/cydonia999/VGGFace2-pytorch/blob/master/models/resnet.py

import torch
import torch.nn as nn
import math

__all__ = ["ConvNet", "convnet3", "convnet1"]

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(
        # bias=False
        in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True
    )

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        # self.downsample = downsample
        self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, ceil_mode=True)
        self.dropout = nn.Dropout2d(0.3)
        self.stride = stride

    def forward(self, x):
        # residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        # if self.downsample is not None:
        #     residual = self.downsample(x)

        # out += residual
        out = self.maxpool(out)
        out = self.dropout(out)
        out = self.relu(out)

        return out

class ConvNet(nn.Module):
    def __init__(
        self,
        block: nn.Module,
        num_layers: int,
        num_classes: int = 1000,
        include_top: bool = True,
        connector: int = None,
        connector_sigmoid: bool = False,
        final_activation: bool = False,
    ):
        super(ConvNet, self).__init__()
        self.include_top = include_top
        self.connector = connector
        self.connector_sigmoid = connector_sigmoid
        self.final_activation = final_activation

        # self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
        # self.bn1 = nn.BatchNorm2d(64)

        # self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=3, bias=False)
        # self.relu = nn.ReLU(inplace=True)
        # self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True)

        # self.layer1 = self._make_layer(block, 64, layers[0])
        # self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        # self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        # self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

        inplanes = 3
        outplanes = 32
        layers = []
        layers.append(block(inplanes, outplanes))

        inplanes = outplanes
        outplanes *= 2
        for _ in range(1, num_layers):
            layers.append(block(inplanes, outplanes))
            inplanes = outplanes
            outplanes *= 2

        self.hidden = nn.Sequential(*layers)

        # self.avgpool = nn.AvgPool2d(7, stride=1)
        # self.avgpool = nn.AdaptiveAvgPool2d((1, 1))

        if self.connector is not None:
            self.fc_ = nn.Linear(inplanes * (32//(2**num_layers))**2, self.connector)
            if self.connector_sigmoid:
                self.sig = nn.Sigmoid()
            self.fc = nn.Linear(self.connector, num_classes)
        else:
            self.fc = nn.Linear(inplanes * (32//(2**num_layers))**2, num_classes)

        if self.final_activation:
            # self.act = nn.Softmax(dim=1)
            self.act = nn.LogSoftmax(dim=1)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2.0 / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def forward(self, x: torch.Tensor):
        # # print(x.shape)
        # x = self.conv1(x)
        # # print(x.shape)
        # x = self.bn1(x)

        # x = self.conv1(x)
        # x = self.relu(x)
        # x = self.maxpool(x)

        # x = self.layer1(x)
        # x = self.layer2(x)
        # x = self.layer3(x)
        # x = self.layer4(x)
        # # print(x.shape)
        # x = self.avgpool(x)
        # print(x.shape)

        x = self.hidden(x)
        # print(x.shape)

        x = x.view(x.size(0), -1)
        # print(x.shape)

        if self.connector is not None:
            x = self.fc_(x)
            if self.connector_sigmoid:
                x = self.sig(x)

        if not self.include_top:
            return x

        x = self.fc(x)

        if self.final_activation:
            x = self.act(x)

        return x

def convnet5(**kwargs):
    """Constructs a ConvNet-5 model."""
    model = ConvNet(BasicBlock, 5, **kwargs)
    return model

def convnet4(**kwargs):
    """Constructs a ConvNet-4 model."""
    model = ConvNet(BasicBlock, 4, **kwargs)
    return model

def convnet3(**kwargs):
    """Constructs a ConvNet-3 model."""
    model = ConvNet(BasicBlock, 3, **kwargs)
    return model

def convnet2(**kwargs):
    """Constructs a ConvNet-2 model."""
    model = ConvNet(BasicBlock, 2, **kwargs)
    return model

def convnet1(**kwargs):
    """Constructs a ConvNet-1 model."""
    model = ConvNet(BasicBlock, 1, **kwargs)
    return model


# -*- coding: utf-8 -*-
import web
import json
import os
import unittest
from mainapp.libs.signature import check_sig
from mainapp.models.mongo.core.base import Base
from mbio.packages.project_demo.delete_demo import DeleteDemoMongo

class DeleteDemoAction(Base):
    def __init__(self):
        super(DeleteDemoAction, self).__init__()
        self.input_data = web.input()
        self._project_type = self.input_data.type

    @check_sig
    def POST(self):
        requires = ['type', 'task_id']
        for i in requires:
            if not (hasattr(self.input_data, i)):
                return json.dumps({"success": False, "info": "Lack argument: %s!" % i})

        find_result = self.db['sg_table_relation'].find_one({})
        if find_result:
            target = find_result['target']
            print(target)
        else:
            print("nothing found in sg_table_relation")
        try:
            del_demo = DeleteDemoMongo(self.input_data.task_id, self.input_data.type, target)
            del_demo.run()
            run_info = dict(success=True)
            run_info['info'] = 'delete_demo_of_{}'.format(self.input_data.task_id)
            return json.dumps(run_info)
        except Exception as e:
            return json.dumps({"success": False, "info": "running error: %s" % str(e)})

class TestFunction(unittest.TestCase):
    """
    This is test for the tool. Just run this script to do test.
    """
    def test_this(self):
        cmd = 'python /mnt/ilustre/users/sanger-dev/biocluster/bin/webapitest.py '
        cmd += 'post '
        cmd += "-fr no "
        cmd += '-c {} '.format("client03")
        cmd += "i/project_demo/delete_demo "
        cmd += "-b http://192.168.12.102:9090 "
        args = dict(
            task_id="copy_demo_ffff",
            type="ref_rna_v2"
        )
        arg_names, arg_values = args.keys(), args.values()
        cmd += '-n "{}" -d "{}" '.format(";".join(arg_names), ";".join(arg_values))
        print(cmd)
        os.system(cmd)

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


from collections import Counter

from flask import Flask, render_template
from flask_bootstrap import Bootstrap

import switchdb

app = Flask(__name__)

@app.route("/", methods=["GET"])
def switch_inventory():
    """
    Main web page, displays summary statistics of all switches
    """
    lastupdate = getLastUpdate()
    switchdata = getSwitchInfo()
    return render_template("main.html", switches=switchdata, lastupdate=lastupdate)

@app.route("/<serial>", methods=["GET"])
def switch_info(serial):
    """
    This page shows detailed stats on an individual switch
    queried by serial number
    """
    detail = getSwitchDetail(serial)
    intdetail = getInterfaceDetail(serial)
    try:
        raw_data = open(f"raw_output/{serial}.txt", "r").read().splitlines()
    except:
        raw_data = "None collected yet"
    return render_template(
        "detail.html",
        title=serial,
        switch=detail,
        interfaces=intdetail,
        raw_data=raw_data,
    )

@app.route("/network-wide", methods=["GET"])
def network_wide():
    """
    This page shows a summary of all port counts, etc
    across the entire network
    """
    network = getNetworkWide()
    return render_template("network-wide.html", network=network)

@app.route("/lastupdate", methods=["GET"])
def getLastUpdate():
    """
    Check DB for last runtime of backend script
    This is published on the main page to see when stats were last updated
    """
    swDB = switchdb.DB()
    lastupdate = swDB.getLastUpdate()
    swDB.close()
    return lastupdate

def getSwitchInfo():
    """
    Query DB for summary info on all
    switches currently monitored
    """
    swDB = switchdb.DB()
    raw_info = swDB.getAllSummary()
    switchList = []
    for row in raw_info:
        row = list(row)
        switch = {}
        switch["name"] = row[0]
        switch["serial"] = row[1]
        switch["swver"] = row[2]
        switch["ip"] = row[3]
        switch["check"] = row[4]
        switch["total"] = row[5]
        switch["up"] = row[6]
        switch["down"] = row[7]
        switch["disabled"] = row[8]
        if switch["total"] == 0:
            switch["capacity"] = 0
        else:
            switch["capacity"] = (switch["up"] / switch["total"]) * 100
        switchList.append(switch)
    swDB.close()
    return switchList

def getSwitchDetail(serial):
    """
    Query DB for details on one specific device
    by serial number
    """
    swDB = switchdb.DB()
    raw_info = swDB.getSwitchDetail(serial)
    switch = {}
    for row in raw_info:
        switch["name"] = row[0]
        switch["serial"] = row[1]
        switch["model"] = row[2]
        switch["swver"] = row[3]
        switch["ip"] = row[4]
        switch["check"] = row[5]
        switch["total"] = row[6]
        switch["up"] = row[7]
        switch["down"] = row[8]
        switch["disabled"] = row[9]
        switch["int10m"] = row[10]
        switch["int100m"] = row[11]
        switch["int1g"] = row[12]
        switch["int10g"] = row[13]
        switch["int25g"] = row[14]
        switch["int40g"] = row[15]
        switch["int100g"] = row[16]
        switch["copper"] = row[17]
        switch["sfp"] = row[18]
        switch["virtual"] = row[19]
        if switch["total"] == 0:
            switch["capacity"] = 0
        else:
            switch["capacity"] = int((switch["up"] / switch["total"]) * 100)
    swDB.close()
    return switch

def getInterfaceDetail(serial):
    """
    Query DB for interface details on one specific device
    by management IP
    """
    swDB = switchdb.DB()
    raw_info = swDB.getInterfaceDetail(serial)
    interfaceList = []
    for row in raw_info:
        row = list(row)
        interface = {}
        interface["name"] = row[0]
        interface["description"] = row[1]
        interface["physical_address"] = row[2]
        interface["oper_status"] = row[3]
        interface["oper_speed"] = row[4]
        interface["oper_duplex"] = row[5]
        interfaceList.append(interface)
    return interfaceList

def getNetworkWide():
    """
    Query DB for all switch statistcs,
    then tally results & return to web page
    """
    swDB = switchdb.DB()
    result = swDB.getNetworkWideStats()
    swDB.close()
    network = {
        "models": [],
        "swvers": [],
        "total": 0,
        "up": 0,
        "down": 0,
        "disabled": 0,
        "int10m": 0,
        "int100m": 0,
        "int1g": 0,
        "int10g": 0,
        "int25g": 0,
        "int40g": 0,
        "int100g": 0,
        "copper": 0,
        "sfp": 0,
        "virtual": 0,
    }
    modellist = []
    swlist = []
    for row in result:
        if "N/A" not in row[0]:
            modellist.append(row[0])
        if "N/A" not in row[1]:
            swlist.append(row[1])
        network["total"] += row[2]
        network["up"] += row[3]
        network["down"] += row[4]
        network["disabled"] += row[5]
        network["int10m"] += row[6]
        network["int100m"] += row[7]
        network["int1g"] += row[8]
        network["int10g"] += row[9]
        network["int25g"] += row[10]
        network["int40g"] += row[11]
        network["int100g"] += row[12]
        network["copper"] += row[13]
        network["sfp"] += row[14]
        network["virtual"] += row[15]
    # Get 5 most common models / software versions
    network["models"] = Counter(modellist).most_common(5)
    network["swvers"] = Counter(swlist).most_common(5)
    return network

def deleteDevice(serial):
    """
    Call to DB to delete a device by serial number
    """
    swDB = switchdb.DB()
    swDB.deleteBySerial(serial)
    swDB.close()

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


#!/usr/bin/env python
"""
Storage import tool
===================

Import database content from a file.

"""
import logging

from orion.core.cli import base as cli
from orion.core.io import experiment_builder
from orion.storage.backup import load_database
from orion.storage.base import setup_storage

logger = logging.getLogger(__name__)

DESCRIPTION = "Import storage"

def add_subparser(parser):
    """Add the subparser that needs to be used for this command"""
    load_parser = parser.add_parser("load", help=DESCRIPTION, description=DESCRIPTION)

    cli.get_basic_args_group(load_parser)

    load_parser.add_argument(
        "file",
        type=str,
        help="File to import",
    )

    load_parser.add_argument(
        "-r",
        "--resolve",
        type=str,
        choices=("ignore", "overwrite", "bump"),
        help="Strategy to resolve conflicts: "
        "'ignore', 'overwrite' or 'bump' "
        "(bump version of imported experiment). "
        "When overwriting, prior trials will be deleted. "
        "If not specified, an exception will be raised on any conflict detected.",
    )

    load_parser.set_defaults(func=main)

    return load_parser

def main(args):
    """Script to import storage"""
    config = experiment_builder.get_cmd_config(args)
    storage = setup_storage(config.get("storage"))
    logger.info(f"Loaded dst {storage}")
    load_database(
        storage,
        load_host=args["file"],
        resolve=args["resolve"],
        name=config.get("name"),
        version=config.get("version"),
    )


#!/anaconda3/envs/FEALPy/bin python3.8
# -*- coding: utf-8 -*-
# ---
# @Software: PyCharm
# @Site:
# @File: totest_temp2.py
# @Author: Yongchao Zhang
# @E-mail: yoczhang@126.com
# @Time: Jun 24, 2020
# ---

from fealpy.functionspace.ScaledMonomialSpace2d import ScaledMonomialSpace2d
import numpy as np
import matplotlib.pyplot as plt
from fealpy.mesh.mesh_tools import find_entity

from fealpy.mesh import PolygonMesh
from fealpy.mesh import StructureQuadMesh, QuadrangleMesh
from fealpy.mesh import TriangleMesh, TriangleMeshWithInfinityNode
from fealpy.decorator import cartesian, barycentric

# --- mesh
n = 0
node = np.array([
    (0, 0),
    (1, 0),
    (1, 1),
    (0, 1)], dtype=np.float)
cell = np.array([
    (1, 2, 0),
    (3, 0, 2)], dtype=np.int)
mesh = TriangleMesh(node, cell)
mesh.uniform_refine(n)

# --- to pmesh
# nmesh = TriangleMeshWithInfinityNode(mesh)
# pnode, pcell, pcellLocation = nmesh.to_polygonmesh()
# pmesh = PolygonMesh(pnode, pcell, pcellLocation)
# mesh = pmesh

# ---- plot mesh ----
# fig1 = plt.figure()
# axes = fig1.gca()
# mesh.add_plot(axes, cellcolor='w')
# find_entity(axes, mesh, entity='cell', showindex=True, color='b', markersize=10, fontsize=8)
# find_entity(axes, mesh, entity='edge', showindex=True, color='r', markersize=10, fontsize=8)
# find_entity(axes, mesh, entity='node', showindex=True, color='y', markersize=10, fontsize=8)
# plt.show()
# plt.close()
# -------------------

p = 1
smspace = ScaledMonomialSpace2d(mesh, p)

# def f(x, index=None):
#     gphi = smspace.grad_basis(x, index=index)
#     gpphi = smspace.grad_basis(x, index=index, p=p+1)
#     return np.einsum('...mn, ...kn->...km', gphi, gpphi)
#
#
# S = smspace.integralalg.integral(f, celltype=True, barycenter=False)

# --- another test
uh = smspace.function()

@cartesian
def f1(x, index=np.s_[:]):
    return uh.value(x, index)

# S1 = smspace.integralalg.integral(f1, celltype=True)
S2 = smspace.integralalg.integral(f1, celltype=True, barycenter=False)
# S3 = smspace.integralalg.cell_integral(f1)

# ------------------------------------------------- #
print("End of this test file")


from dataclasses import dataclass, asdict

@dataclass
class Deportista:
    nombre: str
    altura: float
    peso: float

deportista1 = Deportista('Elena', 1.81, 64)
dicc1 = asdict(deportista1)

if dicc1['altura'] > 1.75:
   print(dicc1['nombre'], 'supera la altura')


from rest_framework import status

from core.fixtures.user import user
from core.fixtures.post import post

class TestPostPermissionViewSet:
    """Test suite for testing the permissions of CRUD operations on a Post model."""

    endpoint = "/api/post/"

    def test_list(self, client, user, post):
        """Test retrieving all posts."""
        response = client.get(self.endpoint)

        assert response.status_code == status.HTTP_200_OK
        assert response.data["count"] == 1

    def test_retrieve(self, client, user, post):
        """Test retrieving a specific post."""
        response = client.get(self.endpoint + f"{post.public_id}/")

        assert response.status_code == status.HTTP_200_OK
        assert response.data["title"] == post.title
        assert response.data["author"]["id"] == user.public_id.hex

    def test_create(self, client, user):
        """Test creating a new post."""
        data = {
            "author": user.public_id.hex,
            "title": "Simple title",
            "body": "Simple body",
        }

        response = client.post(self.endpoint, data)

        assert response.status_code == status.HTTP_401_UNAUTHORIZED

    def test_update(self, client, user, post):
        """Test updating an existing post."""
        data = {}
        response = client.put(self.endpoint + f"{post.public_id}/")

        assert response.status_code == status.HTTP_401_UNAUTHORIZED

    def test_delete(self, client, user, post):
        """Test deleting an existing post."""
        response = client.delete(self.endpoint + f"{post.public_id}/")

        assert response.status_code == status.HTTP_401_UNAUTHORIZED


# -*- coding: utf-8 -*-
from datetime import datetime
from osv import osv, fields
from tools.translate import _

class GiscedataPolissa(osv.osv):

    _name = "giscedata.polissa"
    _inherit = 'giscedata.polissa'

    def get_auto_bat_name(self, cursor, uid, polissa_id, polissa_name, context=None):
        if context is None:
            context = {}
        return "FS" + str(polissa_name)

    def is_autoconsum_amb_excedents(self, cursor, uid, autoconsumo, context=None):
        if context is None:
            context = {}
        if autoconsumo in ('41', '42', '43'):
            return True
        else:
            return False

    def get_bateria_virtual_data_inici_for_invoice(self, cursor, uid, factura, context=None):
        if context is None:
            context = {}
        bat_polissa_obj = self.pool.get("giscedata.bateria.virtual.origen")
        origen_ref = 'giscedata.polissa,{}'.format(factura.polissa_id.id)
        dates_inici = bat_polissa_obj.q(cursor, uid).read(['data_inici_descomptes']).where([('origen_ref', '=', origen_ref)])
        if dates_inici:
            data_inici_bateria = max([d['data_inici_descomptes'] for d in dates_inici])
        else:
            data_inici_bateria = False
        return data_inici_bateria

GiscedataPolissa()