import os
import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2

# defining global variable path
image_path = "recycled_set/train_unproc/plastic"

def loadImages(path):
    # Put files into lists and return them as one list of size 4
    image_files = sorted([os.path.join(path, file) for file in os.listdir(path) if file.endswith('.jpg')])
    return image_files

# Preprocessing
def processing(data):
    # loading image
    # Getting 3 images to work with
    #img = [cv2.imread(i, cv2.IMREAD_UNCHANGED) for i in data[:3]]

    img = [cv2.imread(i, cv2.IMREAD_UNCHANGED) for i in data[:]]
    #print(img)
    # --------------------------------
    # setting dim of the resize
    height = 250
    width = 250
    dim = (width, height)
    res_img = []
    for i in range(len(img)):
        res = cv2.resize(img[i], dim, interpolation=cv2.INTER_LINEAR)
        res_img.append(res)

    # Remove noise
    # Gaussian
    no_noise = []
    for i in range(len(res_img)):
        blur = cv2.GaussianBlur(res_img[i], (5, 5), 0)
        no_noise.append(blur)

    return no_noise

def main():
    # calling global variable
    global image_path
    '''The var Dataset is a list with all images in the folder '''
    dataset = loadImages(image_path)

    print("List of files the first 3 in the folder:\n",dataset[:3])
    print("--------------------------------")

    # sending all the images to pre-processing
    pro = processing(dataset)

    counter=0
    for i in pro:
        counter=counter+1
        cv2.imwrite(image_path+'plastic' +str(counter)+'.jpg', i)

main()


from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from .serializers import VideoSerializer, CommenterSerializer, GetVideoSerializer, UserSerializer
from rest_framework.response import Response
from rest_framework import status
from fake.models import *
import json
from controllers.modelControl import *
from moviepy.editor import VideoFileClip
from rest_framework.permissions import IsAuthenticated

# Create your views here.

class GetAllVideoView(ListAPIView):

    permission_classes = [IsAuthenticated]

    queryset = Video.objects.all()
    serializer_class = GetVideoSerializer

class GetAbonneCountView(APIView):

    def get(self, request):

        iduser = request.GET['iduser']

        user = Utilisateur.objects.get(id=iduser)

        numberAbonne = user.abonne.count()

        return Response(data={"message":numberAbonne}, status=status.HTTP_200_OK)

class VideoView(APIView):

    def post(self,request):

        form = VideoSerializer(data=request.data)
        if form.is_valid():
            url = form.validated_data.get('video')
            image = form.validated_data.get('coverImage')
            nom = form.validated_data.get('nom')
            description = form.validated_data.get('description')
            video = Video(video=url,coverImage=image,nom=nom,description=description,owner=request.user)
            video.save()
            video.refresh_from_db()
            clip = VideoFileClip(video.video.path)
            video.duree = clip.duration
            video.save()

            return Response({"message":"Ok"}, status=status.HTTP_201_CREATED)
        else:
            return Response({"error":form.errors}, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):

        idvideo = request.GET['id']

        video = Video.objects.get(id=idvideo)
        data = dict()

        data['url'] = video.video.url
        data['cover'] = video.coverImage.url
        data['vue'] = video.user_vue.count()
        data['like'] = video.user_like.count()
        #data['dislike'] = video.user_dislike.count()
        data['comment'] = video.commenter_set.count()
        data['idvideo'] = video.id
        try:
            data['userCover'] = video.owner.profilePicture.url
        except:
            pass
        data['username'] = video.owner.username
        data['date'] = str(video.date.date())
        data['heure'] = str(video.date.time())
        data['duree'] = video.duree
        data['nomVideo'] = video.nom

        #data = json.dumps(data)

        return Response(data=data, status=status.HTTP_200_OK)

class CommentaireView(APIView):

    """
    The comment !

    id:Id video
    """

    def get(self, request):
        """
        Parameters
        ----------
        name : str
            The name of the animal
        sound : str
            The sound the animal makes
        num_legs : int, optional
            The number of legs the animal (default is 4)
        """

        idvideo = request.GET['id']
        video = Video.objects.get(id=idvideo)

        serializer = CommenterSerializer(video.commenter_set.all(), many=True)

        return Response(data=serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        idvideo = request.data['idvideo']
        contenue = request.data['contenue']
        video = Video.objects.get(id=idvideo)

        commentaire = Commenter.objects.create(contenue=contenue, video=video, utilisateur=request.user)

        commentaire.save()

        return Response({"message":"ok"}, status=status.HTTP_200_OK)

class LikeVideoView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):

        idvideo = request.GET['idvideo']

        val = likeVideo(request, idvideo)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas like"}, status=status.HTTP_400_BAD_REQUEST)

class LikeComment(APIView):
    pass

class DislikeVideoView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):

        idvideo = request.GET['idvideo']

        val = dislikeVideo(request, idvideo)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas dislike"}, status=status.HTTP_400_BAD_REQUEST)

class DislikeComment(APIView):
    pass

class SabonneView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):

        username = request.GET['username']
        val = sabonne(request, username)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas abonne"}, status=status.HTTP_400_BAD_REQUEST)

class DesabonneView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):

        username = request.GET['username']
        val = desabonne(request, username)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas desabonne"}, status=status.HTTP_200_OK)

class PlaylistView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self, request):

        val = createPlaylist(request)

        return Response({"message":"ok"}, status=status.HTTP_200_OK)

class AddVideoPlaylistView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self, request):

        idvideo = request.data['idvideo']
        idplaylist = request.data['idplaylist']

        val = addVideoOnPlaylist(request, idvideo, idplaylist)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas ajouter"}, status=status.HTTP_400_BAD_REQUEST)

class DeleteVideoPlaylistView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self, request):

        idvideo = request.data['idvideo']
        idplaylist = request.data['idplaylist']

        val = addVideoOnPlaylist(request, idvideo, idplaylist)

        if val:
            return Response({"message":"ok"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"dejas suprimer"}, status=status.HTTP_400_BAD_REQUEST)

class UserView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):

        user = Utilisateur.objects.get(username=request.GET['username'])

        data = dict()

        data['username'] = user.username
        data['profilePicture'] = user.profilePicture.url

        #data = json.dumps(data)

        return Response(data=data, status=status.HTTP_200_OK)


import logging
import os
import re

LOG_LEVEL = {
    "INFO": logging.INFO,
    "DEBUG": logging.DEBUG,
    "WARNING": logging.WARNING,
}

level = LOG_LEVEL.get(os.environ.get("LOG_LEVEL"), LOG_LEVEL["INFO"])

logging.basicConfig(level=level, format="%(message)s")

PREFIXES = {
    "debug": "\x1b[1;33m",
    "warning": "\x1b[1;33m",
    "info": "\x1b[1;34m",
    "hint": "\x1b[3;35m",
    "success": "\x1b[1;32m",
    "error": "\x1b[1;31m",
}

class FancyLogger:

    TERMINATOR = "\x1b[0m"
    HEADER_DELIMITER = "="
    REPLACEMENTS = (
        (r"\/github\/workspace\/?", "./"),
        (r"PosixPath\('([^']*)'\)", r"\1"),
    )

    def __init__(self) -> None:
        self.logger = logging.getLogger("plone-code-analysis")

    def __getattr__(self, attr):
        """Catch all method."""
        return getattr(self.logger, attr)

    def _redact_msg(self, msg: str) -> str:
        """Clean up msg to be logged."""
        for pattern, replace in self.REPLACEMENTS:
            msg = re.sub(pattern, replace, msg)
        return msg

    def _log(self, level, msg, *args, **kwargs):
        fancy = kwargs.get("fancy", True)
        header_level = kwargs.get("header", None)
        kwargs = {k: v for k, v in kwargs.items() if k not in ("fancy", "header")}
        msg = self._redact_msg(msg)
        if fancy:
            if header_level:
                msg_len = len(msg)
                header = self.HEADER_DELIMITER * msg_len
                msg = f"{msg}\n{header}"
                msg = f"{header}\n{msg}" if header_level == 1 else msg
                msg = f"\n{msg}"
            prefix = PREFIXES.get(level, PREFIXES["info"])
            msg = f"{prefix}{msg}{self.TERMINATOR}"

        method = getattr(self.logger, level, getattr(self.logger, "info"))
        method(msg, *args, **kwargs)

    def success(self, msg, *args, **kwargs):
        """Info"""
        self._log("success", msg, *args, **kwargs)

    def info(self, msg, *args, **kwargs):
        """Info"""
        self._log("info", msg, *args, **kwargs)

    def debug(self, msg, *args, **kwargs):
        """Debug"""
        self._log("debug", msg, *args, **kwargs)

    def error(self, msg, *args, **kwargs):
        """Error"""
        self._log("error", msg, *args, **kwargs)

    def warning(self, msg, *args, **kwargs):
        """Warning"""
        self._log("warning", msg, *args, **kwargs)

logger = FancyLogger()


import numpy as np
import cv2
import cv2.aruco as aruco
import csv
import time
#np.load('calibration.pckl', allow_pickle=True)

cameraMatrix = np.load('cameraMatrix.npy')
distCoeffs = np.load('distCoeffs.npy')

cap = cv2.VideoCapture(0)
markerSize = 0.084
#f = open("robotPosition.csv", "a+")
#writer = csv.writer(f, delimiter=',')
while True:
    _, img = cap.read()
    # img=cv2.resize(img,(w,h))
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Pick the AruCo marker
    aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_ARUCO_ORIGINAL)#DICT_4X4_250)
    parameters = cv2.aruco.DetectorParameters_create()
    corners, ids, rejectedImgPoints = cv2.aruco.detectMarkers(imgGray, aruco_dict, parameters=parameters)
    if type(ids) is np.ndarray:
        # pass on the distortion and camera coefficients, and the marker size
        rvecs, tvecs, _objPoints = cv2.aruco.estimatePoseSingleMarkers(corners, markerSize, cameraMatrix, distCoeffs)
        #cv2.aruco.drawAxis(img, cameraMatrix, distCoeffs, rvecs , tvecs, 0.1)
        t = float(time.time())
        for i, id in enumerate(ids):
            cv2.drawFrameAxes(img, cameraMatrix, distCoeffs, rvecs[i] , tvecs[i], 0.1)
            data = [t, i, tvecs[i][0][0], tvecs[i][0][1], tvecs[i][0][2]]
           #writer.writerow(data)
    #f.flush()
    cv2.imshow("Output",img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


#!/usr/bin/env python3
import socket
import sys
import Class

TAM_MSG = 1024 # Tamanho do bloco de mensagem
HOST = '127.0.0.1' # IP do Servidor
PORT = 40000 # Porta que o Servidor escuta
if len(sys.argv) > 1:
    HOST = sys.argv[1]
print('Servidor:', HOST+':'+str(PORT))
serv = (HOST, PORT)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(serv)
print('Para sair use QUIT, Ctrl+D ou CTRL+C\n')
while True:
    print('''
         [1] - Cadastrar Novo modelo
         [2] - Pesquisar Modelos
         [3] - QUIT
        ''')
    try:
        cmd = input('Loja> ')
    except:
        cmd = '5'
    if cmd[0] == '1':

        marca = input('Digite a MARCA do Relógio:')
        modelo = input('Digite o MODELO do Relógio:')
        cor = input('Digite a COR do Relógio:')
        preco = input('Digite o PREÇO do Relógio:')
        descricao = input('Digite uma DESCRIÇÃO para o Relógio:')
        disponibilidade = input('Quantas Unidades estão disponíveis:')

        if input('Deseja Cadastrar? S/N: ').upper() == 'S':

            sock.send(str.encode('CNM {}, {}, {}, {}, {}, {}\n'.format(marca, modelo, cor, preco, descricao, disponibilidade)))

            dados = sock.recv(TAM_MSG)
            if not dados: break
            msg_status = dados.decode().split()

            if msg_status[0] == '+OK':
                print('Cadastro Realizado!')
            else:
                print('Erro ao Cadastrar!', msg_status[1:])

    elif cmd[0] == '2':
        modelo = input('Digite o MODELO do Relógio:')
        sock.send(str.encode('{} {}'.format('PM',modelo)))

        dados = sock.recv(TAM_MSG)
        if dados.decode() != '-ERR':
            linha = dados.decode().split(',')
            bonito = Class.Relogio(linha[0],linha[1],linha[2],linha[3],linha[4],linha[5])
            print(bonito)
        else:
            print('Modelo não emcontrado!')

    elif cmd[0] == '3':
        break

sock.close()


#  Q.1- Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is inheriting Animal and access the base class method.

class animal:
    """
    A class which contains properties of animals

    attributes:
    legs : int
    ears : int
    cat_family: bool
    age : int
    """
    def animal_attribute(self,legs,ears,cat_family,age):
        self.legs = legs
        self.ears = ears
        self.cat_family = cat_family
        self.age = age
        print("legs: ",legs)
        print("ears: ", ears, "\nFrom cat_family: ",cat_family,"\nage: ",age)

class tiger(animal):
    def __init__(self):
        print("A tiger is born")

new_tiger = tiger()
new_tiger.animal_attribute(4,2,True,1)

print('__'*40)

# Q.2- What will be the output of following code.

print("Output:")
print("A B\nA B")

print('__'*40)

# Q.3- Create a class Cop. Initialize its name, age , work experience and designation. Define methods to add, display and update the following details.
# Create another class Mission which extends the class Cop. Define method add_mission _details.
# Select an object of Cop and access methods of base class to get information for a particular cop and make it available for mission.

class Cop():
    def add(self):
        self.name = input(("enter name:"))
        self.age = int(input("enter the age:"))
        self.work_expr = int(input("enter the work experience in years:"))
        self.designation = input("enter the designation:")

    def display(self):
        print("name of this cop: %s\nage of this cop: %d\nwork_experience: %d\ndesignation: %s" % (self.name, self.age, self.work_expr, self.designation))

    def update(self):
        self.name = input(("enter new name:"))
        self.age = int(input("enter the new age:"))
        self.work_expr = int(input("enter the new work experience in years:"))
        self.designation = input("enter the new designation:")

class Mission(Cop):
    mission_name = ''
    mission_duration = ''
    mission_place = ''

    def add_mission_details(self):
        mission_name = input("Enter the mission name:")
        mission_duration = int(input("Enter mission duration in months: "))
        mission_place = input("Enter country for mission: ")

m = Mission()
print("Add data")
m.add()
print("\nshowing added data......")
m.display()
print("\ntime to update data.....")
m.update()
print("\nupdated data below")
m.display()

# Q.4- Create a class Shape.Initialize it with length and breadth Create the method Area. Create class rectangle and square which inherits shape and access the method Area.
print('__'*40)
class Shape:
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return (self.length * self.breadth)

class rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

class square(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

r = rectangle(2, 3)
print("area of rectangle:", r.area())

s = square(5, 5)
print("area of square:", s.area())


# NEURAL_NET_IMPL.PY
# includes functions for moving data through neural network, training
# network, and initiliazing network
# framework from CS181 pset, implemantion of each function by us

from neural_net import NeuralNetwork, NetworkFramework
from neural_net import Node, Target, Input, Weight
from data_reader import *
import random

# run input through network
def FeedForward(network, input):

  network.CheckComplete()

  # set input values
  for i in range(len(input.values)):
    network.inputs[i].raw_value = input.values[i]
    network.inputs[i].transformed_value = input.values[i]
  # push to hidden layer
  for hidden in network.hidden_nodes:
    hidden.raw_value = network.ComputeRawValue(hidden)
    hidden.transformed_value = network.Sigmoid(hidden.raw_value)
  # push to output
  for out in network.outputs:
    out.raw_value = network.ComputeRawValue(out)
    out.transformed_value = network.Sigmoid(out.raw_value)

# run input through network and adjust weights accordingly
def Backprop(network, input, target, learning_rate):
  network.CheckComplete()

  # run input through network
  FeedForward (network,input)

  # calculate error, delta, and epsilon values for each node
  for i in range(len(network.outputs)):
    err = target[i] - network.outputs[i].transformed_value
    network.outputs[i].delta = \
      network.SigmoidPrime(network.outputs[i].raw_value) * err
  for node in network.hidden_nodes:
    eps = 0
    for j in range(len(node.forward_neighbors)):
      eps += node.forward_weights[j].value * node.forward_neighbors[j].delta
    node.delta = network.SigmoidPrime(node.raw_value) * eps

  # update hidden layer weights
  for hid in network.hidden_nodes:
    change = learning_rate * hid.transformed_value
    for j in range(len(hid.forward_weights)):
      hid.forward_weights[j].value += change * hid.forward_neighbors[j].delta

  # update input layer weights
  for inp in network.inputs:
    change = learning_rate * inp.transformed_value
    for j in range(len(inp.forward_weights)):
      inp.forward_weights[j].value += change * inp.forward_neighbors[j].delta

# trains neural network
def Train(network, inputs, targets, learning_rate, epochs):
  network.CheckComplete()
  for i in range(epochs):
    for j in range(len(inputs)):
      Backprop(network, inputs[j], targets[j], learning_rate)

class EncodedNetworkFramework(NetworkFramework):
  def __init__(self):
    super(EncodedNetworkFramework, self).__init__()

  # gives correct label to training/validation sets
  def EncodeLabel(self, label):
    l = [0.0] * 53
    l[label] = 1.0
    return l

  # returns label best fitting output
  def GetNetworkLabel(self):
    outputs = []
    for out in self.network.outputs:
      outputs.append(out.transformed_value)
    return outputs.index(max(outputs))

  # turns an image into an input vector of normalized pixel values
  def Convert(self, image):
    outer = []
    for i in image.pixels:
      for j in i:
        outer.append(j/256.0)
    inp = Input()
    inp.values = outer
    return inp

  # randomize weights to begin training
  def InitializeWeights(self):
    for wgt in self.network.weights:
      wgt.value = random.uniform(-0.01, 0.01)

#network setup: 400 inputs, 60 hidden, 53 ouput nodes
class CustomNetwork(EncodedNetworkFramework):
  def __init__(self):
    super(CustomNetwork, self).__init__()

    for i in range(400):
      self.network.AddNode((Node()), NeuralNetwork.INPUT)
    for j in range(60):
      self.network.AddNode((Node()), NeuralNetwork.HIDDEN)
    for k in range(53):
      self.network.AddNode((Node()), NeuralNetwork.OUTPUT)
    for output in self.network.outputs:
      for hid in self.network.hidden_nodes:
        output.AddInput(hid, None, self.network)
    for hid in self.network.hidden_nodes:
      for inp in self.network.inputs:
        hid.AddInput(inp, None, self.network)


from dataclasses import dataclass
from typing import List

import numpy as np
import openai

from airouter.openai_utils.cache import FileCache

EMBEDDING_MODEL = 'text-embedding-ada-002'

def vector_similarity(x: List[float], y: List[float]) -> float:
    return float(np.dot(np.array(x), np.array(y)))

@dataclass
class EmbeddedText:
    text: str
    embedding: List[float]

@FileCache(cache_file='embeddings.pkl', save_interval=1)
async def get_embeddings(strings: List[str]) -> List[EmbeddedText]:
    response = await openai.Embedding.acreate(
        model=EMBEDDING_MODEL,
        input=strings,
    )
    result = []
    for string, embedding_openai in zip(strings, response['data']):
        embedding = embedding_openai.embedding
        result.append(EmbeddedText(string, embedding))
    return result


import pygame

pygame.init()

window = pygame.display.set_mode((1200, 400))

track = pygame.image.load('track1.png')
car = pygame.image.load('tesla.png')
car =pygame.transform.scale(car, (200, 400))

while True:
    window.blit(track, (0,0))
    window.blit(car, (0,0))
    pygame.display.update()


# Name: Packet wait play sound
# Description: Add a packet wait entry to play a sound when trade window is opened
# Author: Reetus
# Era: Any

from Assistant import Engine
from ClassicAssist.UO.Network.PacketFilter import *

pwe = Engine.PacketWaitEntries.Add(PacketFilterInfo(0x6F), PacketDirection.Incoming, True)

pwe.Lock.WaitOne()

while True:
    PlaySound("Bike Horn.wav")
    Pause(1000)


# -*- coding: utf-8 -*-
__author__ = 'plemberger'

from sklearn.cross_validation import cross_val_score
from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn.linear_model import SGDClassifier
import xgboost as xgb
from sklearn.externals import joblib

from load_and_reshape import *

import os

# global variables
clf = None
proba_predicted = None
y_predicted = None
X_train = None
X_test = None
y_train = None

# loading the prepared train and test data for DepartmentDescription features
def load_prepared_data_DD():
    global X_train
    global X_test
    global y_train

    X_train = pd.read_csv(X_train_file_DD, index_col ='VisitNumber')
    y_train = pd.read_csv(y_train_file, index_col = 'VisitNumber')['TripType']
    X_test = pd.read_csv(X_test_file_DD, index_col ='VisitNumber')

    return

# loading the prepared train and test data for FinelineNumber features
def load_prepared_data_FL():
    global X_train
    global X_test
    global y_train

    X_train = pd.read_csv(X_train_file_FL, index_col ='VisitNumber')
    print('--> loading X_train done!')

    y_train = pd.read_csv(y_train_file, index_col = 'VisitNumber')['TripType']
    print('--> loading y_train done!')

    X_test = pd.read_csv(X_test_file_FL, index_col ='VisitNumber')
    print('--> loading X_test done!')
    return

# create and fit a classifier
def fit_model():
    global clf
    print('--> fitting started')

    #clf = SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, n_iter=5, random_state=42)
    #clf = RandomForestClassifier(n_estimators=50, max_depth=None, min_samples_split=1, random_state=0, verbose=2)
    #clf = LogisticRegression(verbose=2, solver = 'lbfgs', multi_class = 'multinomial', max_iter = 500)
    clf = xgb.XGBClassifier(silent =  False)
    clf = clf.fit(X_train, y_train)
    print('--> fitting done!')

    joblib.dump(clf, '/Users/pirminlemberger/PycharmProjects/Walmart/classifiers/LR_lbfgs_with_FL.pkl')
    print('--> model saved!')

    return

# predict TripTypes values using the trained classifier
def predict_values():
    global y_predicted

    y_predicted = pd.Series(clf.predict(X_test))
    y_predicted.index = X_test.index
    if os.path.exists(y_predicted_file):
        os.remove(y_predicted_file)
    y_predicted.to_csv(y_predicted_file, header = ['TripType'])
    print('--> predicting y values done!')
    return

# predict TripTypes probabilities using the trained classifier
def predict_probabilities():
    global proba_predicted

    print('--> start computation of probabilities!')
    proba_predicted = pd.DataFrame(clf.predict_proba(X_test))
    proba_predicted.index = X_test.index
    print('--> predicting y probabilities done!')
    return

# write submission file according to Kaggle specified format
def write_submission_file():

    def create_header(n):
        return 'TripType_' + str(n)

    cols = pd.Series(clf.classes_).astype(int)
    cols = cols.map(create_header)
    proba_predicted.columns = cols

    if os.path.exists(proba_predicted_file):
        os.remove(proba_predicted_file)
    proba_predicted.to_csv(proba_predicted_file)
    print('--> submission file written!')
    return

# perform a cross-validation using the selected classifier
def cross_validate():
    scores = cross_val_score(clf, X_train, y_train, cv=3, scoring='log_loss')
    print('--> cross validation done, score = {}'.format(-scores.mean()))

# compute features importance (available for RF and XGB)
def compute_feature_importance():
    # XGB
    xgb.plot_importance(clf)
    feature_importances = clf.booster().get_fscore()
    feature_importances = pd.Series(feature_importances).sort_values()

    # RF and other classifiers
    #feature_names = X_train.columns
    #importances = clf.feature_importances_
    #feature_importances = pd.Series(data=importances, index=feature_names)
    #feature_importances = feature_importances.sort_values()

    print('--> feature importances:')
    print(feature_importances)
    return

# use a grid search CV to optimize hyper-parameters of selected classifier
def optimize_params():
    global clf

    # XGB
    parameters_to_try = [{'learning_rate':0.1, 'n_estimators':100}, {'learning_rate':0.2, 'n_estimators':50}]
    clf = xgb.XGBClassifier(seed=0)

    # RF
    #parameters_to_try = {'n_estimators': [250, 500], 'max_depth': [10, None]}
    #clf = RandomForestClassifier(random_state=0, verbose=2)

    grid_clf = GridSearchCV(clf, parameters_to_try, cv=3, scoring='log_loss')
    grid_clf.fit(X_train, y_train)

    print('--> cross validation done!')

    print('--> best parameters:')
    print(clf.best_params_)
    print()

    print('--> scores for all combinations of parameters:')
    print(clf.grid_scores_)
    print()
    return


from .aws import AWSContext
from .config import ConfigContext
from .stack import StackContext
from .view import ViewContext
from .gem import GemContext
from .resource_group_context import ResourceGroupController
from .resource_type_context import ResourceTypeContext
from .stack_info_manager_context import StackInfoManagerContext
from .hook import HookContext

class Context(object):
    '''Aggregates objects that provide a context for performing Lumberyard resource management operations.'''

    def __init__(self, metricsInterface, view_class=ViewContext):
        self.metrics = metricsInterface
        self.view = view_class(self)
        self.aws = AWSContext(self)
        self.stack = StackContext(self)
        self.config = ConfigContext(self)
        self.gem = GemContext(self)
        self.resource_group_controller = ResourceGroupController(self)
        self.resource_groups = self.resource_group_controller.resource_groups
        self.hooks = HookContext(self)
        self.resource_types = ResourceTypeContext(self)
        self.stack_info = StackInfoManagerContext(self)

    # bootstrap order matters
    def bootstrap(self, args):
        self.view.bootstrap(args)
        self.config.bootstrap(args)
        self.gem.bootstrap(args)
        self.resource_group_controller.bootstrap(args)

    # initialization order matters
    def initialize(self, args):
        self.view.initialize(args)
        self.aws.initialize(args)
        self.stack.initialize(args)
        self.config.initialize(args)
        self.resource_group_controller.initialize(args)

    def __str__(self):
        return '[ config: {config} ]'.format(config=self.config)


import sys
#sys.stdin=open("input.txt", "rt")
'''
n,k = map(int, input().split())
a = list(map(int, input().split()))

seq = []
for i in range(n):
    for j in range(i+1,n):
        for l in range(j+1,n):
            summ = a[i]+a[j]+a[l]
            seq.append(summ)
seq.sort(reverse=True)
print(seq[k-1])
'''
n,k = map(int, input().split())
a = list(map(int, input().split()))

res=set() # 중복 제거하는 자료구조

for i in range(n):
    for j in range(i+1,n):
        for m in range(j+1,n):
            res.add(a[i]+a[j]+a[m]) # res는 append가 아니라 add
res = list(res) # res는 list가 아니라 list화 해야함
res.sort(reverse=True)
print(res[k-1])

'''
1. set -> 중복 제거하는 자료구조 / 이걸 몰라서 중복 처리가 안됨
    -> input에서 중복은 별 상관이 없나보다 / output만 중복처리
    -> set 자료구조 익히기(add, not list)
'''


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Socker Programming - Multi Connection Server"""

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

import numpy as np
import pandas as pd
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt

url = 'https://fred.stlouisfed.org/graph/fredgraph.csv?id=VIXCLS'
vix = pd.read_csv(url,
                  index_col=0,
                  parse_dates=True,
                  na_values='.',
                  infer_datetime_format=True,
                  squeeze=True).dropna()
ma = vix.rolling('90d').mean()
state = pd.cut(ma, bins=[-np.inf, 14, 18, 24, np.inf], labels=range(4))

cmap = plt.get_cmap('RdYlGn_r')
ma.plot(color='black',
        linewidth=1.5,
        marker='',
        figsize=(8, 4),
        label='VIX 90d MA')
ax = plt.gca()  # Get the current Axes that ma.plot() references
ax.set_xlabel('')
ax.set_ylabel('90d moving average: CBOE VIX')
ax.set_title('Volatility Regime State')
ax.grid(False)
ax.legend(loc='upper center')
ax.set_xlim(xmin=ma.index[0], xmax=ma.index[-1])

trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
for i, color in enumerate(cmap([0.2, 0.4, 0.6, 0.8])):
    ax.fill_between(ma.index,
                    0,
                    1,
                    where=state == i,
                    facecolor=color,
                    transform=trans)
ax.axhline(vix.mean(),
           linestyle='dashed',
           color='xkcd:dark grey',
           alpha=0.6,
           label='Full-period mean',
           marker='')

plt.show()


import os
import logging

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required

from blog.models import PostModel, CommentModel, CategoryModel
from blog.forms import AddPostForm, UpdatePostForm, AddCommentForm

def post(request, slug):
    """ viewing post detail """
    post = get_object_or_404(PostModel, slug=slug)
    comments = post.p_comments.all()
    if request.method == 'POST':
        comment_form = AddCommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = CommentModel()
            new_comment.author = request.user
            new_comment.post = post
            new_comment.content = comment_form.cleaned_data['content']
            new_comment.save()
        if request.user.is_authenticated:
            logger = logging.getLogger('comment_added')
            logger.info(f'post-slug: {post.slug}, user: {request.user.username}')
        messages.success(request, 'Yeni yorum eklendi.')
        return redirect('post_url', slug=post.slug)
    else:
        comment_form = AddCommentForm()
    context={
        'post' : post,
        'comments' : comments,
        'comment_form' : comment_form,
    }
    if request.user.is_authenticated:
        logger = logging.getLogger('post_viewed')
        logger.info(f'post-slug: {slug}, user: {request.user.username}')
    return render(request, 'post.html', context)

@staff_member_required(login_url='/')
def add_post(request):
    """ adding new post """
    form = AddPostForm(request.POST or None, request.FILES or None)
    print('\n\n')
    print('method', request.method)
    if request.method == "POST":
        print('post')
        form = AddPostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            new_post = PostModel()
            new_post.title = cd['title']
            new_post.image = request.FILES['image']
            new_post.author = request.user
            new_post.content = cd['content']
            new_post.save()
            for id in cd['categories']:
                category = CategoryModel.objects.get(id=id)
                new_post.categories.add(category)
            messages.success(request, 'Yeni gönderi eklendi.')
            if request.user.is_authenticated:
                logger = logging.getLogger('post_added')
                logger.info(f'post-slug: {new_post.slug}, user: {request.user.username}')
            return redirect('post_url', slug=new_post.slug)
    context = {
        'form' : form,
    }
    return render(request, 'add_post.html', context)

@staff_member_required(login_url='/')
def update_post(request, slug):
    """ updating old post """
    print(request.GET)
    post = get_object_or_404(PostModel, slug=slug, author=request.user)
    initial = {
        'title' : post.title,
        'image' : post.image,
        'content' : post.content,
    }
    post_categories = CategoryModel.objects.filter(c_post=post)
    initial['categories'] = list(category.id for category in post_categories)
    form = UpdatePostForm(
        request.POST or None,
        request.FILES or None,
        initial=initial
    )
    if request.method == "POST":
        if form.is_valid():
            cd = form.cleaned_data
            post.title = cd['title']
            if request.FILES:
                if post.image:
                    os.remove(post.image.path)
                post.image = request.FILES['image']
            post.content = cd['content']
            post.categories.clear()
            for id in cd['categories']:
                category = CategoryModel.objects.get(id=id)
                post.categories.add(category)
            post.save()
            messages.success(request, 'Gönderi başarıyla güncellendi.')
            if request.user.is_authenticated:
                logger = logging.getLogger('post_updated')
                logger.info(f'post-slug: {slug}, user: {request.user.username}')
            return redirect('post_url', slug=post.slug)
    context = {
        'post' : post,
        'form' : form,
    }
    return render(request, 'update_post.html', context)

@staff_member_required(login_url='/')
def delete_post(request, slug):
    """ deleting a post """
    post = get_object_or_404(PostModel, slug=slug, author=request.user).delete()
    messages.success(request, 'Gönderi başarıyla silindi.')
    if request.user.is_authenticated:
        logger = logging.getLogger('post_deleted')
        logger.info(f'post-slug: {slug}, user: {request.user.username}')
    return redirect('my_posts_url')


import pandas as pd
import sklearn.preprocessing
import sklearn.utils
import numpy as np
import sklearn.gaussian_process.kernels
import keras
import matplotlib.pyplot as plt

def figure_formatting(): # make the plot look xmgrace-esque
    font = {'family': 'sans-serif', 'weight': 'bold', 'size': 18}
    plt.rcParams['font.sans-serif'] = ['Arial']
    plt.rc('font', **font)
    plt.rcParams['axes.linewidth'] = 2.5
    plt.rcParams['xtick.major.size'] = 10
    plt.rcParams['xtick.major.width'] = 2.5
    plt.rcParams['ytick.major.size'] = 10
    plt.rcParams['ytick.major.width'] = 2.5
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    plt.rcParams['mathtext.default'] = 'regular'
    plt.rcParams['legend.fancybox'] = False # no rounded legend box

figure_formatting()

descriptors = ["A1", "A2", "A3", "A4"]  # Note: change as needed

def normalize_data(df_train, df_test, fnames, lname, unit_trans=1, debug=False):
    _df_train = df_train.copy().dropna(subset=fnames + lname)
    _df_test = df_test.copy().dropna(subset=fnames + lname)
    X_train, X_test = _df_train[fnames].values, _df_test[fnames].values
    y_train, y_test = (
        _df_train[lname].values * unit_trans,
        _df_test[lname].values * unit_trans,
    )
    if debug:
        print(
            "training data reduced from %d -> %d because of nan."
            % (len(df_train), y_train.shape[0])
        )
        print(
            "test data reduced from %d -> %d because of nan."
            % (len(df_test), y_test.shape[0])
        )
    x_scaler = sklearn.preprocessing.StandardScaler()
    x_scaler.fit(X_train)
    X_train = x_scaler.transform(X_train)
    X_test = x_scaler.transform(X_test)
    y_scaler = sklearn.preprocessing.StandardScaler()
    y_scaler.fit(y_train)
    y_train = y_scaler.transform(y_train)
    y_test = y_scaler.transform(y_test)
    for ii, ln in enumerate(lname):
        if debug:
            print(
                (
                    "mean in target: %s, train/test: %f/%f"
                    % (ln, np.mean(y_train[:, ii]), np.mean(y_test[:, ii]))
                )
            )
    return X_train, X_test, y_train, y_test, x_scaler, y_scaler

def main():

    df = pd.read_csv("4-4-2-asym-AB-AC_rs_0.csv")
    df_train = df[df["bin"] == "train"]
    df_val = df[df["bin"] == "val"]
    df_train_all = df_train.append(df_val)
    df_test = df[df["bin"] == "test"]

    fnames = descriptors
    lname = ["C1"]  # Note: change as needed

    X_train, X_test, y_train, y_test, x_scaler, y_scaler = normalize_data(
        df_train_all, df_test, fnames, lname, unit_trans=1, debug=True
    )

    model = keras.models.load_model(
        f"quant_ANN_{lname[0]}.h5", compile=False
    )  # Note: change as needed

    predictions = y_scaler.inverse_transform(model.predict(X_test))

    ### Will append the predictions to the dataframe df_test, and save to an Excel file

    df_predictions = pd.DataFrame(
        predictions, columns=["Prediction"]
    )  # making the predictions into a pandas dataframe, in order to append
    df_predictions.reset_index(drop=True, inplace=True)
    df_test.reset_index(drop=True, inplace=True)

    df_predictions = pd.concat(
        [df_predictions, df_test], axis=1
    )  # combining test data with the predictions, column wise

    # Reordering the columns of the dataframe
    column_order = ["C1", "C2", "Prediction"] + descriptors
    df_predictions = df_predictions[column_order]

    # Writing it all to a csv

    df_predictions.to_csv(f"predictions_{lname[0]}.csv", index=False)

    ### Making a parity plot

    truth_values = df_predictions[lname[0]]  # Note: change as needed
    prediction_values = df_predictions["Prediction"]

    truth_values = [item * 1E6 for item in truth_values] # Converting to micromolar
    prediction_values = [item * 1E6 for item in prediction_values]

    plt.scatter(truth_values, prediction_values)
    plt.xlabel('Truth (\u03BCM)', fontweight='bold')
    plt.ylabel('Prediction (\u03BCM)', fontweight='bold')
    plt.xticks([0.00, 0.25, 0.50, 0.75, 1.00, 1.25, 1.50])
    plt.title('Parity plot for P$_1$', fontweight='bold') # Note: change as needed
    plt.savefig(f'{lname[0]}_parityplot.png', format='png', bbox_inches='tight', dpi=300)
    plt.savefig(f'{lname[0]}_parityplot.eps', format='eps', bbox_inches='tight') # saving as a vector plot

if __name__ == "__main__":
    main()


# В заданном списке вещественных чисел найдите разницу между
# максимальным и минимальным значением дробной части элементов.
# Пример: [1.1, 1.2, 3.1, 5, 10.01] => 0.19

def diff_max_min(ls: list) -> float:
    sortedls = []
    for i in ls:
        n = round((float(i) % 1), 2)
        sortedls.append(n)
    print(sortedls)
    sortedls.sort()
    print(sortedls)
    for i in sortedls:
        if i > 0:
            return sortedls[-1] - i

print(diff_max_min([10, 2.005, 5.019, 1.1, 1.2, 3.1, 5, 10.01]))


#!/usr/bin/python3

#load the parameters stored in local file of following format:
#username=[username]
#password=[password]
#url=https://exofop.ipac.caltech.edu/tess/password_check.php
#status='' This value is used for internal testing and can be ignored or excluded

def ExoFOP_parameters(file_name):
   params={}
   params['status']=''
   with open(file_name) as fp:
      for line in fp:
         line=line.strip()
         items=line.split('=')
         params[items[0]]=items[1]
   params['cookie']='exocookies_'+params['username']+params['status']+'.txt'
   return params

def get_private_table(table_url, params):
   response=requests.get(url, cookies=params['cookie'])
   soup=BeautifulSoup(response.text, "lxml")
   for script in soup(["script", "style"]):
      script.decompose()
   stripped_text=soup.get_text()
   TESTDATA=StringIO(stripped_text)
   df_csv=pd.read_csv(TESTDATA, index_col=0, delimiter=",",  warn_bad_lines=True)#, error_bad_lines=False)#, usecols=['ID', 'TIC ID', 'Username', 'TAG ID', 'notes'])
   return df_csv

if __name__ == '__main__':
   import sys
   params=ExoFOP_parameters(sys.argv[1])
   print(params)
   print(get_private_table(table_url, params))


from typing import List

class Solution:
    def smallestSubarrays(self, nums: List[int]) -> List[int]:
        res = [1] * len(nums)
        for i, x in enumerate(nums):
            for j in range(i - 1, -1, -1):
                if nums[j] | x == nums[j]:
                    break
                nums[j] |= x
                res[j] = i - j + 1
        return res


from datetime import datetime

from sqlalchemy import (JSON, TIMESTAMP, Boolean, Column, ForeignKey, Integer,
                        MetaData, String, Table, Enum)
from sqlalchemy.dialects.postgresql import JSONB

from src.database import Base, metadata

import enum

class LoadTools(enum.Enum):
    locust = 1
    yandex_tank = 2

class Product(Base):
    __tablename__ = 'product'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    description = Column(String, nullable=True)

class LoadTestDescribe(Base):
    __tablename__ = 'load_test_describe'

    id = Column(Integer, primary_key=True)
    product_id = Column(Integer, ForeignKey(Product.id))
    name = Column(String, nullable=False)
    description = Column(String, nullable=True)

class LoadTestResult(Base):
    __tablename__ = 'load_test_result'

    id = Column(Integer, primary_key=True)
    test_id = Column(Integer, ForeignKey(LoadTestDescribe.id))
    data = Column(JSONB, nullable=True)
    type_load_tool = Column(Enum(LoadTools), nullable=True)
    upload_time = Column(TIMESTAMP, default=datetime.utcnow)
    test_time_start = Column(TIMESTAMP, nullable=False)
    test_time_end = Column(TIMESTAMP, nullable=False)
    successful_result_test = Column(Boolean, default=None)
    calculated_test = Column(Boolean, default=False)

class LoadTestResultSummary(Base):
    __tablename__ = 'load_test_result_summary'

    id = Column(Integer, primary_key=True)
    test_id = Column(Integer, ForeignKey(LoadTestDescribe.id))
    data = Column(JSONB)
    upload_time = Column(TIMESTAMP, default=datetime.utcnow)
    test_time_start = Column(TIMESTAMP, nullable=False)
    test_time_end = Column(TIMESTAMP, nullable=False)
    successful_result_test = Column(Boolean, default=None)
    calculated_test = Column(Boolean, default=False)


N = input()
arr = [int(x) for x in input().split(" ")]

cmax = 0
ans = 0
for i in range(len(arr)):
	cmax = max(cmax, arr[i])
	ans += cmax - arr[i]

print(ans)


from spack import *
from os import remove as rm

class Face(Package):
    """Fortran Ansi Colors (and Styles) Environment."""

    homepage = "https://github.com/szaghi/FACE"
    url      = "https://github.com/szaghi/FACE/archive/v1.0.1.tar.gz"

    version('1.0.1', 'c0e3a48c1d459137674e66f729282545')
    version('1.0.0', '2716d4215cf44d4cafc50fbb433c3260')

    variant('shared', default=True, description='Build shared libraries')
    variant('static', default=True, description='Build static library')
#    variant('docs', default=True, description='Generate API documentation.')

    depends_on('py-fobis-py', type='build')
#    depends_on('py-ford', type='build', when='+docs')

    def install(self, spec, prefix):
        fobis = which('FoBiS.py')
        command = ["build", "-ch", "-dbld", "."]
        compiler = ["-fc", "${FC}", "-compiler"]
        cflags = "-c"
        lflags = ""
        cflags_shared = " "
        lflags_shared = " "
        target = ["-t", "face.f90"]

        mkdirp(prefix.lib, prefix.include)

        rm("fobos")
        if spec.satisfies('%gcc'):
            compiler.append("gnu")
            cflags += " -Ofast -frealloc-lhs -std=f2008 -fall-intrinsics"
            lflags += " -Ofast"
            cflags_shared += " -fPIC"
            lflags_shared += " -shared "
        elif spec.satisfies('%intel'):
            compiler.append("intel")
            cflags += " -fast -assume realloc_lhs -standard-semantics -std08"
            lflags += " -fast"
            cflags_shared += " -fpic"
            lflags_shared += " -shared"
        else:
            raise InstallError("Unsported compiler.")

        if spec.satisfies('+shared'):
            libname = 'libface.so'
            soname = libname + '.' + spec.version.up_to(1)
            filename = libname + '.' + spec.version.dotted
            fobis_options = command + compiler + \
                            ["-cflags", cflags + cflags_shared] + \
                            ["-lflags", lflags + lflags_shared +
                             '-Wl,-soname,' + soname] + \
                            ["-mklib", "shared"] + target + \
                            ["-o", filename]
            fobis(*fobis_options)
            install(filename, prefix.lib)
            with working_dir(prefix.lib):
                ln = which('ln')
                ln('-s', filename, soname)
                ln('-s', soname, libname)

        if spec.satisfies('+static'):
            fobis_options = command + compiler + ["-cflags", cflags] + \
                            ["-lflags", lflags] + ["-mklib", "static"] + \
                            target + ["-o", "libface.a"]
            fobis(*fobis_options)
            install('libface.a', prefix.lib)

        if spec.satisfies('+shared') or spec.satisfies('+static'):
            install(join_path('mod', 'face.mod'), prefix.include)


import boto3
import botocore
from botocore.exceptions import BotoCoreError, ClientError, NoCredentialsError, PartialCredentialsError, ParamValidationError, WaiterError
import loguru
from loguru import logger
import os
import io
import pandas as pd
import numpy as np
from datetime import timedelta

AWS_ACCESS_KEY_ID=os.environ['AWS_ACCESS_KEY']
AWS_SECRET_ACCESS_KEY=os.environ['AWS_ACCESS_SECRET']

# ---------------------------------------
# FUNCTIONS
# ---------------------------------------

# FUNCTION TO EXECUTE ATHENA QUERY AND RETURN RESULTS
# ----------

def run_athena_query(query:str, database: str, region:str):

    # Initialize Athena client
    athena_client = boto3.client('athena',
                                 region_name=region,
                                 aws_access_key_id=AWS_ACCESS_KEY_ID,
                                 aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

    # Execute the query
    try:
        response = athena_client.start_query_execution(
            QueryString=query,
            QueryExecutionContext={
                'Database': database
            },
            ResultConfiguration={
                'OutputLocation': 's3://prymal-ops/athena_query_results/'  # Specify your S3 bucket for query results
            }
        )

        query_execution_id = response['QueryExecutionId']

        # Wait for the query to complete
        state = 'RUNNING'

        while (state in ['RUNNING', 'QUEUED']):
            response = athena_client.get_query_execution(QueryExecutionId = query_execution_id)
            logger.info(f'Query is in {state} state..')
            if 'QueryExecution' in response and 'Status' in response['QueryExecution'] and 'State' in response['QueryExecution']['Status']:
                # Get currentstate
                state = response['QueryExecution']['Status']['State']

                if state == 'FAILED':
                    logger.error('Query Failed!')
                elif state == 'SUCCEEDED':
                    logger.info('Query Succeeded!')

        # OBTAIN DATA

        # --------------

        query_results = athena_client.get_query_results(QueryExecutionId=query_execution_id,
                                                MaxResults= 1000)

        # Extract qury result column names into a list

        cols = query_results['ResultSet']['ResultSetMetadata']['ColumnInfo']
        col_names = [col['Name'] for col in cols]

        # Extract query result data rows
        data_rows = query_results['ResultSet']['Rows'][1:]

        # Convert data rows into a list of lists
        query_results_data = [[r['VarCharValue'] for r in row['Data']] for row in data_rows]

        # Paginate Results if necessary
        while 'NextToken' in query_results:
                query_results = athena_client.get_query_results(QueryExecutionId=query_execution_id,
                                                NextToken=query_results['NextToken'],
                                                MaxResults= 1000)

                # Extract quuery result data rows
                data_rows = query_results['ResultSet']['Rows'][1:]

                # Convert data rows into a list of lists
                query_results_data.extend([[r['VarCharValue'] for r in row['Data']] for row in data_rows])

        results_df = pd.DataFrame(query_results_data, columns = col_names)

        return results_df

    except ParamValidationError as e:
        logger.error(f"Validation Error (potential SQL query issue): {e}")
        # Handle invalid parameters in the request, such as an invalid SQL query

    except WaiterError as e:
        logger.error(f"Waiter Error: {e}")
        # Handle errors related to waiting for query execution

    except ClientError as e:
        error_code = e.response['Error']['Code']
        error_message = e.response['Error']['Message']

        if error_code == 'InvalidRequestException':
            logger.error(f"Invalid Request Exception: {error_message}")
            # Handle issues with the Athena request, such as invalid SQL syntax

        elif error_code == 'ResourceNotFoundException':
            logger.error(f"Resource Not Found Exception: {error_message}")
            # Handle cases where the database or query execution does not exist

        elif error_code == 'AccessDeniedException':
            logger.error(f"Access Denied Exception: {error_message}")
            # Handle cases where the IAM role does not have sufficient permissions

        else:
            logger.error(f"Athena Error: {error_code} - {error_message}")
            # Handle other Athena-related errors

    except Exception as e:
        logger.error(f"Other Exception: {str(e)}")
        # Handle any other unexpected exceptions

def generate_daily_run_rate(selected_value):

    logger.info(f'UPDATING FORECAST TABLE - {selected_value}')

    # DAILY QTY SOLD
    # -----

    # Calculate daily dataframe
    daily_df = result_df.loc[result_df['sku_name']==selected_value].sort_values('order_date',ascending=False)
    product_sku = daily_df['sku'].unique().tolist()[0]

    # Calculate statistics for past 7, 14, 30 & 60 days
    last_7_median = daily_df.head(7)['qty_sold'].median()
    last_7_p25 = np.percentile(daily_df.head(7)['qty_sold'],25)
    last_7_p75 = np.percentile(daily_df.head(7)['qty_sold'],75)

    last_14_median = daily_df.head(14)['qty_sold'].median()
    last_14_p25 = np.percentile(daily_df.head(14)['qty_sold'],25)
    last_14_p75 = np.percentile(daily_df.head(14)['qty_sold'],75)

    last_30_median = daily_df.head(30)['qty_sold'].median()
    last_30_p25 = np.percentile(daily_df.head(30)['qty_sold'],25)
    last_30_p75 = np.percentile(daily_df.head(30)['qty_sold'],75)

    last_60_median = daily_df.head(60)['qty_sold'].median()
    last_60_p25 = np.percentile(daily_df.head(60)['qty_sold'],25)
    last_60_p75 = np.percentile(daily_df.head(60)['qty_sold'],75)

    # Consolidate stats
    recent_stats_df = pd.DataFrame([[last_7_p25, last_7_median, last_7_p75],
                [last_14_p25, last_14_median, last_14_p75],
                [last_30_p25, last_30_median, last_30_p75],
                [last_60_p25, last_60_median, last_60_p75]],
                columns=['percentile_25','median','percentile_75'])

    # Calculate median of lower bound (median) and upper bound (75th percentile)
    lower_bound = recent_stats_df['median'].median()
    upper_bound = recent_stats_df['percentile_75'].median()

    # Extrapolate out 30, 60, 90 days
    daily_run_rate = ['forecast_daily', lower_bound,upper_bound]

    # Consolidate into dataframe
    df = pd.DataFrame([daily_run_rate],
                columns=['forecast','lower_bound','upper_bound'])

    # Append product name & sku
    df['sku'] = product_sku
    df['sku_name'] = selected_value

    # Set partition date to yesterday (data as of yesterday)
    df['partition_date'] = pd.to_datetime(pd.to_datetime('today') - timedelta(1)).strftime('%Y-%m-%d')

    return df[['sku','sku_name','forecast','lower_bound','upper_bound','partition_date']]

# Check S3 Path for Existing Data
# -----------

def check_path_for_objects(bucket: str, s3_prefix:str):

  logger.info(f'Checking for existing data in {bucket}/{s3_prefix}')

  # Create s3 client
  s3_client = boto3.client('s3',
                          region_name = REGION,
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

  # List objects in s3_prefix
  result = s3_client.list_objects_v2(Bucket=bucket, Prefix=s3_prefix)

  # Instantiate objects_exist
  objects_exist=False

  # Set objects_exist to true if objects are in prefix
  if 'Contents' in result:
      objects_exist=True

      logger.info('Data already exists!')

  return objects_exist

# Delete Existing Data from S3 Path
# -----------

def delete_s3_prefix_data(bucket:str, s3_prefix:str):

  logger.info(f'Deleting existing data from {bucket}/{s3_prefix}')

  # Create an S3 client
  s3_client = boto3.client('s3',
                          region_name = REGION,
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

  # Use list_objects_v2 to list all objects within the specified prefix
  objects_to_delete = s3_client.list_objects_v2(Bucket=bucket, Prefix=s3_prefix)

  # Extract the list of object keys
  keys_to_delete = [obj['Key'] for obj in objects_to_delete.get('Contents', [])]

  # Check if there are objects to delete
  if keys_to_delete:
      # Delete the objects using 'delete_objects'
      response = s3_client.delete_objects(
          Bucket=bucket,
          Delete={'Objects': [{'Key': key} for key in keys_to_delete]}
      )
      logger.info(f"Deleted {len(keys_to_delete)} objects")
  else:
      logger.info("No objects to delete")

# --------------
# Function to run Athena query , not return results
# --------------

def run_athena_query_no_results(query:str, database: str):

    # Initialize Athena client
    athena_client = boto3.client('athena',
                                 region_name='us-east-1',
                                 aws_access_key_id=AWS_ACCESS_KEY_ID,
                                 aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

    # Execute the query
    try:
        response = athena_client.start_query_execution(
            QueryString=query,
            QueryExecutionContext={
                'Database': database
            },
            ResultConfiguration={
                'OutputLocation': 's3://prymal-ops/athena_query_results/'  # Specify your S3 bucket for query results
            }
        )

        query_execution_id = response['QueryExecutionId']

        # Wait for the query to complete
        state = 'RUNNING'

        while (state in ['RUNNING', 'QUEUED']):
            response = athena_client.get_query_execution(QueryExecutionId = query_execution_id)
            logger.info(f'Query is in {state} state..')
            if 'QueryExecution' in response and 'Status' in response['QueryExecution'] and 'State' in response['QueryExecution']['Status']:
                # Get currentstate
                state = response['QueryExecution']['Status']['State']

                if state == 'FAILED':
                    logger.error('Query Failed!')
                elif state == 'SUCCEEDED':
                    logger.info('Query Succeeded!')

    except ParamValidationError as e:
        logger.error(f"Validation Error (potential SQL query issue): {e}")
        # Handle invalid parameters in the request, such as an invalid SQL query

    except WaiterError as e:
        logger.error(f"Waiter Error: {e}")
        # Handle errors related to waiting for query execution

    except ClientError as e:
        error_code = e.response['Error']['Code']
        error_message = e.response['Error']['Message']

        if error_code == 'InvalidRequestException':
            logger.error(f"Invalid Request Exception: {error_message}")
            # Handle issues with the Athena request, such as invalid SQL syntax

        elif error_code == 'ResourceNotFoundException':
            logger.error(f"Resource Not Found Exception: {error_message}")
            # Handle cases where the database or query execution does not exist

        elif error_code == 'AccessDeniedException':
            logger.error(f"Access Denied Exception: {error_message}")
            # Handle cases where the IAM role does not have sufficient permissions

        else:
            logger.error(f"Athena Error: {error_code} - {error_message}")
            # Handle other Athena-related errors

    except Exception as e:
        logger.error(f"Other Exception: {str(e)}")
        # Handle any other unexpected exceptions

# ========================================================================
# Execute Code
# ========================================================================

DATABASE = 'prymal-analytics'
REGION = 'us-east-1'

# Construct query to pull data by product
# ----

QUERY = f"""SELECT partition_date
            , order_date
            , sku
            , sku_name
            , SUM(qty_sold) as qty_sold
            FROM shopify_qty_sold_by_sku_daily

            WHERE partition_date >= DATE(current_date - interval '120' day)
            GROUP BY partition_date
            , order_date
            , sku
            , sku_name
            ORDER BY order_date ASC
            """

# Query datalake to get quantiy sold per sku for the last 120 days
# ----

result_df = run_athena_query(query=QUERY, database=DATABASE, region=REGION)
result_df.columns = ['partition_date','order_date','sku','sku_name','qty_sold']

logger.info(result_df.head(3))
logger.info(result_df.info())
logger.info(f"Count of NULL RECORDS: {len(result_df.loc[result_df['order_date'].isna()])}")
# Format datatypes & new columns
result_df['order_date'] = pd.to_datetime(result_df['order_date']).dt.strftime('%Y-%m-%d')
result_df['qty_sold'] = result_df['qty_sold'].astype(int)
result_df['week'] = pd.to_datetime(result_df['order_date']).dt.strftime('%Y-%W')

logger.info(f"MIN DATE: {result_df['order_date'].min()}")
logger.info(f"MAX DATE: {result_df['order_date'].max()}")

# Create dataframe of skus sold in the time range
skus_sold_df = result_df.loc[~result_df['sku_name'].isna(),['sku','sku_name']].drop_duplicates()

# Construct query to pull latest (as of yesterday) inventory details
# ----

yesterday_date = pd.to_datetime(pd.to_datetime('today') - timedelta(1)).strftime('%Y-%m-%d')

QUERY =f"""with inventory AS (

        SELECT partition_date
        , CAST(sku AS VARCHAR) as sku
        , total_fulfillable_quantity
        FROM shipbob_inventory
        WHERE partition_date = '{yesterday_date}'
        )

        SELECT partition_date
        , CASE WHEN sku IS NULL THEN 'Not Reported'
            ELSE sku end as sku
        , SUM(total_fulfillable_quantity)
        FROM inventory
        GROUP BY partition_date
        , CASE WHEN sku IS NULL THEN 'Not Reported'
            ELSE sku end

                    """

# Query datalake to get current inventory details for skus sold in the last 120 days
# ----

inventory_df = run_athena_query(query=QUERY, database='prymal', region=REGION)
inventory_df.columns = ['partition_date','sku','inventory_on_hand']

logger.info(inventory_df.head(3))
logger.info(inventory_df.info())

# Format datatypes & new columns
inventory_df['inventory_on_hand'] = inventory_df['inventory_on_hand'].astype(int)

# List of products to forecast stockout dates for
PRODUCT_LIST = ['Salted Caramel - Large Bag (320 g)',
                'Cacao Mocha - Large Bag (320 g)',
                'Original - Large Bag (320 g)',
                'Vanilla Bean - Large Bag (320 g)',
                'Butter Pecan - Large Bag (320 g)',
                'Cinnamon Dolce - Large Bag (320 g)']

# Blank df to store results
product_run_rate_df = pd.DataFrame()

# For each sku in products list, generate forecast using recent sales data
for p in PRODUCT_LIST:

    # Generate daily run rates for the product
    df = generate_daily_run_rate(p)

    # Append to run rate dataframe
    product_run_rate_df = pd.concat([product_run_rate_df,df])

# Reset index
product_run_rate_df.reset_index(inplace=True,drop=True)

# Merge run rate df with yesterday's partition of inventory df
inventory_details_df = product_run_rate_df.merge(inventory_df,
                how='left',
                on=['partition_date', 'sku'])

# Calculate days of stock on hand given the inventory on hand and daily run rate
inventory_details_df['days_of_stock_onhand'] = round(inventory_details_df['inventory_on_hand'] / inventory_details_df['upper_bound'],0).astype(int)

inventory_details_df = inventory_details_df[['sku','sku_name','forecast','lower_bound','upper_bound','inventory_on_hand','days_of_stock_onhand','partition_date']]

# Create s3 client
s3_client = boto3.client('s3',
                          region_name = REGION,
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_ACCESS_KEY
                          )

# Set bucket
BUCKET = os.environ['S3_PRYMAL_ANALYTICS']

# WRITE TO S3 =======================================

# Log number of rows
logger.info(f'{len(inventory_details_df)} rows in inventory_details_df')

# Configure S3 Prefix
S3_PREFIX_PATH = f"shopify/inventory_report/partition_date={yesterday_date}/shopify_inventory_report_{yesterday_date}.csv"

# Check if data already exists for this partition
data_already_exists = check_path_for_objects(bucket=BUCKET, s3_prefix=S3_PREFIX_PATH)

# If data already exists, delete it ..
if data_already_exists == True:

   # Delete data
   delete_s3_prefix_data(bucket=BUCKET, s3_prefix=S3_PREFIX_PATH)

logger.info(f'Writing to {S3_PREFIX_PATH}')

with io.StringIO() as csv_buffer:
    inventory_details_df.to_csv(csv_buffer, index=False)

    response = s3_client.put_object(
        Bucket=BUCKET,
        Key=S3_PREFIX_PATH,
        Body=csv_buffer.getvalue()
    )

    status = response['ResponseMetadata']['HTTPStatusCode']

    if status == 200:
        logger.info(f"Successful S3 put_object response for PUT ({S3_PREFIX_PATH}). Status - {status}")
    else:
        logger.error(f"Unsuccessful S3 put_object response for PUT ({S3_PREFIX_PATH}. Status - {status}")

# --------------------
# RUN 'ATHENA ALTER TABLE' TO UPDATE TABLE
# --------------------

QUERY = f"""

ALTER TABLE shopify_inventory_report ADD
  PARTITION (partition_date = '{yesterday_date}')

"""

run_athena_query_no_results(query=QUERY, database='prymal-analytics')


X = int(input())

if X == 1:
    print(1)
else:
    max = 0
    for i in range(1, 100):
        for j in range(2, 10):
            if i**j > X:
                break
            elif max < i**j:
                max = i**j

    print(max)


from dataclasses import dataclass
from typing import Union

@dataclass
class SegmentSetTable(object):
    set_id: list[int]
    segment_id: list[int]
    size: int

    @staticmethod
    def from_dict(set_dict: dict[Union[int, str], list[int]]):
        """Create `SegmentSetTable` from dict where keys are set ids, values are lists of segments ids."""
        set_ids = []
        segment_ids = []
        for k in set_dict.keys():
            for v in set_dict[k]:
                set_ids.append(int(k))
                segment_ids.append(v)
        return SegmentSetTable(set_ids, segment_ids, len(set_ids))


# Combination Sum IV
class Solution:
    def combinationSum4(self, nums, target):
        dp = [0] * (target + 1)
        dp[0] = 1

        for t in range(1, target + 1):
            dp[t] = sum(0 if t - n < 0 else dp[t - n] for n in nums)

        return dp[target]

if __name__ == "__main__":
    sol = Solution()
    nums = [9]
    target = 3
    print(sol.combinationSum4(nums, target))


"""empty message

Revision ID: 9611191a3d83
Revises: bc2eee4d0747
Create Date: 2021-02-21 21:28:01.275643

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '9611191a3d83'
down_revision = 'bc2eee4d0747'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('rating_steps', schema=None) as batch_op:
        batch_op.add_column(sa.Column('rate_loop_rating_step_id', sa.Integer(), nullable=True))
        batch_op.create_foreign_key('fk_rate_loop_rating_steps', 'rating_steps', ['rate_loop_rating_step_id'], ['id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('rating_steps', schema=None) as batch_op:
        batch_op.drop_constraint('fk_rate_loop_rating_steps', type='foreignkey')
        batch_op.drop_column('rate_loop_rating_step_id')

    # ### end Alembic commands ###


# -*- coding: utf-8 -*-
"""
Created on Wed May 17 15:55:59 2023

@author: KENO
"""

# importing the necessary library
import pandas as pd
import sklearn
import streamlit as st
import pickle

# Load the trained model
with open('model.pkl', 'rb') as file:
    model = pickle.load(file)

# Load the one-hot encoded mapping
with open('pre-process.pkl', 'rb') as file:
    ohe_process = pickle.load(file)
    ohe_process = ohe_process.drop('class_Negative', axis='columns')
    ohe_process = ohe_process.drop('class_Positive', axis='columns')

def preprocess_input(input_data):
    # Convert the input data into a DataFrame
    df = pd.DataFrame([input_data])

    # Get the column names with object data type
    object_columns = df.select_dtypes(include='object').columns

    # Convert the columns to categorical
    df[object_columns] = df[object_columns].astype('category')

    # Apply one-hot encoding using the loaded mapping
    df_encoded = pd.get_dummies(df).reindex(columns=ohe_process.columns, fill_value=0)

    return df_encoded

def main():
    st.title("Early Stage Diabetes Risk Prediction App :hospital: :male-doctor:")

    # Collect user inputs
    input_data = {}

    # input fields
    input_data['Age'] = st.number_input("Enter your age:", min_value=18, max_value=100)

    input_data['Gender'] = st.selectbox("Select your gender:", ['Male', 'Female'])
    input_data['Polyuria'] = st.selectbox("Symptoms of Polyuria:", ['No', 'Yes'])
    input_data['Polydipsia'] = st.selectbox("Symptoms of Polydipsia:", ['No', 'Yes'])
    input_data['sudden weight loss'] = st.selectbox("Sudden weight loss:", ['No', 'Yes'])
    input_data['weakness'] = st.selectbox(" Signs of Weakness:", ['No', 'Yes'])
    input_data['Polyphagia'] = st.selectbox(" Symptoms of Polydphagia:", ['No', 'Yes'])
    input_data['Genital thrush'] = st.selectbox(" Symptoms of Genital thrush:", ['No', 'Yes'])
    input_data['visual blurring'] = st.selectbox(" Visual blurring:", ['No', 'Yes'])
    input_data['Itching'] = st.selectbox(" Experiences itching:", ['No', 'Yes'])
    input_data['Irritability'] = st.selectbox(" Experiences irritability:", ['No', 'Yes'])
    input_data['delayed healing'] = st.selectbox(" Symptoms of delayed healing:", ['No', 'Yes'])
    input_data['partial paresis'] = st.selectbox(" Symptoms of partial paresis:", ['No', 'Yes'])
    input_data['muscle stiffness'] = st.selectbox(" Symptoms of muscle stiffness:", ['No', 'Yes'])
    input_data['Alopecia'] = st.selectbox(" Symptoms of alopecia:", ['No', 'Yes'])
    input_data['Obesity'] = st.selectbox(" Signs of Obesity:", ['No', 'Yes'])

    # Preprocess the user inputs
    processed_input = preprocess_input(input_data)

    # Make predictions using the loaded model
    if st.button('Diagnose'):
        prediction = model.predict(processed_input)

        # Display the prediction to the user
        if prediction == 0:
            st.success("The Patient is not at risk for Diabetes")
        else:
            st.success("The Patient is at risk for Diabetes")

if __name__ == "__main__":
    main()


import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from uncertainties import ufloat

x, y = np.genfromtxt('Helmholz1.txt', unpack=True)
x=x/100

def g(x):
    return ((4*np.pi*10**(-7)*2*0.0625**2)/(0.0625**2+ (x)**2)**(3/2))*200*1000

t= np.linspace(0.06, 0.26, 1000)

plt.plot (x,y, 'rx', label='Messwerte')
#plt.plot(x, (np.pi*10**(-7)*2*0.0625**2)/(0.0625**2+ x**2)**(5/2)*10)
plt.plot(t, g(t), 'b-', label='Theoriekurve')
plt.xlabel(r'Abstand vom Spule 1 in m')
plt.ylabel(r'B/ mT')
plt.legend()
plt.savefig('Helmholz1.pdf')


from time import time, sleep
from contextlib import contextmanager

#считают время работы блока кода и выводят его на экран

class cm_timer_1:

    def __init__(self):
        self.start = 0
        self.finish = 0

    def __enter__(self):
        self.start = time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.finish = time()
        print("Время работы: ", self.finish - self.start)

@contextmanager #на основе библиотеки
def cm_timer_2():
    start = time()
    yield None
    finish = time()
    print("Время работы: ", finish - start)

if __name__ == '__main__':
    with cm_timer_1():
        sleep(2)
    with cm_timer_2():
        sleep(2)


from fastapi import FastAPI

app = FastAPI()

BOOKS = {
    'book1': {'title': 'title1', 'author': 'author1'},
    'book2': {'title': 'title2', 'author': 'author2'},
    'book3': {'title': 'title3', 'author': 'author3'},
    'book4': {'title': 'title4', 'author': 'author4'},
    'book5': {'title': 'title5', 'author': 'author5'},
}

@app.get('/')
async def books():
    return BOOKS

@app.put('/updateBook/{bookName}')
async def updateBook(bookName: str, bookTitle: str, bookAuthor: str):
    bookDetails = {'title': bookTitle, 'author': bookAuthor}

    # updating the books dictionary
    BOOKS[bookName] = bookDetails

    return bookDetails


import asyncio
import time

# Definir las funciones a ejecutar en segundo plano
async def funcion_1(n):
    print(f'Ejecutando funcion 1 con n = {n}')
    await asyncio.sleep(5)
    return n * n

async def funcion_2(n):
    print(f'Ejecutando funcion 2 con n = {n}')
    await asyncio.sleep(3)
    return n + n

# Función principal que ejecuta funciones en segundo plano
async def ejecutar_funciones_en_segundo_plano(n):
    # Ejecutar las funciones en segundo plano usando asyncio
    resultado_1 = asyncio.create_task(funcion_1(n))
    resultado_2 = asyncio.create_task(funcion_2(n))

    # Esperar hasta que las tareas estén completas
    await asyncio.gather(resultado_1, resultado_2)

    # Obtener los resultados de las funciones
    resultado_1 = resultado_1.result()
    resultado_2 = resultado_2.result()

    print(f'Resultados: funcion_1 = {resultado_1}, funcion_2 = {resultado_2}')

if __name__ == "__main__":
    # Inicializar el event loop de asyncio
    loop = asyncio.get_event_loop()
    loop.run_until_complete(ejecutar_funciones_en_segundo_plano(5))
    loop.close()


# 5. Write a program that finds the shortest and the longest string from a list of strings.

list_of_strings = ['subash', 'chandra', 'Elluri', 'harini', 'darapu', 'abc', 'xy', 'I dont care']

longest_length = shortest_length = len(list_of_strings[0])
for string in list_of_strings:
    if len(string) >= longest_length:
        longest_string = string
        longest_length = len(string)
    if len(string) <= shortest_length:
        shortest_string = string
        shortest_length = len(string)

print(f'The longest string is {longest_string} with length {longest_length}')
print(f'The shortest string is {shortest_string} with length {shortest_length}')


"""
#!/usr/bin/env python
anonymize.py
"""

import os, sys, json
import pdb

def anonymize_ids_in_target_dir(target_dir):
    ## Get dir contents
    hits = os.listdir(target_dir)
    ## Create new csv file as key to anonymized results
    hitlist = open(target_dir +  "-anonymized-results-key.csv", "w")
    hitlist.write("WorkerId,AnonId\n")

    ## Anonymized data dir
    if not os.path.isdir(target_dir + "-anonymized-results/"):
        os.mkdir(target_dir + "-anonymized-results")

    for hitnum, hit in enumerate(hits):
        if hit.endswith(".json"):
            hitdata = json.load(open(target_dir + "/" + hit))
            workerid = hitdata["WorkerId"]
            hitdata["WorkerId"] = "anon" + str(hitnum)
            anonfile = open(target_dir + "-anonymized-results/anon-" + str(hitnum) + ".json","w")
            json.dump(hitdata, anonfile)
            anonfile.close()
            hitlist.write(workerid + ",anon-" + str(hitnum) + "\n")

    hitlist.close()

def anonymize_ids_in_child_dirs(parent_dir):
    sub_dirs = os.listdir(parent_dir)
    for sub_dir in sub_dirs:
        if os.path.isdir(sub_dir):
            anonymize_ids_in_target_dir(sub_dir)

if __name__ == "__main__":
    target_dir = sys.argv[1] if len(sys.argv) >= 2 else "."
    if target_dir == ".":
        print("Currently looking for sub-directories to anonymize...")
        anonymize_ids_in_child_dirs(target_dir)
    else:
        print("Currently anonymizing files in " + target_dir)
        anonymize_ids_in_target_dir(target_dir)


import math
def mean(num):
    return sum(num)/len(num)
def sd(num):
    n= len(num)
    mean_value=mean(num)
    sqd=sum((x-mean_value)**2 for x in num)
    return math.sqrt(sqd/(n-1))
num=[10,20,30,40,55,96]
print(mean(num))
print(sd(num))


from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import CustomUserViewSet, CollegeViewSet, StudentViewSet, EventViewSet, RegisterView
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

router = DefaultRouter()
router.register(r'users', CustomUserViewSet)
router.register(r'colleges', CollegeViewSet)
router.register(r'students', StudentViewSet)
router.register(r'events', EventViewSet, basename='event')

urlpatterns = [
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('register/', RegisterView.as_view(), name='register'),
    path('', include(router.urls)),
]


#!/usr/bin/env python3

from __future__ import print_function

import argparse
import logging
import sys

def add_pairs(filename, all_pairs):
    basefile, annotator = filename.split('.annotation.')
    basefile = basefile.split('/')[-1]
    pairs = all_pairs.setdefault(annotator, {}).setdefault(basefile, set())

    for line in open(filename):
        parts = [int(v) for v in line.strip().split() if v != '-']
        source = max(parts)
        parts.remove(source)
        for part in parts:
            pairs.add((part, source))
    return all_pairs

def print_kappa(name, annotations0, annotations1):
    # Cohen's Kappa
    a, b, c, d = 0, 0, 0, 0
    # These will be:
    #                      Rater 0
    #                   link   no-link
    # Rater 1   link      a      c
    #          no-link    b      d

    # Get valid ranges for annotations
    filenames = list(annotations0.keys()) + list(annotations1.keys())
    for filename in filenames:
        min_src = 10000000
        max_src = 0
        for anno in [annotations0, annotations1]:
            if filename in anno:
                for _, src in anno[filename]:
                    min_src = min(min_src, src)
                    max_src = max(max_src, src)
            else:
                print("Comparing annotations without matching files", name, file=sys.stderr)
        for i in range(min_src, max_src + 1):
            for j in range(0, i + 1):
                if (j, i) in annotations0[filename]:
                    if (j, i) in annotations1[filename]: a += 1
                    else: b += 1
                else:
                    if (j, i) in annotations1[filename]: c += 1
                    else: d += 1

    # Kappa
    total = a + b + c + d
    a /= total
    b /= total
    c /= total
    d /= total
    pO = (a + d)
    pE = (a + b) * (a + c) + (c + d) * (b + d)
    kappa = (pO - pE) / (1 - pE)
    print("{} Kappa {:.3f}   from {} {} {} {}".format(name, kappa, a, b, c, d))

def print_f1(name, annotations0, annotations1):
    # Harmonic mean of the two values for how many we had in common
    common, total_0, total_1 = 0, 0, 0

    # Get valid ranges for annotations
    filenames = list(annotations0.keys()) + list(annotations1.keys())
    for filename in filenames:
        if filename in annotations0 and filename in annotations1:
            common += len(annotations0[filename].intersection(annotations1[filename]))
        if filename in annotations0:
            total_0 += len(annotations0[filename])
        if filename in annotations1:
            total_1 += len(annotations1[filename])
    val0 = 100 * common / total_0
    val1 = 100 * common / total_1
    f1 = 2 * val0 * val1 / (val0 + val1)

    print("{} F1    {:.2f}   from {:.2f} {:.2f} - {} {} {}".format(name, f1, val0, val1, common, len(annotations0), len(annotations1)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Compare annotations of conversation graphs')
    parser.add_argument('files', help='Files containing annotations', nargs="+")
    parser.add_argument('-f1', help='Calculate f1', action='store_true')
    args = parser.parse_args()

    all_pairs = {}
    for filename in args.files:
        add_pairs(filename, all_pairs)

    annotators = list(all_pairs.keys())
    for annotator0 in annotators:
        for annotator1 in annotators:
            if annotator0 == annotator1:
                break
            name = "Annotators:"+ annotator0 +":"+ annotator1
            annotations0 = all_pairs[annotator0]
            annotations1 = all_pairs[annotator1]
            print_kappa(name, annotations0, annotations1)
            if args.f1:
                print_f1(name, annotations0, annotations1)


#2D List
my2DList = [ ["AJ", 21, "Mac"], ["Roman", 19, "PC"], ["Dean", 17, "PC"] ]
print(my2DList)
print(my2DList[0])
print(my2DList[0][0])
print("==================")
#Editing a 2D List
my2DList = [ ["AJ", 21, "Mac"],
   ["Roman", 19, "PC"],
   ["Dean", 17, "PC"] ]

my2DList[1][2] = "Linux"
# The line above changes list 1, item 2 from PC to Linux

print(my2DList[1])
# I'm using this line to output list 1 to check that the change has happened correctly.
print("==================")
#day43 challenge
print("Bingo game")
print("=================")
import random

bingo = []

def ran():
  number = random.randint(1,90)
  return number

def prettyPrint():
  for row in bingo:
    print(row)

numbers = []
for i in range(8):
  numbers.append(ran())

numbers.sort()

bingo = [ [ numbers[0], numbers[1], numbers[2]],
          [ numbers[3], "BINGO", numbers[4] ],
          [ numbers [5], numbers[6], numbers[7]]
        ]

prettyPrint()


from django.views.generic import FormView
from django.http import HttpResponseRedirect
from django.contrib.contenttypes.models import ContentType
from .forms import CommentCreateForm
from .models import Comment

class CommentCreate(FormView):
    form_class = CommentCreateForm

    def form_valid(self, form):
        next_step = form.cleaned_data.get('next_step')
        text = form.cleaned_data.get('text')
        author = self.request.user
        content_type_id = form.cleaned_data.get('content_type_id')
        object_id = form.cleaned_data.get('object_id')
        content_type = ContentType.objects.get_for_id(content_type_id)
        comment = Comment.objects.create(
            author=author,
            text=text,
            content_type=content_type,
            object_id=object_id
        )
        return HttpResponseRedirect(next_step)


import sys
input = sys.stdin.readline

# 최대공약수를 구하는 함수
def gcd(num1, num2):
    if num1 < num2:
        (num1, num2) = (num2, num1)
    while num2 != 0:
        (num1, num2) = (num2, num1 % num2)
    return num1

N = int(input())

num_list = list(map(int, input().split()))

for i in range(1, N):
    GCD = gcd(num_list[0], num_list[i])
    print('{}/{}'.format(num_list[0] // GCD, num_list[i] // GCD))  # "(num_list[0] // GCD) / (num_list[i] // GCD)" 출력

[백준] 단계별로풀어보기/14 정수론 및 조합론/3036.py


#importing the libraries
import pandas as pd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import re
import warnings
warnings.filterwarnings("ignore")
import nltk
from thefuzz import fuzz
from thefuzz import process
import sys
import logging
import string

def remove_punctuation(text):
    return ''.join([words.lower() for words in text if words not in string.punctuation])

def tokenization(text):
    return nltk.tokenize.word_tokenize(text)

stopwords = nltk.corpus.stopwords.words('english')
def stopwards(words):
    return [i for i in words if i not in stopwords]

lemma= nltk.WordNetLemmatizer()

def lemmatization(words):
    return ' '.join([lemma.lemmatize(word) for word in words])

def replace_year(x):
    l=re.findall("\d{4}", x)
    for i in l:
        x=x.replace(i, 'wxyz')
    return x

def main(df):
    '''This is the main function of the program
    '''
    print('IN MAIN')
    replace_dict={"\r": " ","\n":" ",    }

    for key,items in replace_dict.items():
        df['Plot']= df['Plot'].str.replace(key,items)

    #replacing the year with wxyz
    df['Plot_1'] = df['Plot'].apply(lambda x: replace_year(x))
    #removing punctuations and numbers
    df['plot_without_punct']=df['Plot_1'].apply(lambda x: re.sub(r'[0-9]', '',x)).apply(lambda x: remove_punctuation(x))
    #tokenization
    df['plot_tokenized']=df['plot_without_punct'].apply(lambda x: tokenization(x))
    #removing stopwards
    df['plot_tokenized_removed_sw']=df['plot_tokenized'].apply(lambda x: stopwards(x))
    #applying lemmatization
    df['plot_lemma']=df['plot_tokenized_removed_sw'].apply(lambda x: lemmatization(x))
    #making final dataframe
    df=df[['Release Year', 'Title', 'Origin/Ethnicity', 'Director', 'Cast', 'Genre','Genre_updated', 'Wiki Page', 'Plot', 'plot_lemma']]
    df.rename(columns={'plot_lemma': 'Plot_cleanned'},inplace=True)
    df.to_csv('wiki_movie_plots_deduped_cleaned_genre_and_plot_script.csv',index=False)

if __name__ == '__main__':
    LOG_FORMAT = '%(levelname)s %(asctime)s - %(message)s'
    logging.basicConfig(filename = 'logs_plot.log',
                        level = logging.DEBUG,
                        format = LOG_FORMAT,
                        filemode = 'w')
    path=sys.argv
    logging.info('Started fetching')
    main(pd.read_csv(path[1]))
    logging.info('Fetching Done')


from django.urls import path
from .views import IndexView, ArticleNewView, article_detail, manager_dashboard, MarketologDashboard

urlpatterns = [
    path('', IndexView.as_view(), name='index'),
    path('article/new', ArticleNewView.as_view(), name='article_new'),
    path('article/<int:article_id>/detail', article_detail, name='article_detail'),
    path('manager/dashboard', manager_dashboard, name='manager_dashboard'),
    path('marketolog/dashboard', MarketologDashboard.as_view() , name='marketolog_dashboard'),
]


# Explanation: A program that takes a range and creates a plot based on three separate functions iterating through those ranges.

# Task: Write a program called plottask.py that displays a plot of the functions f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] on the one set of axes.

# Sources: I was able to complete the bulk of this task using the lecture slides and the accompanying further reading material. I did some extra research
# into more advanced styling options, namely:

#    - W3Schools' material on Matplotlib markers, lines, grids and labels;
#    - The NumPy documentation for that library's append function, which I ultimately couldn't get to work;
#    - Matplotlib's documentation for some more extra styling options.

# All links are contained in the README.

# Working Notes: The actual logic of this was quite simple, I knew I needed to loop through a range and produce three separate arrays. I initially tried
# to use a NumPy array, but this doesn't seem to work with the standard append command. I researched the NumPy append command, which produces a new
# array for reasons that I don't yet understand, and then experimented with the insert and concatenate commands from the same library, all of which I
# could only generate more errors. Instead I changed each array back to a standard list and used the original append command. After that it was a matter
# of experimenting with various line, grid, label and marker styles.

import matplotlib.pyplot as plt

range = [0,1,2,3,4]

# one range each for the three arrays required
xpoints = []
ypoints = []
zpoints = []

# loops through range and adds the result of each operation to a separate array
for i in range:
    normal = i
    square = i*i
    cubed = i*i*i
    xpoints.append(normal)
    ypoints.append(square)
    zpoints.append(cubed)

# ls indicates the line style, with - representing a solid (default) line, : a dotted line, and -- a dashed line.
#
plt.plot(xpoints,label="Original Values", color="DodgerBlue", ls="-", marker="o")
plt.plot(ypoints,label="Squared Values", color="GoldenRod", ls="-.", marker="D")
plt.plot(zpoints,label="Cubed Values", color="FireBrick", ls="--", marker="^")

# the fontdict parameter allows for the setting of uniform or divergent font properties across different elements

titlefont = {"family":"sans-serif","color":"FireBrick","size": 14}
labelfont = {"family":"sans-serif","color":"FireBrick","size": 10}

plt.grid(color="NavajoWhite",linestyle=":")
plt.legend(edgecolor="FireBrick",borderpad=1,facecolor="FloralWhite")
plt.title("The Integers 0 to 4, Powered by 1, 2 and 3",fontdict=titlefont)
plt.xlabel("Integer Value",fontdict=labelfont)
plt.ylabel("Powered Value",fontdict=labelfont)

plt.savefig("plot.png")


word = input().strip()
w1,w2 = word.split()
w1o=""
w2o=0
for i in range(len(w1)):
	if i==0:
		w1o+=w1[i].upper()
	else:
		w1o+=w1[i].lower()
for i in w2:
	if i in "0123456789":
		w2o+= int(i)
print(w1o,w2o)


import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from uncertainties import ufloat

a1, b1= np.genfromtxt('Werte1.txt', unpack=True)
a2, b2= np.genfromtxt('Werte2.txt', unpack=True)
a3, b3= np.genfromtxt('Werte3.txt', unpack=True)
a4, b4= np.genfromtxt('Werte4.txt', unpack=True)
a5, b5= np.genfromtxt('Werte5.txt', unpack=True)

#plt.plot(t, f(t, *params), 'b-' ,label='Lineare Regression')
def f(x, c, d, s):
    return s- c* (np.exp(-d*x))

params1, cov1 = curve_fit(f, a1, b1)
params2, cov2 = curve_fit(f, a2, b2)
params3, cov3 = curve_fit(f, a3, b3)
params4, cov4 = curve_fit(f, a4, b4)
params5, cov5 = curve_fit(f, a5, b5)

covv1 = np.sqrt(np.diag(cov1))
covv2 = np.sqrt(np.diag(cov2))
covv3 = np.sqrt(np.diag(cov3))
covv4 = np.sqrt(np.diag(cov4))
covv5 = np.sqrt(np.diag(cov5))

print(params1[2],'pm',covv1[2],params2[2],'pm',covv2[2],params3[2],'pm',covv3[2],params4[2],
'pm',covv4[2],params5[2],'pm',covv5[2])

x=np.linspace(0, 200, 10000)
plt.plot (a1, b1, 'rx', label='Messwerte 1')
plt.plot (a2, b2, 'bx', label='Messwerte 2')
plt.plot (a3, b3, 'x',color= 'lime', label='Messwerte 3')
plt.plot (a4, b4, 'x',color= 'purple', label='Messwerte 4')
plt.plot (a5, b5, 'x',color= 'orange', label='Messwerte 5')
plt.plot(x,f(x, *params1), 'r-' )
plt.plot(x,f(x, *params2), 'b-' )
plt.plot(x,f(x, *params3), '-',color= 'lime' )
plt.plot(x,f(x, *params4), '-' ,color= 'purple')
plt.plot(x,f(x, *params5), '-' ,color= 'orange')

#plt.plot(x,f(x, *params), 'b-' ,label='Ausgleichsfunktion f(x)')
#plt.axhline(y=3.167131, color='slateblue', linestyle='--', label='y =\frac{1}{\sqrt2}(\frac{U_c}{U})_{\text{max}}')
#plt.axvline(x=29000, color='slateblue', linestyle='--',label='Halbwertsbreite')
#plt.axvline(x=37500 , color='slateblue', linestyle='--')
plt.grid()
plt.xlabel(r'$U / V$')
plt.ylabel(r'$ I / mA$')
plt.legend(loc="best")
plt.tight_layout()
plt.savefig('plot1.pdf')
plt.show()


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

import os,sys,getopt
import numpy
import math
from math import sqrt, acos

list = ['LEU_LEU', 'ALA_ILE', 'ARG_ILE', 'PRO_PRO', 'MET_LEU', 'MET_VAL', 'ARG_VAL', 'PHE_MET', 'ARG_PRO', 'HIS_LEU', 'PHE_PRO', 'ILE_LEU', 'ILE_ALA', 'VAL_PRO', 'ILE_VAL', 'TYR_PRO', 'LEU_PRO', 'ASN_ILE', 'ASN_PHE', 'PHE_ILE', 'PHE_THR', 'ALA_LEU', 'PHE_LEU', 'TYR_PHE', 'SER_ILE', 'GLN_ALA', 'GLN_LEU', 'TYR_LEU', 'ILE_PRO', 'LYS_PRO', 'VAL_ALA', 'GLY_ALA', 'LYS_ILE', 'ALA_PRO', 'TYR_ILE', 'MET_ILE', 'ALA_GLU', 'ARG_ALA', 'GLN_VAL', 'ASN_VAL', 'HIS_ILE', 'VAL_LEU', 'SER_ALA', 'ARG_LEU', 'LEU_ALA', 'VAL_VAL', 'PHE_VAL', 'TYR_VAL', 'GLN_ILE', 'ALA_ALA', 'SER_PRO', 'ASN_LEU', 'LYS_SER', 'GLN_MET']
#PCT = open('PDB_cst.txt', 'r')
for i in range(0,53):
    P = list[i].split('_')[0]
    N = list[i].split('_')[1]
    #print(P,N)
    PCT = open('PDB_cst.txt', 'r')
    WT = open(list[i] + '.txt', 'w')
    for li in PCT:
        #print(li.split()[1])
        if li.split()[1] == P and li.split()[2] == N:
            print(li)
            WT.write(li)


import random
from subversion_rando import logic_presets
from subversion_rando.logic_presets import custom_logic_str_from_tricks, custom_logic_tricks_from_str
from subversion_rando.trick import Trick
from subversion_rando.trick_data import Tricks, trick_name_lookup

def test_custom_logic_str() -> None:
    empty_trick_str = custom_logic_str_from_tricks(frozenset())
    assert empty_trick_str == "000000000000", f"empty: {empty_trick_str}"

    for _ in range(10):
        l_int = random.randrange(0x1000_0000_0000, 0x1_0000_0000_0000)
        l_int &= 0xffff_ffff_fff0
        l_str = hex(l_int)[2:]
        l_t = custom_logic_tricks_from_str(l_str)
        # print(l_str)
        # pprint([trick_name_lookup[t] for t in l_t])
        assert l_str == custom_logic_str_from_tricks(l_t)

    # print(custom_logic_str_from_tricks(frozenset()))

def test_specific_set() -> None:
    # just some random set to see if something changes
    test_str = "3b0489a4fbb0"
    test_set = frozenset([
        Tricks.uwu_2_tile,
        Tricks.crouch_precise,
        Tricks.ice_clip,
        Tricks.spazer_into_lower_pirate_lab,
        Tricks.sbj_w_hjb,
        Tricks.crumble_jump,
        Tricks.wave_gate_glitch,
        Tricks.xray_climb,
        Tricks.uwu_2_tile_surface,
        Tricks.short_charge_2,
        Tricks.searing_gate_tricks,
        Tricks.short_charge_4,
        Tricks.super_sink_easy,
        Tricks.movement_zoast,
        Tricks.crouch_or_downgrab,
        Tricks.patience,
        Tricks.sbj_underwater_w_hjb,
        Tricks.morph_jump_4_tile,
        Tricks.dark_medium,
        Tricks.short_charge_3,
        Tricks.sbj_no_hjb,
        Tricks.super_sink_hard
    ])
    assert custom_logic_str_from_tricks(test_set) == test_str
    assert custom_logic_tricks_from_str(test_str) == test_set

def test_str_2_tricks_reference() -> None:
    _mask_2_trick: dict[str, Trick] = getattr(logic_presets, "_mask_2_trick")
    for mask_str, t in _mask_2_trick.items():
        fs = frozenset([t])
        assert custom_logic_str_from_tricks(fs) == mask_str, f"{trick_name_lookup[t]} {mask_str}"
        assert custom_logic_tricks_from_str(mask_str) == fs, f"{mask_str} {trick_name_lookup[t]}"

if __name__ == "__main__":
    test_custom_logic_str()
    test_str_2_tricks_reference()
    test_specific_set()