import time
import pandas as pd
import numpy as np

CITY_DATA = { 'Chicago': 'chicago.csv',
              'New York City': 'new_york_city.csv',
              'Washington': 'washington.csv' }

# Modified print-statements
def print_pause_a(message_to_print):
    print(message_to_print)
    time.sleep(1.0)

def print_pause_b(message_to_print):
    print(message_to_print)
    time.sleep(0.5)

# TO DO: display the most common month
def popular_month(df):
    most_popular_month = df['month'].mode()[0]
    print('Most popular month:', most_popular_month)

# TO DO: display the most common day of week
def popular_day(df):
    most_popular_day = df['day'].mode()[0]
    print('Most popular day:', most_popular_day)

# TO DO: display the most common start hour
def popular_hour(df):
    df['hour'] = df['Start Time'].dt.hour
    most_popular_hour = df['hour'].mode()[0]
    print('Most popular start hour:', most_popular_hour)

# TO DO: display most commonly used start station with Pandas .idxmax()
def popular_start_station(df):
    most_popular_start_station = df['Start Station'].value_counts().idxmax()
    print('Most commonly used start station:', most_popular_start_station)

# TO DO: display most commonly used end station with Pandas .idxmax()
def popular_end_station(df):
    most_popular_end_station = df['End Station'].value_counts().idxmax()
    print('Most commonly used end station:', most_popular_end_station)

# TO DO: display most frequent combination of start station and end station trip
def popular_combination_station(df):
    most_popular_start_station = df['Start Station'].value_counts().idxmax()
    most_popular_end_station = df['End Station'].value_counts().idxmax()
    most_popular_combination_station = df.groupby(['Start Station', 'End Station']).count()
    print('Most frequent combination of start station and end station trip:', most_popular_start_station, " & ", most_popular_end_station)

# TO DO: display mean travel time (sec to min /60)
def mean_travel(df):
    mean_travel_time = df['Trip Duration'].mean()
    print('Mean travel time:', mean_travel_time/60, ' minutes')

# TO DO: display total travel time (sec to day /(24*60*60))
def total_travel(df):
    total_travel_time = sum(df['Trip Duration'])
    print('Total travel time:', total_travel_time/86400, ' days')

# TO DO: Display counts of user types
def count_user(df):
    count_user_types = df['User Type'].value_counts()
    print('Counts of user Types:', count_user_types)

# TO DO: Display counts of gender
def count_gender(df):
    try:
      count_gender = df['Gender'].value_counts()
      print('Counts of gender:\n', count_gender)
    except KeyError:
      print_pause_b('Counts of gender:\nData not available.')

# TO DO: Display earliest year of birth
def earliest_birth(df):
    try:
      earliest_year_birth = df['Birth Year'].min()
      print('Earliest year of birth:', earliest_year_birth)
    except KeyError:
      print('Earliest year of birth:\nData not available.')

# TO DO: Display most recent year of birth
def recent_birth(df):
    try:
      most_recent_year_birth = df['Birth Year'].max()
      print('Most recent year of birth:', most_recent_year_birth)
    except KeyError:
      print('Most recent year of birth:\nData not available.')

# TO DO: Display  most common year of birth
def common_birth(df):
    try:
      most_common_year_birth = df['Birth Year'].value_counts().idxmax()
      print('Most common year of birth:', most_common_year_birth)
    except KeyError:
      print('Most common year of birth:\nData not available.')

# Providing input for main-function
def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.
    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """

    print_pause_a('Hello! Let\'s explore some US bikeshare data!')
    print_pause_a('')

# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
#HINT: Use a while loop to handle invalid inputs
    while True:
        city = input('Please choose a business location to analyze:\nType (1)Chicago, (2)New York City, (3)Washington\n')
        city = city.lower()
# Improve usability through multiple options for the same city
        if city == 'chicago' or city == '1':
            city = 'Chicago'
            break
        if city == 'new york' or city == 'new york city' or city == '2':
            city = 'New York City'
            break
        elif city == 'washington' or city == 'washington dc' or city == '3':
            city = 'Washington'
            break
# 'Safety net' if no valid input is given to the function
        else:
            print_pause_a('Please select one of the given possibilities.')
            get_filters()
    print_pause_a('You have chosen ' + city + ' as a filter . Please continue..')
    print_pause_a('')

# TO DO: get user input for month (all, january, february, ... , june)
    while True:
        month = input('Would you like to filter the data by month? If not please choose all.\nType (1) January, (2) February, (3) March, (4) April, (5) May, (6) June (7) all\n')
        month = month.lower()
# Improve usability through multiple options for the same month
        if month == '1' or month == 'january' or month == 'jan':
            month = 'January'
            break
        elif month == '2' or month == 'february' or month == 'feb':
            month = 'February'
            break
        elif month == '3' or month == 'march' or month == 'mar':
            month = 'March'
            break
        elif month == '4' or month == 'april' or month == 'apr':
            month = 'April'
            break
        elif month == '5' or month == 'may':
            month = 'May'
            break
        elif month == '6' or month == 'june'or month == 'jun':
            month = 'June'
            break
        elif month == '7' or month == 'all'or month == 'jul':
            month = 'all'
            break
# 'Safety net' if no valid input is given to the function
        else:
            print_pause_a('Please select one of the given possibilities.')
            get_filters()
    print_pause_a('You have chosen ' + month + ' as a filter . Please continue..')
    print_pause_a('')
    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)

    while True:
        day = input('Would you like to filter the data by day? If not please choose all.\nType (1) Monday, (2)Tuesday, (3)Wednesday, (4)Thursday, (5)Friday, (6)Saturday, (7)Sunday, (8) all\n')
        day = day.lower()
# Improve usability through multiple options for the same day
        if day == '1' or day == 'monday' or day == 'mon':
            day = 'Monday'
            break
        elif day == '2' or day == 'tuesday' or day == 'tue':
            day = 'Tuesday'
            break
        elif day == '3' or day == 'wednesday' or day == 'wed':
            day = 'Wednesday'
            break
        elif day == '4' or day == 'thursday' or day == 'thu':
            day = 'Thursday'
            break
        elif day == '5' or day == 'friday' or day == 'fri':
            day = 'Friday'
            break
        elif day == '6' or day == 'saturday' or day == 'sat':
            day = 'Saturday'
            break
        elif day == '7' or day == 'sunday' or day == 'sun':
            day = 'Sunday'
            break
        elif day == '8' or day == 'all':
            day = 'all'
            break
# 'Safety net' if no valid input is given to the function
        else:
            print_pause_a('Please select one of the given possibilities.')
            get_filters()
    print_pause_a('You have chosen ' + day + ' as a filter.')
    print_pause_a('')
    print_pause_a('You\'re dataset is being processed')
    print_pause_b('-'*40)
# Returning user input for further processing
    return city, month, day

def load_data(city, month, day):

    """
    Loads data for the specified city and filters by month and day if applicable.
    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
# Choose data from provided csv according to user input provided by respective function and create a dataset (city)
    df = pd.read_csv(CITY_DATA[city])
# Preparing for .dt.
    df['Start Time'] = pd.to_datetime(df['Start Time'])
# Creating additional columns for month & day to prepare for respective requests
    df['month'] = df['Start Time'].dt.month
    df['day'] = df['Start Time'].dt.weekday_name
# Choose data according to user input provided by respective function (month)
    if month != 'all':
        months = ['January', 'February', 'March', 'April', 'May', 'June']
        month = months.index(month) + 1
# create a adjusted dataset
        df = df[df['month'] == month]
# Choose data according to user input provided by respective function (day)
    if day != 'all':
# create a adjusted dataset
        df = df[df['day'] == day.title()]
# return dataset as requested by user
    return df
# Give the user the opportunity to see the raw data
def raw_data(df):
    display_data = input('Do you want to see the first 5 rows which are going to be used for the calculation?\ny/n\n')
    display_data = display_data.lower()
    index = 0
    while True:
        if display_data == 'n':
            print_pause_a('The programm will now go on with the calculation')
            break
        elif display_data == 'y':
            print(df[index: index + 5])
            index = index + 5
            display_data = input('Do you want to see the the next 5 rows which are going to be used for the calculation?\ny/n\n')
            display_data = display_data.lower()
# 'Safety net' if no valid input is given to the function
        else:
            print_pause_a('Sorry I don\'t understand-please try again')
            raw_data(df)

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""
    print_pause_b('Calculating the most frequent times of travel...\n')
# Needed later on to determine how long it took to make the calculation
    start_time = time.time()
    popular_month(df)
    popular_day(df)
    popular_hour(df)
# How long did the calculation take
    print_pause_b('This took %s seconds.' % (time.time() - start_time))
    print_pause_b('-'*40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""
    print_pause_b('Calculating the most popular stations and trip...\n')
# Needed later on to determine how long it took to make the calculation
    start_time = time.time()
    popular_start_station(df)
    popular_end_station(df)
    popular_combination_station(df)
# How long did the calculation take
    print_pause_b('This took %s seconds.' % (time.time() - start_time))
    print_pause_b('-'*40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""
    print_pause_b('Calculating trip duration...\n')
# Needed later on to determine how long it took to make the calculation
    start_time = time.time()
    total_travel(df)
    mean_travel(df)
# How long did the calculation take
    print_pause_b(('This took %s seconds.' % (time.time() - start_time)))
    print_pause_b('-'*40)

def user_stats(df):
    """Displays statistics on bikeshare users."""
    print_pause_b('Calculating user stats...\n')
# Needed later on to determine how long it took to make the calculation
    start_time = time.time()
    count_user(df)
    count_gender(df)
    earliest_birth(df)
    recent_birth(df)
    common_birth(df)
# How long did the calculation take
    print_pause_b(('This took %s seconds.' % (time.time() - start_time)))
    print_pause_b('-'*40)

# Improve usability by providing the option of creating further surveys
def restart_survey():
    print_pause_a('Do you want to create another survey?')
    restart = input('y/n\n')
    if restart == 'y':
        main()
# Ending the program if no futher surveys are needed
    elif restart == 'n':
        print_pause_a('Thank you for using this data analysis tool!')
        quit()
# 'Safety net' if no valid input is given to the function
    else:
        print_pause_a('Sorry I don\'t understand-please try again')
        restart_survey()

# main function that combines the predefined functions
def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        raw_data(df)
        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)
        restart_survey()

# checking if this is the main program
if __name__ == "__main__":
	main()


import copy

from language import *
from mute import *
from greetings import *
from lights import *
from volume import *
from admin import *
from settings import *
from speak import *

commands = {
    volume: volumeWords,
    greeting: greetingWords,
    lights: lightWords,
    }

def isMessageForComputer(words, numWords):
    if (words[0] in language_wakeWords):
        return True

    if (numWords > 1 and words[1] in language_wakeWords):
        return True

    if (numWords > 2 and words[2] in language_wakeWords):
        return True

    return False

def processWords(words):
    processedWords = []
    for word in words:
        if (word not in language_politeWords and word not in language_rudeWords):
            processedWords.append(word)

    return processedWords

def calculateScore(commandWords, inputWords):
    matches = 0
    for word in inputWords:
        if word in commandWords:
            matches += 1
    return matches

def handle(message):
    message = message.lower()
    words = message.split(' ')
    processedWords = processWords(words)

    numWords = len(words)
    numProcessedWords = len(processedWords)

    execute = lambda: commandNotRecognized(words)
    maxScore = settings_minThreshold

    if (numWords > 1 and isMessageForComputer(processedWords, numProcessedWords)):
        for key, value in commands.items():
            score = calculateScore(value, processedWords)

            if (score > maxScore):
                command = copy.copy(key)
                args = copy.copy(words)
                execute = lambda: command(args)
                maxScore = score

        vocalResponse = execute()
        if settings_levelOneAudibleConfirmations:
            speak(vocalResponse)


from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

import layouts.knowledgeEditorClassFeatureDefinition as design
import connectionToDatabase as db
import knowledgeEditor.Dialog.ScalarClassFeatureDef as ScalarEdit
import knowledgeEditor.Dialog.LogicalClassFeatureDef as LogicalEdit
import knowledgeEditor.Dialog.DimensionalClassFeatureDef as DimensionalEdit

class classFeatureDefinition(QtWidgets.QMainWindow, design.Ui_classFeatureDefinition):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна
        self.featureOfClass = []
        self.inst()
        self.show_ScalarEditor = ScalarEdit.Scalar(self)
        self.show_LogicalEditor = LogicalEdit.Logical(self)
        self.show_DimensionalEditor = DimensionalEdit.Dimensional(self)

        self.comboBox_classChoose_classFeatureDefinition.activated.connect(self.takeFeaturesFromClass)
        self.button_goBack_classFeatureDefinition.clicked.connect(self.goto_return)
        self.comboBox_featureChoose_classFeatureDefinition.activated.connect(self.takeTypeOfFeature)
        self.comboBox_featureChoose_classFeatureDefinition.activated.connect(self.getValueOfFeature)
        self.button_ok_classFeatureDefinition.clicked.connect(self.goto_return)
        self.comboBox_classChoose_classFeatureDefinition.activated.connect(self.showSetFeature)
        self.comboBox_classChoose_classFeatureDefinition.activated.connect(self.showUnSetFeature)
        self.button_featureSet_classFeatureDefinition_2.clicked.connect(self.setFeatureDef)
        self.button_featureUnSet_classFeatureDefinition.clicked.connect(self.unsetFeatureDef)

    def inst(self):
        self.comboBox_classChoose_classFeatureDefinition.clear()
        classes = db.getAllClasses()
        for row in classes:
            self.comboBox_classChoose_classFeatureDefinition.addItem(row["Class"])
        if self.comboBox_classChoose_classFeatureDefinition.count() > 0:
            self.comboBox_classChoose_classFeatureDefinition.setCurrentText(classes[0]["Class"])
        self.takeFeaturesFromClass()
        self.getValueOfFeature()
        self.showSetFeature()
        self.showUnSetFeature()

    def takeFeaturesFromClass(self):
        self.comboBox_featureChoose_classFeatureDefinition.clear()
        features = db.getFeautureFromClass_classExplanation(
            self.comboBox_classChoose_classFeatureDefinition.currentText())
        if not features == None:
            if len(features) > 0:
                for row in features:
                    self.comboBox_featureChoose_classFeatureDefinition.addItem(row["NameFeature"])
                self.comboBox_featureChoose_classFeatureDefinition.setCurrentText(features[0]["NameFeature"])
                self.takeTypeOfFeature()
                return features
            else:
                return []

    def setFeatureDef(self):
        featureType = self.takeTypeOfFeature()
        if featureType == 1:
            self.goto_ScalarEdit()
        if featureType == 2:
            self.goto_LogicalEdit()
        if featureType == 3:
            self.goto_DimensionalEdit()

    def goto_ScalarEdit(self):
        self.show_ScalarEditor.inst(self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                    db.getIdFeatureClass_pairByClassNameFeatureName(
                                        self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                        self.comboBox_classChoose_classFeatureDefinition.currentText()))
        self.show_ScalarEditor.show()
        self.hide()

    def goto_LogicalEdit(self):
        self.show_LogicalEditor.inst(self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                     db.getIdFeatureClass_pairByClassNameFeatureName(
                                         self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                         self.comboBox_classChoose_classFeatureDefinition.currentText()))
        self.show_LogicalEditor.show()
        self.hide()

    def goto_DimensionalEdit(self):
        self.show_DimensionalEditor.inst(self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                         db.getIdFeatureClass_pairByClassNameFeatureName(
                                             self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                             self.comboBox_classChoose_classFeatureDefinition.currentText()))
        self.show_DimensionalEditor.show()
        self.hide()

    def unsetFeatureDef(self):
        feature = self.comboBox_featureChoose_classFeatureDefinition.currentText()
        featureType = db.takeTypeOfFeature(feature)
        if featureType['Type'] == 1:
            self.show_ScalarEditor.deleteFeature(db.getIdFeatureClass_pairByClassNameFeatureName(
                                            self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                            self.comboBox_classChoose_classFeatureDefinition.currentText()))
            self.inst()
        if featureType['Type'] == 2:
            self.show_LogicalEditor.inst(self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                         db.getIdFeatureClass_pairByClassNameFeatureName(
                                             self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                             self.comboBox_classChoose_classFeatureDefinition.currentText()))
            self.inst()
        if featureType['Type'] == 3:
            self.show_DimensionalEditor.inst(self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                             db.getIdFeatureClass_pairByClassNameFeatureName(
                                                 self.comboBox_featureChoose_classFeatureDefinition.currentText(),
                                                 self.comboBox_classChoose_classFeatureDefinition.currentText()))
            self.inst()

    def showSetFeature(self):
        print()

    def showUnSetFeature(self):
        self.text_featureUnset_classFeatureDefinition.clear()
        self.text_featureSetted_classFeatureDefinition.clear()
        AllFeatures = self.takeFeaturesFromClass()
        if not AllFeatures==None:
            if len(AllFeatures) > 0:
                for row in AllFeatures:
                    if db.isSet(db.getIdFeatureClass_pairByClassNameFeatureName(
                            row["NameFeature"],
                            self.comboBox_classChoose_classFeatureDefinition.currentText())):
                        self.text_featureSetted_classFeatureDefinition.append(row["NameFeature"])
                    else:
                        self.text_featureUnset_classFeatureDefinition.append(row["NameFeature"])

    #
    # if row["Type"] == 1:
    #     return 'Scalar'
    # if row["Type"] == 2:
    #     return 'Logical'
    # if row["Type"] == 3:
    #     return 'Dimensional'

    def getValueOfFeature(self):
        self.text_Definition.clear()
        feature = self.comboBox_featureChoose_classFeatureDefinition.currentText()
        className=self.comboBox_classChoose_classFeatureDefinition.currentText()
        self.text_Definition.clear()
        featureType = db.takeTypeOfFeature(feature)
        idFeatureClass=db.getIdFeatureClass_pairByClassNameFeatureName(feature,className)
        if featureType is not None:
            if featureType['Type'] == 1:
                values = db.getClassFeatureDefById_Scalar(idFeatureClass)
                for x in values:
                    self.text_Definition.append(x["Value"])

            if featureType['Type'] == 2:
                values = db.getClassFeatureDefById_Logical(idFeatureClass)
                self.text_Definition.append("True value:=" + str(values["True_Value"]))
                self.text_Definition.append("False value:=" + str(values["False_Value"]))
            if featureType['Type'] == 3:
                values = db.getClassFeatureDefById_Dimensional(idFeatureClass)
                self.text_Definition.append(str(values["LeftValue"])+" <= Value for class <= " +str(values["RightValue"]))

    def takeTypeOfFeature(self):
        self.line_featureType_classFeatureDefinition.clear()
        feature = self.comboBox_featureChoose_classFeatureDefinition.currentText()
        featureType = db.takeTypeOfFeature(feature)
        if featureType['Type'] == 1:
            self.line_featureType_classFeatureDefinition.setText("Скалярный")
            return 1
        if featureType['Type'] == 2:
            self.line_featureType_classFeatureDefinition.setText("Логический")
            return 2
        if featureType['Type'] == 3:
            self.line_featureType_classFeatureDefinition.setText("Размерный")
            return 3
        return -1

    def goto_return(self):
        self.parent().show()
        self.close()


# Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
#
# Example:
#
# Given array nums = [-1, 2, 1, -4], and target = 1.
#
# The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution:
    def threeSumClosest(self, nums, target):
        diff = float('inf')
        result = None
        nums.sort()
        for i, num in enumerate(nums):
            j, k = i+1, len(nums) -1
            while j < k:
                three_sum = nums[j] + nums[k] +  nums[i]
                if three_sum < target:
                    j += 1
                elif three_sum > target:
                    k -= 1
                else:
                    return target
                curr_diff = abs(three_sum - target)
                if curr_diff < diff:
                    diff = curr_diff
                    result = three_sum
        return result

arr = [0, 2, -10,5 ]
s = Solution()
print(s.threeSumClosest(arr, 1))


from flask import Flask, Response, render_template
from multiprocessing import Process, Queue, Lock
import time
import cv2
from Object_detection import yolo  # 욜로 사용시
# from Pose_estimation import openpose,openpose_single #오픈포즈 사용시
from ESMS import send_sms
from datetime import datetime
import argparse

# Flask 웹서버 실행, __name__ 실행
app = Flask(__name__)
print("Queue waiting")

# url 경로 '/' 호출 시 templates/index.html로 렌더링
@app.route('/')
def index():
    return render_template('/index.html')

# url 경로 '/view_info1' 호출 시 원본영상을 프레임별로 반환
@app.route('/view_info1')
def view_info1():
    return Response(generate1(),
                    mimetype="multipart/x-mixed-replace; boundary=frame")

# url 경로 '/view_info2' 호출 시 객체인식 된 결과를 프레임별로 반환
@app.route('/view_info2')
def view_info2():
    return Response(generate2(),
                    mimetype="multipart/x-mixed-replace; boundary=frame")

# mimetype="multipart/x-mixed-replace; boundary=frame"
# 서버가 클라이언트에게 보내주는 HTTP 헤더타입
# 브라우져 화면에 나타나는 내용이 지속적으로 변하게 가능

# 원본 영상을 송출하기 위한 함수
def generate1():
    #init시 생성된 Queue 변수 호출
    global w2
    while True:
        # Queue에 저장된 원본 프레임 호출
        frame = w2.get()

        # Queue에 저장된 프레임이 없는 경우 continue
        if frame is None:
            continue

        #원본 frame 복사 후 640x640 으로 리사이즈
        cpy_frame = frame.copy()
        cpy_frame = cv2.resize(cpy_frame, (640, 640))

        # JPEG 형식으로 인코딩
        (flag, encodedImage) = cv2.imencode(".jpg", cpy_frame)

        # 인코딩이 성공적으로 되었는지 확인
        if not flag:
            continue

        # yield the output frame in the byte format
        # 매 프레임마다 str - > byte 포멧 형식으로 변환 후 yield를 통해 반환
        yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
               bytearray(encodedImage) + b'\r\n')

# 인식결과에 대한 영상을 송출하기 위한 함수
def generate2():
    #init시 생성된 Queue 변수 호출
    global w3
    while True:
        # 인식결과 프레임이 저장된 Queue 호출
        frame = w3.get()
        if frame is None:
            continue

        # 이미지 리사이즈
        cpy_frame = frame.copy()
        cpy_frame = cv2.resize(cpy_frame, (640, 640))

        # JPEG 형식으로 인코딩
        (flag, encodedImage) = cv2.imencode(".jpg", cpy_frame)

        # 인코딩 성공적으로 되었는지 확인
        if not flag:
            continue
        # yield the output frame in the byte format
        # byte 타입의 str형식으로 처리되는 프레임마다 반환
        yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
               bytearray(encodedImage) + b'\r\n')

# 프레임 생성 ,q = w1 ,q2 = w2
def create_frame(input_image, q, q2):
    # 영상파일 호출, 실시간일 경우 0
    video = cv2.VideoCapture(input_image)
    i = 0
    # Loop
    while True:
        # read함수를 통해 프레임 호출
        hasFrame, frame = video.read()
        # 프레임을 q2(원본영상을 웹에 송출하기위한 Queue, w2)에 input
        q2.put(frame)

        #영상이 끝난경우 종료
        if frame is -1:
            break

        #프레임이 없는경우 종료
        if not hasFrame:
            print("process...end")
            break

        # 프레임 있을경우 영상 처리
        else:
            #딜레이
            time.sleep(0.03)

            # 50프레임(약1.5초 주기)당 실행
            if i % 50 == 0:
                # 응급환자 발생여부를 판독하기 위한 q(w1)에 input
                q.put(frame)
                print("------------------------------------")
                print(f"Process {i} FRAMES")
        i += 1
    # 종료 후 객체 close
    video.release()
    cv2.destroyAllWindows()

# frame 처리 ,q = w1 ,q2 = w3
# w1에 프레임이 있는 경우에만 처리됨
# 응급환자 발생여부를 판독하기 위한 프레임이 있을경우 처리
def processing_frame(mode, q, q2):
    while True:
        # 응급환자 발생 수를 저장한 배열(Queue) 호출
        global fainting_count
        # Queue(w1)에 저장된 Frame 호출
        frame = q.get()

        # main.py 실행시 -m 'yolo' 입력한 경우 ,또는 옵션을 주지 않은 경우 Yolo 진행
        if mode == 'yolo':
            #Object_detection/yolo.py의 yolo 함수 호출, 객체인식 진행
            #yolo 함수에서 처리된 결과를 result 변수에 저장, list 형식으로 [인식된영상, 응급환자 수] 반환
            result = yolo.yolo(frame)

        # main.py 실행시 -m 'openpose' 입력한 경우 ,openpose 모드로 진행, 사용x
        # elif mode == 'openpose':
        # result = openpose.openpose(frame)
        # result = openpose_single.openpose(frame)

        # main.py 실행시 -m 옵션을 통해 'yolo' 또는 'openpose' 외 다른 명령을 입력한 경우 에러로 처리, break
        else:
            print("Error You choice '-m [yolo] or [openpose]'")
            break

        # 객체인식 후 바운딩박스 처리된 영상을 frame 변수에 저장
        frame = result[0]
        # 객체인식 후 응급환자 발생 수를 fainting_people 변수에 저장
        fainting_people = result[1]

        # fainting_people 값이 0보다 클 경우 응급환자 발생으로 간주하여 Queue 처리
        # 제일 우선적으로 들어온 데이터(0번 인덱스)를 제거하고 마지막 항목에 새로운 데이터(1)를 추가
        if fainting_people > 0:
            print("find emergency patients")
            fainting_count.pop(0)
            fainting_count.append(1)

        # fainting_people 값이 0과 같거나 작은경우 응급환자가 발생하지 않은것으로 간주하여 Queue 처리
        # 제일 우선적으로 들어온 데이터(0번 인덱스)를 제거하고 마지막 항목에 새로운 데이터(0)를 추가
        else:
            fainting_count.pop(0)
            fainting_count.append(0)
        print(f"fainting_count : {fainting_count}")
        print(f"fainting_count : {sum(fainting_count)}")

        # 리스트 'fainting_count'에 존재하는 값들의 합이 10일 경우 응급상황으로 간주하여 SMS 전송함수 실행
        if sum(fainting_count) == 10:
            #print("This is emergency scenario. send SMS")

            # send_sms 함수를 호출하여 관리자에게 문자메시지 전송
            send_esms()

            # SMS 전송 후 fainting_count 초기화
            fainting_count = [0] * 10
            print(f"fainting_count init : {fainting_count}")

        # print(f"inference time : {round(time.time()-start_time, 4)}")

        # q2(w3)에 객체인식 결과 프레임을 input
        q2.put(frame)
        #frame 없는경우 종료
        if frame is -1:
            break

# Naver Cloud Platform에서 제공하는 SMS API 서비스를 이용하여 SMS문자를 보내기 위한 함수
def send_esms():
    print("This is emergency scenario. Send SMS")
    # 오늘 날짜 정보를 today 변수에 저장
    today = time.strftime('%Y년 %m월 %d일', time.localtime(time.time()))
    # 현재 시간을 cur_time 변수에 저장
    cur_time = time.strftime('%H시 %M분 %S초', time.localtime(time.time()))
    # 오늘 날짜와 현재 시간을 today_cur_time 변수에 저장
    today_cur_time = today + '\n' + cur_time
    # 보내는 사람의 번호를 str형식으로 send_phonenum 변수에 저장
    send_phonenum = 'yourphone'  # '010-1234-5678'
    # 받는 사람의 번호를 list(str) 형식으로 recv_phonenum 변수에 저장
    recv_phonenum = ['sendphone']  # 1명에게 보낼경우 ['010-1234-5678'] 2명 이상에게 보낼 경우 ['010-1234-5678','010-3333-7777']

    # ESMS/send_sms.py의 send_sms 함수에 보내는 사람, 받는 사람의 전화번호와 날짜와시간에 대한 정보를 넘겨줌
    # SMS 발송 후 응답결과(json 포멧)를 result 변수에 저장
    result = send_sms.send_msg(send_phonenum, recv_phonenum, today_cur_time)
    print(f"result : {result}")

if __name__ == "__main__":
    #main.py 실행시 옵션을 설정할 수 있도록 argparse 객체 지정
    parser = argparse.ArgumentParser()
    #main.py 실행시 추가적으로 줄 수 있는 인자값 설정
    #-i 옵션을 통해 image 또는 video 호출 가능, default 값으로 'videos/20200424_1.mp4'가 지정됨
    parser.add_argument('-i', '--image', type=str, default='videos/20200424_1.mp4', help='input image or video')
    #-m 옵션을 통해 객체인식 모드를 지정가능, yolo 모드와 openpose 모드를 지정할 수 있으며 default 값으로 'yolo'가 지정됨
    parser.add_argument('-m', '--mode', type=str, default='yolo', help='choice "yolo" or "openpose"')

    #인자값을 사용하기 위한 객체 지정
    args = parser.parse_args()
    #이미지 관련 인자값에 대해 저장
    input_image = args.image
    #인식관련 인자값에 대해 저장
    mode = args.mode

    print("Main status")
    # 프로세스 간 데이터를 주고받기 위한 큐 할당
    w1 = Queue()
    w2 = Queue()
    w3 = Queue()
    print("Queue Ready")

    #응급환자 발생 수를 저장하기 위한 배열(Queue) 설정
    fainting_count = [0] * 10

    # 각 프로세스별로 함수 작동하도록 설정(병렬처리)
    p1 = Process(target=create_frame, args=(input_image, w1, w2))
    p2 = Process(target=processing_frame, args=(mode, w1, w3))

    #프로세스 가동
    p1.start()
    print("process 1 start")
    p2.start()
    print("process 2 start")
    print("Process Ready")

    #플라스크 웹 서버 실행
    app.run(host='0.0.0.0', port=8992, debug=True, threaded=True, use_reloader=False)
    print("app start")


# _*_ coding:utf-8 _*_
import pika

rabbitmq_host = '172.16.10.10'
rabbitmq_port = 5672

connection = pika.BlockingConnection(pika.ConnectionParameters(rabbitmq_host, rabbitmq_port))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                         type='fanout')

# 不指定queue名字,rabbitmq会随机分配一个名字
# exclusive=True 表示使用此queue的消费者断开后,自动将queue删除
result = channel.queue_declare(exclusive=True)

queue_name = result.method.queue

# 绑定消费者连接指定exchange
channel.queue_bind(exchange='logs',
                   queue=queue_name)

print('[*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print("[x] %r" % body)
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(callback,
                      queue=queue_name)

channel.start_consuming()


# LC 98 Validate Binary Search Tree (Medium)

# Given the root of a binary tree, determine if it is a valid binary search tree(BST).

# A valid BST is defined as follows:

# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.

# Example 1:

# Input: root = [2, 1, 3]
# Output: true
# Example 2:

# Input: root = [5, 1, 4, null, null, 3, 6]
# Output: false
# Explanation: The root node's value is 5 but its right child's value is 4.

# Constraints:

# The number of nodes in the tree is in the range[1, 104].
# -231 <= Node.val <= 231 - 1

# SOLUTION

# Approach 1: Recursive Traversal with Valid Range
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:

        def validate(node, low=-math.inf, high=math.inf):
            # Empty trees are valid BSTs.
            if not node:
                return True
            # The current node's value must be between low and high.
            if node.val <= low or node.val >= high:
                return False

            # The left and right subtree must also be valid.
            return (validate(node.right, node.val, high) and
                    validate(node.left, low, node.val))

        return validate(root)

# Approach 2: Iterative Traversal with Valid Range

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        if not root:
            return True

        stack = [(root, -math.inf, math.inf)]
        while stack:
            root, lower, upper = stack.pop()
            if not root:
                continue
            val = root.val
            if val <= lower or val >= upper:
                return False
            stack.append((root.right, val, upper))
            stack.append((root.left, lower, val))
        return True


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 2018

@author: casa
"""
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.utils import to_categorical
from keras import backend as K
import numpy as np
from tensorflow.python.lib.io import file_io
import io
import PIL
import random
import matplotlib as plt
import argparse

# parámetros para redimensionar imágenes
img_width, img_height = 150, 150
epochs = 50
batch_size = 16

train_data_dir = ''
validation_data_dir = ''

classes_num = 3  # numero de clases para clasificar
nb_train_samples = 4984
nb_validation_samples = 144

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

def leer_una_imagen(uri):
    image_bytes = file_io.FileIO(uri, mode='r').read()
    image = PIL.Image.open(io.BytesIO(image_bytes)).convert('RGB')
    image = image.resize((img_width, img_height), PIL.Image.BILINEAR)
    return image

def leer_imagenes_etiquetas(ruta):
    ## variables
    x=[]
    y=[]

    ruta=ruta + "/"
    print('LA RUTA ES...' + ruta)
    ## obtenemos la lista de ficneros para la ruta pasada por parámentro
    filelist = sorted(file_io.list_directory(ruta))
    random.seed(42)
    random.shuffle(filelist)

    print('TAMAÑO DIRECTORIO...' + str(len(filelist)) + "  primero..." + filelist[1])
    ## obtenemos las imágenes y las etiquetas de cada elemento de la lista
    for imgPath in filelist:
        imagen=leer_una_imagen(ruta + imgPath)
        imagen = img_to_array(imagen) # pasa a array
        x.append(imagen)
        	# lee, redimensiona y lo añade al array

        #imagePath = ruta + imgPath
        #imagen = cv2.imread(imagePath) # lee
        #imagen = cv2.resize(imagen, (img_width, img_height))  # redimentsiona

        # extraemos la etiqueta del nombre de cada fichero
        #ruta_partes = imagePath.split("/")  # lo dividimos en las partes de la ruta
        #nombreimagen = ruta_partes[len(ruta_partes)-1]   # nos quedamos con el nombre del fichero, que es el último

        label = imgPath[imgPath.find("_")+1:imgPath.find(".")] # la etiqueta está entre _ y .
        label = int(label) -1  # las etiquetas empiezan en 1, y les restamos 1 para que empiecen en 0
        y.append(label)

    print('REGISTROS LEIDOS X...' + str(len(x)))
    print('REGISTROS LEIDOS Y...' + str(len(y)))
    return (x,y)

def preproceso_imagenes_etiquetas(x,y):
    # pasar cada pixel a una escala de [0, 1] en un array numpy
    x = np.array(x, dtype="float") / 255.0
    # pasar las etiquetas a array y luego a categórico
    y = np.array(y)
    y_cat = to_categorical(y, num_classes=classes_num)

    return (x,y_cat)

def definir_red_neuronal():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=input_shape))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1))
    #model.add(Activation('sigmoid'))
    model.add(Dense(classes_num, activation='softmax'))

    model.compile(loss='categorical_crossentropy',
                  optimizer='rmsprop',
                  metrics=['categorical_accuracy'])

    return model

def definir_data_augmentation(x_train_p, y_train_p, x_validation_p, y_validation_p):
    # this is the augmentation configuration we will use for training
    train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

    # this is the augmentation configuration we will use for testing:
    # only rescaling
    test_datagen = ImageDataGenerator(rescale=1. / 255)

    t_generator = train_datagen.flow(
        x_train_p,y_train_p,
        batch_size=batch_size)

    v_generator = test_datagen.flow(
        x_validation_p,y_validation_p,
        batch_size=batch_size)

    return (t_generator,v_generator)

def dibujar_grafico_accuracy_loss(H):
    plt.use("Agg")
    plt.use("ggplot")
    plt.figure()

    plt.plot(np.arange(0, epochs), H.history["loss"], label="train_loss")
    plt.plot(np.arange(0, epochs), H.history["val_loss"], label="val_loss")
    plt.plot(np.arange(0, epochs), H.history["acc"], label="train_acc")
    plt.plot(np.arange(0, epochs), H.history["val_acc"], label="val_acc")

    plt.title("Training Loss y Accuracy")
    plt.xlabel("Epoch #")
    plt.ylabel("Loss/Accuracy")
    plt.legend(loc="lower left")
    plt.savefig(args["grafico"])

###########################################################
###########################################################
###
###    PROGRAMA PRINCIPAL
###
###########################################################
###########################################################

def Run():
    ## Leemos datos y etiquetas para train y validación, y los preprocesamos
    (x_train, y_train) = leer_imagenes_etiquetas(train_data_dir)
    (x_train, y_train) = preproceso_imagenes_etiquetas(x_train, y_train)
    (x_validation, y_validation) = leer_imagenes_etiquetas(validation_data_dir)
    (x_validation, y_validation) = preproceso_imagenes_etiquetas(x_validation, y_validation)

    if (len(x_train)==0):
        print("ALGO HA IDO MAL!!!")
        return()
    ## definimos la estrategia de aumento de datos
    (train_generator,validation_generator) = definir_data_augmentation(x_train, y_train,x_validation, y_validation)

    ## preparamos la arquitectura de la red neuronal
    modelo = definir_red_neuronal()

    ## lanzamos el entrenamiento con los datos preparados y la red definida
    history = modelo.fit_generator(
        train_generator,
        steps_per_epoch=nb_train_samples // batch_size,
        epochs=epochs,
        validation_data=validation_generator,
        validation_steps=nb_validation_samples // batch_size)

    # guardamos el modelo entrenado
    modelo.save_weights('first_try.h5')

    # guardamos la gráfica de accuracy y loss
    dibujar_grafico_accuracy_loss(history)

###########################################################
###########################################################
if __name__ == '__main__':
    # declaración de argumentos de entrada
    ap = argparse.ArgumentParser()
    ap.add_argument("-t", "--rtrain", required=True, help="ruta de train")
    ap.add_argument("-v", "--rvalid", required=True, help="ruta de validation")
    ap.add_argument("-g", "--grafico", type=str, default="plot.png", help="ruta de grafico")
    # parseo de argumentos
    args = vars(ap.parse_args())

    # lanzamos el proceso primcipal
    train_data_dir=args["rtrain"]
    validation_data_dir=args["rvalid"]
    Run()


"""
===============
Basic pie chart
===============

Demo of a basic pie chart plus a few additional features.

In addition to the basic pie chart, this demo shows a few optional features:

    * slice labels
    * auto-labeling the percentage
    * offsetting a slice with "explode"
    * drop-shadow
    * custom start angle

Note about the custom start angle:

The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt

with open ('123.txt', 'r') as f:
    content = f.readlines()
    content = [x.strip() for x in content]
    positive = content[0]
    negative = content[1]

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Positive', 'Negative'
sizes = [positive,negative]

fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()


# We need decorator to work both in and out of class.
# Define decorator as a class instance, we should ensure implenting __call__() and __get__()

import types
from functools import wraps

class Profiled:
	def __init__(self, func):
		wraps(func)(self)
		self.ncalls = 0

	def __call__(self, *args, **kwargs):
		self.ncalls += 1
		return self.__wrapped__(*args, **kwargs)

	def __get__(self, instance, cls):
		if instance is None:
			return self
		else:
			return types.MethodType(self, instance)

# Test
@Profiled
def add(x, y):
	return x + y

class Spam:
	@Profiled
	def bar(self, x):
		print (self, x)

# Test
print (add(2, 3))
print (add(4, 5))
print (add.ncalls)
s = Spam()
s.bar(1)
s.bar(2)
s.bar(3)
print (Spam.bar.ncalls)


from services.ratchet_hub import RatchetHub
import pdb

def get_vantage_config(org, web_port):
    result = """
        # <org> vantage
    rewrite  ^/ratchet/<org>/projects/$  /ratchet/<org>/projects/vantage.html;

    location /ratchet/<org>/projects/ {
        rewrite  ^/ratchet/<org>/projects/(.*)  /$1 break;
        proxy_pass   http://esv4-engtool01.linkedin.biz:<port>;
    }
"""
    result = result.replace("<org>", org)
    result = result.replace("<port>", str(web_port))
    return result

def get_team_config(org, team, web_port):
    result = """
        # <org> <team>
    rewrite  ^/ratchet/<org>/projects/<team>/$ /ratchet/<org>/projects/<team>/qplan.html;

    location /ratchet/<org>/projects/<team>/ {
        rewrite  ^/ratchet/<org>/projects/<team>/(.*)  /$1 break;
        proxy_pass   http://esv4-engtool01.linkedin.biz:<port>;
    }

"""
    result = result.replace("<org>", org)
    result = result.replace("<team>", team)
    result = result.replace("<port>", str(web_port))
    return result

def get_org_config(org, hub_port):
    result = ''
    ratchet_hub = RatchetHub("127.0.0.1", hub_port)
    vantage_info = ratchet_hub.get_vantage_config()
    result = result + get_vantage_config(org, vantage_info['web_port'])

    teams_info = ratchet_hub.get_team_instances_info()
    teams = teams_info.keys()
    teams.sort()
    for team in teams:
        result = result + get_team_config(org, team, teams_info[team]['web_port'])
    return result

if __name__ == "__main__":
    result = ''
    result = result + get_org_config("consumer", 4000)
    #result = result + get_org_config("money", 4010)

    print(result)


from flask import Flask
from flask import jsonify
from flask import request
import requests
app = Flask(__name__)

start = [{}]  #metoda put do modułu czasowego
time  = [{"speed":0,"symTime" : "2019-11-18+18:40:15" }]  #metoda put do modułu czasowego
Tzco = [{"Tzco": 0}] #to będzie pobierał od nas moduł 6
Tpm = [{"Tpm": 0}] #tak samo
impuls = [{"impuls": 0}]
#methods
@app.route('/Tzco', methods=['GET'])
def getTzco():
    return jsonify({'Tzco' : Tzco})

@app.route('/Tpm', methods=['GET'])
def getTpm():
    res = requests.put("http://127.0.0.1:5000/Tzco",json={'Tzco':2137})
    return jsonify({'Tpm' : Tpm})

@app.route('/Tpm', methods=['PUT'])
def editTpm():
    new_Tpm = request.get_json()
    Tpm[0] = new_Tpm
    qs = request.get_json()
    return jsonify({})
@app.route('/Tzco', methods=['PUT'])
def editTzco():
    new_Tzco = request.get_json()
    Tzco[0] = new_Tzco
    qs = request.get_json()
    return jsonify({})

@app.route('/start', methods=['GET'])
def getStart():
    return jsonify({'start' : start})

@app.route('/time', methods=['GET'])
def getTime():
    return jsonify({'time' : time})

@app.route('/impuls', methods=['GET'])
def getimpuls():
    return jsonify({'impuls' : impuls})

@app.route('/impuls', methods=['PUT'])
def editimpuls():
    new_impuls = request.get_json()
    impuls[0] = new_impuls
    qs = request.get_json()
    return jsonify({})

@app.route('/time', methods=['PUT'])
def editTime():
    new_time = request.get_json()
    time[0] = new_time
    qs = request.get_json()
    impuls = {"impuls": 1}
    return jsonify({})

@app.route('/start', methods=['PUT'])
def editStart():
    new_start = request.get_json()
    start[0] = new_start
    qs = request.get_json()
    impuls[0] = {"impuls": 1}
    return jsonify({})

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


# ------------------------------------------------------------------------------
# Copyright 2020 Rui LIU (@liurui39660)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------------

from copy import deepcopy

from .CountMinSketch import CountMinSketch

class RelationalCore:
	def __init__(self, numRow: int, numColumn: int, factor: float = 0.5) -> None:
		super().__init__()
		self.timestamp = 1
		self.factor = factor
		self.indexEdge = [0] * numRow
		self.indexSource = [0] * numRow
		self.indexDestination = [0] * numRow
		self.numCurrentEdge = CountMinSketch(numRow, numColumn)
		self.numTotalEdge = deepcopy(self.numCurrentEdge)
		self.numCurrentSource = CountMinSketch(numRow, numColumn)
		self.numTotalSource = deepcopy(self.numCurrentSource)
		self.numCurrentDestination = CountMinSketch(numRow, numColumn)
		self.numTotalDestination = deepcopy(self.numCurrentDestination)

	@staticmethod
	def ComputeScore(a: float, s: float, t: float) -> float:
		return 0 if s == 0 or t - 1 == 0 else pow((a - s / t) * t, 2) / (s * (t - 1))

	def __call__(self, source: int, destination: int, timestamp: int) -> float:
		if self.timestamp < timestamp:
			self.numCurrentEdge.MultiplyAll(self.factor)
			self.numCurrentSource.MultiplyAll(self.factor)
			self.numCurrentDestination.MultiplyAll(self.factor)
			self.timestamp = timestamp
		self.numCurrentEdge.Hash(self.indexEdge, source, destination)
		self.numCurrentEdge.Add(self.indexEdge)
		self.numTotalEdge.Add(self.indexEdge)
		self.numCurrentSource.Hash(self.indexSource, source)
		self.numCurrentSource.Add(self.indexSource)
		self.numTotalSource.Add(self.indexSource)
		self.numCurrentDestination.Hash(self.indexDestination, destination)
		self.numCurrentDestination.Add(self.indexDestination)
		self.numTotalDestination.Add(self.indexDestination)
		return max([
			self.ComputeScore(self.numCurrentEdge(self.indexEdge), self.numTotalEdge(self.indexEdge), timestamp),
			self.ComputeScore(self.numCurrentSource(self.indexSource), self.numTotalSource(self.indexSource), timestamp),
			self.ComputeScore(self.numCurrentDestination(self.indexDestination), self.numTotalDestination(self.indexDestination), timestamp),
		])


import tensorflow as tf
import numpy as np

n_inputs = 2
n_steps = 3
n_neurons = 4

X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
X_seqs = tf.unstack(tf.transpose(X, perm=[1,0,2]))
basic_cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons)
output_seqs, states = tf.nn.static_rnn(basic_cell, X_seqs, dtype=tf.float32)
outputs = tf.transpose(tf.stack(output_seqs),perm=[1,0,2])
init = tf.global_variables_initializer()

X_batch = np.random.randn(20,n_steps,n_inputs)
with tf.Session() as sess:
    init.run()
    writer = tf.summary.FileWriter("./logs/test", sess.graph)
    sess.run(writer, feed_dict={X:X_batch})
    _outputs = sess.run(outputs, feed_dict={X:X_batch})
    _states = sess.run(states, feed_dict={X:X_batch})
    print(_outputs)
    print()
    print(_states)


# uncompyle6 version 3.7.4
# Python bytecode 3.4 (3310)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/stas/workspace/partners/flask_restframework/flask_restframework/filter_backends.py
# Compiled at: 2017-07-14 09:11:18
# Size of source mod 2**32: 2741 bytes
import json
from flask_restframework.queryset_wrapper import MongoDbQuerySet

class BaseBackend:

    def __init__(self, qs, request, resource):
        self.qs = qs
        self.request = request
        self.resource = resource

    def filter(self):
        raise NotImplementedError

class OrderingBackend(BaseBackend):
    __doc__ = '\n    Allows ordering with GET parameter.\n    For example,\n\n        GET ?ordering=name,-value\n\n    Will sort .order_by(["name", "-value"])\n\n    You can set resource attribute **ordering** if you want default ordering\n    '

    def _default_ordering(self):
        if hasattr(self.resource, 'ordering'):
            return self.resource.ordering
        return []

    def filter(self):
        try:
            ordering_fields = self.request.args.get('ordering')
            if ordering_fields:
                ordering_fields = ordering_fields.split(',')
            else:
                ordering_fields = []
        except:
            ordering_fields = []

        ordering_fields = ordering_fields or self._default_ordering()
        if ordering_fields:
            self.qs = self.qs.order_by(*ordering_fields)
        return self.qs

class JsonFilterBackend(BaseBackend):
    __doc__ = '\n    Allows custom filtration with json_filter GET parameter.\n    For example:\n\n        GET ?json_filters={"name": "blablabla"}\n\n    will filter queryset in this way:\n\n        .filter(__raw__={"name": "blablabla"})\n\n    You can manage filter logig with Resource attribute update_json_filter which accepts\n    (json_filter)->new_json_filter\n\n    .. warning::\n\n        This filter can be used only with :class:`.MongoDbQuerySet`\n\n    '
    qs = None

    def filter(self):
        try:
            json_filter = self.request.args.get('json_filters')
            json_filter = json.loads(json_filter)
        except:
            return self.qs

        assert isinstance(self.qs, MongoDbQuerySet)
        if hasattr(self.resource, 'update_json_filter'):
            json_filter = self.resource.__class__.update_json_filter(json_filter)
        self.qs = MongoDbQuerySet.from_queryset(self.qs.data.filter(__raw__=json_filter))
        return self.qs

class SearchFilterBackend(BaseBackend):
    __doc__ = '\n    Allows custom filtration with search GET parameter.\n    For example:\n\n        GET ?search="search text"\n\n    will filter queryset in this way:\n\n        .filter(__raw__={"$text": {"$search": search_text}})\n\n    '

    def filter(self):
        try:
            search_text = self.request.args.get('search')
        except:
            search_text = ''

        if search_text:
            self.qs = self.qs.filter(__raw__={'$text': {'$search': search_text}})
        return self.qs


from rest_framework import generics
from rest_framework.permissions import IsAuthenticatedOrReadOnly

from posts.api.serializers import PostSerializer, CommentSerializer, UpvoteSerializer
from posts.api.premissions import IsAuthorOrAdminOrReadOnly, IsAuthenticatedOrAdmin
from posts.models import Post, Comment, Upvote

class PostListView(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

class PostDetailsView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthorOrAdminOrReadOnly]
    lookup_field = "slug"

class CommentListView(generics.ListCreateAPIView):
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        post_slug = self.kwargs["slug"]
        return Comment.objects.filter(post__slug=post_slug)

    def perform_create(self, serializer):
        post_slug = self.kwargs["slug"]
        post = Post.objects.get(slug=post_slug)
        serializer.save(author=self.request.user, post=post)

class CommentDetailsView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [IsAuthorOrAdminOrReadOnly]

class UpvoteListView(generics.ListCreateAPIView):
    serializer_class = UpvoteSerializer
    permission_classes = [IsAuthenticatedOrAdmin]

    def get_queryset(self):
        post_slug = self.kwargs["slug"]
        return Upvote.objects.filter(post__slug=post_slug)

    def perform_create(self, serializer):
        post_slug = self.kwargs["slug"]
        post = Post.objects.get(slug=post_slug)
        serializer.save(user=self.request.user, post=post)

class UpvoteDetailsView(generics.RetrieveDestroyAPIView):
    queryset = Upvote.objects.all()
    serializer_class = UpvoteSerializer
    permission_classes = [IsAuthenticatedOrAdmin]


import prompt

AMOUNT_OF_TRIES = 3

def check_answer(answer, right_answer):
    return answer == right_answer

def play(get_question_and_answer, description):
    counter = 0
    print('Welcome to the Brain Games!')
    print(description, end='\n\n')
    name = prompt.string('May I have your name? ')
    print('{}, {}!'.format('Hello', name), end='\n\n')

    while counter < AMOUNT_OF_TRIES:
        question, right_answer = get_question_and_answer()
        print('Question: ' + question)
        answer = prompt.string('Your answer: ')

        if check_answer(answer, right_answer):
            print('Correct!')
            counter += 1
        else:
            print(str(answer) + ' is wrong answer ;(. Correct answer was ' + str(right_answer))
            print("Let's try again, " + name + '!')
    else:
        print('{}, {}!'.format('Congratulations', name))


import sqlite3

class SQLite:

	def __init__(self,db_path):
		self.sql = sqlite3.connect(db_path)
		self.cur = self.sql.cursor()

	def init(self):
		try:
			self.cur.execute("""CREATE TABLE user_msg (
					email       VARCHAR(30) ,
					from_mail   VARCHAR(30) ,
					message     varchar(600),
					ip_from     varchar(20) ,
					datetime_    varchar(30)
				);
				""")
		except:
			pass

	def inserMessage(self,to,from_,mesg,ip,datetime):
		self.cur.execute(
				"""INSERT INTO
				user_msg (`email`,`from_mail`,`message`,`ip_from`,`datetime_`)
				VALUES (?,?,?,?,?)
				""",(to,from_,mesg,ip,datetime)
			);self.sql.commit()

	def selectByUser(self):
		self.cur.execute("SELECT * FROM user_msg ");
		return self.cur.fetchall()


# Support for py 2 and 3
from __future__ import division, print_function, unicode_literals

# Common Imports
import os
import numpy as np

# ML Imports

# Graph Imports
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

# Config
PROJECT_ROOT_DIRECTORY = '.'

# Define Functions

def image_path(fig_id):
    if not os.path.exists('images'):
        os.makedirs('images')
    return os.path.join(PROJECT_ROOT_DIRECTORY, 'images', fig_id)

def save_fig(fig_id, tight_layout=True):
    print("Saving", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(image_path(fig_id) + ".png", format='png', dpi=300)

# Set plots
angle = np.pi / 5
stretch = 5
m = 200

np.random.seed(3)
X = np.random.randn(m, 2) / 10
X = X.dot(np.array([[stretch, 0], [0, 1]]))
X = X.dot([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])

u1 = np.array([np.cos(angle), np.sin(angle)])
u2 = np.array([np.cos(angle - 2 * np.pi / 6), np.sin(angle - 2 * np.pi / 2)])
u3 = np.array([np.cos(angle - np.pi / 2), np.sin(angle - np.pi / 2)])

X_proj1 = X.dot(u1.reshape(-1, 1))
X_proj2 = X.dot(u2.reshape(-1, 1))
X_proj3 = X.dot(u3.reshape(-1, 1))

plt.figure(figsize=(8, 4))
plt.subplot2grid((3, 2), (0, 0), rowspan=3)
plt.plot(
    [-1.4, 1.4], [-1.4 * u1[1] / u1[0], 1.4 * u1[1] / u1[0]],
    "k-",
    linewidth=1)
plt.plot(
    [-1.4, 1.4], [-1.4 * u2[1] / u2[0], 1.4 * u2[1] / u2[0]],
    "k--",
    linewidth=1)
plt.plot(
    [-1.4, 1.4], [-1.4 * u3[1] / u3[0], 1.4 * u3[1] / u3[0]],
    "k:",
    linewidth=2)
plt.plot(X[:, 0], X[:, 1], "bo", alpha=0.5)
plt.axis([-1.4, 1.4, -1.4, 1.4])
plt.arrow(
    0,
    0,
    u1[0],
    u1[1],
    head_width=0.1,
    linewidth=5,
    length_includes_head=True,
    head_length=0.1,
    fc='k',
    ec='k')
plt.arrow(
    0,
    0,
    u3[0],
    u3[1],
    head_width=0.1,
    linewidth=5,
    length_includes_head=True,
    head_length=0.1,
    fc='k',
    ec='k')
plt.text(u1[0] + 0.1, u1[1] - 0.5, r"$\mathbf{c_2}$", fontsize=22)
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$x_2$", fontsize=18, rotation=0)
plt.grid(True)

plt.subplot2grid((3, 2), (0, 1))
plt.plot([-2, 2], [0, 0], "k-", linewidth=1)
plt.plot(X_proj1[:, 0], np.zeros(m), "bo", alpha=0.3)
plt.gca().get_xaxis().set_ticks([])
plt.gca().get_yaxis().set_ticklabels([])
plt.axis([-2, 2, -1, 1])
plt.grid(True)

plt.subplot2grid((3, 2), (1, 1))
plt.plot([-2, 2], [0, 0], "k--", linewidth=1)
plt.plot(X_proj2[:, 0], np.zeros(m), "bo", alpha=0.3)
plt.gca().get_yaxis().set_ticks([])
plt.gca().get_xaxis().set_ticklabels([])
plt.axis([-2, 2, -1, 1])
plt.grid(True)

plt.subplot2grid((3, 2), (1, 1))
plt.plot([-2, 2], [0, 0], "k--", linewidth=1)
plt.plot(X_proj2[:, 0], np.zeros(m), "bo", alpha=0.3)
plt.gca().get_yaxis().set_ticks([])
plt.gca().get_xaxis().set_ticklabels([])
plt.axis([-2, 2, -1, 1])
plt.grid(True)

plt.subplot2grid((3, 2), (2, 1))
plt.plot([-2, 2], [0, 0], "k:", linewidth=1)
plt.plot(X_proj3[:, 0], np.zeros(m), "bo", alpha=0.3)
plt.gca().get_yaxis().set_ticks([])
plt.axis([-2, 2, -1, 1])
plt.xlabel("$z_1$", fontsize=18)
plt.grid(True)

save_fig("pca_best_projection")
plt.show()


#!/usr/bin/env python3
"""
Copyright 2020 Conversando Na Nuvem (https://www.youtube.com/channel/UCuI2nDGLq_yjY9JNsDYStMQ/) - Leandro Damascena

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------

This script manages aws-network-discovery, a tool for analyzing VPC dependencies.
"""
import sys
import argparse

# Check version
if sys.version_info < (3, 6):
    print("Python 3.6 or newer is required", file=sys.stderr)
    sys.exit(1)

from commands.vpc import Vpc

__version__ = "0.2.1"

def show_options(args="sys.argv[1:]"):
    parser = argparse.ArgumentParser()
    parser.add_argument(
                        "-v",
                        "--vpc-id",
                        required=True,
                        help="Inform VPC to analyze"
                        )
    parser.add_argument(
                        "-r",
                        "--region-name",
                        required=False,
                        help="Inform REGION to analyze. If not informed, try to get from config file"
                        )
    options = parser.parse_args()

    return options

def main():
    """Entry point for the CLI."""

    # Load commands
    if len(sys.argv) <= 1:
        options = show_options(args=['-h'])

    args = show_options(sys.argv)

    vpc = Vpc(vpc_id=args.vpc_id, region_name=args.region_name)
    vpc.run()

if __name__ == "__main__":
    main()


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: M:\Programming\Project\django-auth\auth\CustomAuth\migrations\0002_date_joined_auto_now_add.py
# Compiled at: 2019-12-09 12:37:18
# Size of source mod 2**32: 442 bytes
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [
     ('CustomAuth', '0001_initial')]
    operations = [
     migrations.AlterField(model_name='user',
       name='date_joined',
       field=models.DateTimeField(auto_now_add=True, null=True, verbose_name='join date'))]


# coding: utf-8
# Created by Jabok @ August 14th 2014
# fetcher.py
import os
import toml
from validators import validate_specs
from comic import Comic
from linkers import findlink
from images import findimages
from getter import Getter
from finder import Identifier
from bs4 import BeautifulSoup
from utils import lastcomicfile
"""
Initiates the fetching of a comic, attempting to generate the schema if necessary.
"""
_getter = Getter(timeout=5)

def findcontent(url, link_identifier, progress_identifier):
    """Finds image url and the link to the next page at the given web address."""
    # Url should be a full url path for correct url joining!
    image, nextpage = None, None
    soup = BeautifulSoup(_getter.get(url))
    nextpage = findlink(soup, url, link_identifier)
    if not (image and newpage): raise Exception("Nothing Found!")
    return image, nextpage

def fetchcomic(request, overwrite=False, startpage=None,
    pages=-1):
    """Fetches the comic described in the given request"""
    from utils import getcomiclist, printiter
    # If it is not a comic name that is known
    if os.path.exists(request):
        with open(request) as f:
            specs = toml.load(f)
        title = specs['title']
        directory = os.path.dirname(request) or os.getcwd()
    else:
        title = request.strip()
        directory = os.getcwd()

    if (not title in getcomiclist()) or overwrite:
        if not os.path.exists(request):
            return print("Could not find any specfile or comic '{0}'!".format(request))

        # Validate the given specification
        print("Validating... ", end="")
        valid, errors = validate_specs(specs, directory=directory)
        print("OK" if valid else "FAILED")
        if not valid:
            print("Cannot fetch a comic from the given spec due to the following errors:")
            return printiter(errors)

        Comic.create(specs, directory=directory)

    print("Preparing scrape...")
    with Comic.load(title) as comic:
        print("- Comic:", comic)
        link_identifier     = Identifier.load(comic.progress['link_identifier'])
        image_identifier    = Identifier.load(comic.progress['image_identifier'])

        lastimages  = comic.progress['lastimages']
        remaining   = pages
        reconnect   = comic.progress.get('reconnect', False)
        lastpage    = comic.progress['lastpage']
        if (not lastpage) or startpage: # No previous, or start supplied
            nextpage = startpage or specs['startpage']
            print("- Starting new scrape from", nextpage)
        else:
            print("- Resuming scrape from", lastpage)
            data        = _getter.get_read(lastpage)
            soup        = BeautifulSoup(data)
            nextpage    = findlink(soup, lastpage, link_identifier)

        # Do the actual scraping
        try:
            if nextpage:
                pagestamp = "({0} pages)".format(pages) if (pages != -1) else ""
                print("Starting scrape..."+pagestamp)

            while nextpage and remaining: # There is a way!
                print("- {0:03}: {1}".format(comic.progress['lastindex']+1, nextpage))
                data        = _getter.get_read(nextpage, reconnect=reconnect)
                soup        = BeautifulSoup(data)
                imageurls   = findimages(soup, nextpage, image_identifier)
                if not imageurls:
                    print("No images found at '{0}'! Ending...".format(nextpage))
                    break
                if imageurls == lastimages:
                    print("Image duplicates found at '{0}'! Ending...".format(nextpage))
                    break
                for url in imageurls:
                    comic.add(url, reconnect=reconnect)
                comic.setscraped(nextpage, imageurls)
                lastimages  = imageurls # Don't repeat content!
                lastpage    = nextpage
                nextpage    = findlink(soup, nextpage, link_identifier)
                if nextpage == lastpage:
                    print("No further links found at '{0}'! Ending...".format(lastpage))
                    break
                remaining  -= 1
            lastpage = comic.progress['lastpage']
            print("No more comics found after '{0}', ending...".format(lastpage))
        except KeyboardInterrupt:
            print("\nInterrupted!")
            print("Progress:")
            print("- Last page: ", comic.progress['lastpage'])
            print("- Last index:", comic.progress['lastindex'])
            print("Closing...", end=" ")
        except Exception as e:
            print("CAUGHT EXCEPTION!")
            print("Closing...", end=" ")
            raise

    meta = {"lastcomic": title}
    with open(lastcomicfile, "w") as f:
        toml.dump(meta, f)
    print("Scrape ended.")


# -*- coding: utf-8 -*-

# django imports
from django.conf import settings
from django.utils.translation import get_language, to_locale

def project_data(request):
    return {
        'PROJECT_NAME': settings.PROJECT_NAME,
        'GOOGLE_ANALYTICS_TRACKING_ID': settings.GOOGLE_ANALYTICS_TRACKING_ID,
    }

def languages(request):
    lang_code = get_language()
    return {
        'LANGUAGE_CODE': lang_code,
        'LOCALE': to_locale(lang_code),
        'LANGUAGES': settings.LANGUAGES,
    }


import jwt
from rest_framework.permissions import BasePermission as DRFBasePermission
from authen.models import Member
from cook_intra import settings_base

class BasePermission(DRFBasePermission):
    def has_permission(self, request, view):  # 사용자 지정 권한
        if view.action == "join":             # view.action  조인
            return True  # permission True
        else:
            token = request.data.get("token", None)
            if not token:
                return False
            try:
                user_info = jwt.decode(token, settings_base.SECRET_KEY, algorithms=['HS256'])  # jwt token decode
                user = Member.objects.get(user_info["username"])
                request.user = user
                return True
            except Exception as e:
                return False

    def has_object_permission(self, request, view, obj):
        token = request.data.get("token", None)
        if not token:
            return False
        try:
            user_info = jwt.decode(token, settings_base.SECRET_KEY, algorithms=['HS256'])  # jwt token decode
            user = Member.objects.get(user_info["username"])
            request.user = user
            return True
        except Exception as e:
            return False


from keras.datasets import reuters
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras. layers import Dense, Embedding, LSTM, Flatten

#1. 데이터
(x_train,y_train),(x_test,y_test) = reuters.load_data(num_words=10000, test_split = 0.2)
# 가장 빈도수가 많은 것부터 1000번쨰까지

print(x_train.shape, x_test.shape)  #(8982,), (2246,)
print(y_train.shape, y_test.shape)  #(8982,), (2246,)

print(x_train[0])
print(y_train[0])

#list는 shape구할 수 없다

print(len(x_train[0])) # 87

# y의 카테고리 개수 출력
category = np.max(y_train) + 1
print("카테고리:",category) #46개

# y의 유니크한 값을 출력
y_bunpo = np.unique(y_train)
print(y_bunpo)

y_train_pd = pd.DataFrame(y_train)
bbb = y_train_pd.groupby(0)[0].count()
print(bbb)
print(bbb.shape)

# 주간과제: groupby()의 사용법 숙지할 것

########################################

from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical

####다시 해보기
x_train = pad_sequences(x_train, maxlen=100, padding='pre') #maxlen - 최대값을 100으로 잡는다. / truncating - ex)100개가 넘는 문자열 자를 때(default = 앞에서부터)
# 여기서는 87개이기 때문에 truncating 필요 없다
x_test = pad_sequences(x_test, maxlen=100, padding='pre')

print(len(x_train[0]))  #87
print(len(x_train[-1])) #105

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

print(x_train.shape, x_test.shape) #(8982,100), (2246,100)

#2. 모델
model = Sequential()
# model.add(Embedding(1000, 100, input_length=100))
model.add(Embedding(1000,100))
# parameter 개수가 너무 커져도 좋지 않고 알아서 판단해야함
# word+_size 통상적으로 들어가는 단어 개수 넣어주는 것
# output*word_size=첫번째 파라미터 개수
# input_length안 써주면 x_train의  input_length 값을 자연스럽게 가져옴
# Embedding은 3차
model.add(LSTM(100))
model.add(Dense(46, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['acc']) #sparse_categorical_crossentropy

history = model.fit(x_train,y_train,batch_size=100,epochs=10, validation_split=0.2)

acc = model.evaluate(x_test,y_test)[1]
print("acc:",acc)

y_val_loss = history.history['val_loss']
y_loss = history.history['loss']

plt.plot(y_val_loss,marker=',',c='red',label='TestSet loss')
plt.plot(y_loss,marker=',',c='blue',label='Trainset loss')
plt.legend(loc='upper right')
plt.grid()
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()

# 8000개로 훈련, 2000여개로 맞추는 것


from pyrealtime.decode_layer import DecodeLayer
from pyrealtime.input_layers import InputLayer
from pyrealtime.layer_manager import LayerManager
from pyrealtime.plot_layer import SimplePlotLayer, FigureManager
import numpy as np

from pyrealtime.utility_layers import BufferLayer

def gen_dummy_data(counter):
    data = np.random.randn(4)
    return data

def decoder(data):
    return {'x1': data[0], 'x2': data[1:]}

def plot_config(ax):
    ax.set_ylim(-2, 2)

def create_fig(fig):
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    return {'x1': ax1, 'x2': ax2}

def main():
    input_layer = InputLayer(gen_dummy_data, rate=30, name="dummy input")
    split_layer = DecodeLayer(input_layer, decoder=decoder, name="decoder")
    buffer_1 = BufferLayer(split_layer.get_port('x1'), buffer_size=100, name="buffer1")
    buffer_2 = BufferLayer(split_layer.get_port('x2'), buffer_size=100, name="buffer2")
    fig_manager = FigureManager(create_fig=create_fig)
    SimplePlotLayer(buffer_1, plot_key='x1', plot_config=plot_config, fig_manager=fig_manager)
    SimplePlotLayer(buffer_2, plot_key='x2', plot_config=plot_config, fig_manager=fig_manager)
    LayerManager.run()

if __name__ == "__main__":
    main()


import sqlparse
import re
import csv
from functools import cmp_to_key
from math import inf
database = {}
def fill_db_meta(meta):
    with open(meta,"r") as f:
        metadata = f.readlines()
    lines = len(metadata)
    i=0
    while(i<lines):
        if "<begin_table>" in metadata[i]:
            i=i+1
            table = {}
            database[metadata[i].strip()] = table
            table["cols"] = {}
            table["cols_order"] = []
            i=i+1
            while True:
                if "<end_table>" in metadata[i].strip():
                    break
                table["cols"][metadata[i].strip()]=[]
                table["cols_order"].append(metadata[i].strip())
                i=i+1

        i=i+1

aggrs = {"sum":0,"avg":1,"max":2,"min":3,"count":4}
def fill_db_data():
    for table in database.keys():
        with open(table+".csv","r") as f:
            data = csv.reader(f)
            for row in data:
                for i in range(len(row)):
                    database[table]["cols"][database[table]["cols_order"][i]].append(int(row[i]))

def recur(tables,newrow,newtable):
    if(len(tables)==0):
        newtable.append(newrow)
        return
    curtable = tables[0]
    temprow=newrow[:]
    for j in range(len(curtable["cols"][curtable["cols_order"][0]])):
        for i in range(len(curtable["cols_order"])):
            newrow.append(curtable["cols"][curtable["cols_order"][i]][j])
        recur(tables[1:],newrow,newtable)
        newrow=temprow[:]

def join_tables(tablelist):
    newtable={}
    newtable["cols"] = {}
    newtable["rows"] = []
    tables = []
    for table in tablelist:
        tables.append(database[table])
    i=0
    for table in tables:
        for col in range(len(table["cols_order"])):
            newtable["cols"][table["cols_order"][col]] = i
            newtable["cols"][i] = table["cols_order"][col]
            i+=1
    recur(tables,[],newtable["rows"])
    return newtable

def f_count(newtable,cmd):
        return len(newtable["rows"])

def f_sum(newtable,cmd):
    sums = 0
    pos = newtable["cols"][cmd.strip()]
    for row in newtable["rows"]:
            sums+=row[pos]
    return sums

def f_avg(newtable,cmd):
    sums = f_sum(newtable,cmd)
    n = len(newtable["rows"])
    avg = sums/n
    return avg

def f_max(newtable,cmd):
    maxs = -inf
    pos = newtable["cols"][cmd.strip()]
    for row in newtable["rows"]:
            maxs = max(maxs,row[pos])
    return maxs

def f_min(newtable,cmd):
    mins = inf
    pos = newtable["cols"][cmd.strip()]
    for row in newtable["rows"]:
            mins = min(mins,row[pos])
    return mins

def aggr(newtable,params):
    cmd = [i.strip() for i in re.split("\(|\)",params) if i.strip()!=""]
    res = 0
    if(cmd[0]=="count"):
        res= f_count(newtable,cmd[1])
    elif(cmd[0]=="sum"):
        res= f_sum(newtable,cmd[1])
    elif(cmd[0]=="avg"):
        res= f_avg(newtable,cmd[1])
    elif(cmd[0]=="max"):
        res= f_max(newtable,cmd[1])
    elif(cmd[0]=="min"):
        res= f_min(newtable,cmd[1])
    return res

def group_by_parse(group_by_part,newtable):
    cmd = group_by_part.split(",")
    pos = [newtable["cols"][i.strip()] for i in cmd]

def order_by_parse(order_by_part,newtable):
    cmd = order_by_part.split(",")
    cmd = [i.split() for i in cmd]
    print(cmd)
    def comp(val1,val2):
        for i in cmd:
            if(len(i)==1):
                pos = newtable["cols"][i[0]]
                if(val1[pos] < val2[pos]):
                    return -1
                elif(val1[pos] > val2[pos]):
                    return 1
            else:
                pos = newtable["cols"][i[0]]
                if "desc" in i:
                    if(val1[pos] > val2[pos]):
                        return -1
                    elif(val1[pos] < val2[pos]):
                        return 1
                else:
                    if(val1[pos] < val2[pos]):
                        return -1
                    elif(val1[pos] > val2[pos]):
                        return 1
        return 0
    newtable["rows"].sort(key=cmp_to_key(comp))

def show_table(newtable):
    newtable["rows"].insert(0,newtable["ord"])
    for row in newtable["rows"]:
        for els in row:
            if(els==None):
                print("",end="\t")
            else:
                print(els,end="\t")
        print("")

def where_parse(where_part,newtable):
    temp = where_part
    where_part = re.split("and|or",where_part)
    where_part = [i.strip() for row in where_part for i in re.split("<=|>=|!=|==|<|>",row) if i.strip() != ""]
    print(where_part)
    temptable = []
    for row in newtable["rows"]:
        tempstr = temp
        for els in where_part:
            if(els.isnumeric()):
                pass
            else:
                val = row[int(newtable['cols'][els])]
                tempstr = tempstr.replace(els,str(val))
        if(eval(tempstr)):
            temptable.append(row)

    newtable["rows"] = temptable

def make_distinct(newtable):
    b = []
    for row in newtable["rows"]:
        if row not in b:
            b.append(row)
    newtable["rows"] = b

def select_parse(select_part,newtable):
    isdistict = False
    isaggr = False
    if "distinct" in select_part:
        isdistict = True
    col_list = [cols.strip() for temp in re.split("distinct",select_part) for cols in temp.split(",") if (cols.strip() != "")]
    if(len(col_list)==0):
        print("No column selected")
    if(len(col_list)==1 and col_list[0] == "*"):
        newrow = []
        for i in newtable["cols"].keys():
            if(str(i).isnumeric()):
                pass
            else:
                newrow.append(i)

        if(isdistict):
            make_distinct(newtable)

        newtable["ord"]=newrow
        ord = {}
        for i in range(len(newrow)):
            ord[newrow[i]] = i
            ord[i] = newrow[i]
        newtable["cols"] = ord
        return

    temptable=[]
    for j in col_list:
        temp = re.split("\(|\)",j)[0].strip()
        try:
            aggrs[temp]
            isaggr=True
        except KeyError:
            pass
    if(isaggr):
        temprow=[]
        for j in col_list:
            temp = re.split("\(|\)",j)[0].strip()
            print(temp)
            try:
                aggrs[temp]
                temprow.append(aggr(newtable,j))
            except KeyError:
                try:
                    temprow.append(newtable["row"][0][newtable["cols"][j]])
                except KeyError:
                    temprow.append(None)

        newtable["rows"][:] = [col_list,temprow]
    else:
        for i in newtable["rows"]:
            temprow=[]
            for j in col_list:
                temprow.append(i[newtable["cols"][j]])
            temptable.append(temprow)
        newtable["rows"] = temptable
    if(isdistict):
        make_distinct(newtable)

    newtable["ord"]=col_list
    ord = {}
    for i in range(len(col_list)):
        ord[col_list[i]] = i
        ord[i] = col_list[i]
    newtable["cols"] = ord

def parse(query):
    query = sqlparse.format(query,keyword_case  = 'lower')
    if ";" not in query:
        print("No ;")
        return
    if "select" not in query or "from" not in query:
        print("No select or from")
        return
    select_part=""
    tables=[]
    from_part=""
    where_part=""
    group_by_part=""
    order_by_part=""
    query =  query.strip(";")
    q = query

    select_part = re.split("select",q)[1].strip()
    from_part = re.split("from",select_part)
    select_part = from_part[0].strip()
    from_part = from_part[1].strip()
    if "where" in from_part:
        where_part = re.split("where",from_part)[1].strip()
        where_part = re.split("group by|order by",where_part)[0].strip()
    from_part = re.split("where|group by|order by",from_part)[0].strip()
    if "order by" in q:
        order_by_part = re.split("order by",q)[1].strip()
    if "group by" in q:
        if order_by_part=="":
            group_by_part = re.split("group by",q)[1].strip()
        else:
            group_by_part = re.split("group by",q)[1]
            group_by_part = re.split("order by",group_by_part)[0].strip()

    tables = [tabs.strip() for tabs in from_part.split(",")]
    newtable = join_tables(tables)
    if(len(newtable["cols"]) == 0):
        print("No such tables")
        return
    if(where_part):
        where_parse(where_part,newtable)
    if(group_by_part):
        group_by_parse(group_by_part,newtable)
    select_parse(select_part,newtable)
    if(order_by_part):
        order_by_parse(order_by_part,newtable)

    show_table(newtable)

while True:
    fill_db_meta("metadata.txt")
    fill_db_data()
    q = input()
    parse(q)


"""
Flat text button GUI element.
"""

from PIL import ImageDraw

import arcade
from .button_abstract import ButtonAbstract
from .theme import Theme

class FlatTextButton(ButtonAbstract):
    """ Flat button with text """
    def __init__(self,
                 text,
                 center_x,
                 center_y,
                 width,
                 height,
                 theme: Theme
                 ):
        super().__init__(center_x, center_y)

        assert theme.text_color is not None
        assert theme.background_color is not None
        assert theme.text_color_mouse_over is not None
        assert theme.background_color_mouse_over is not None

        text_image_normal = arcade.get_text_image(text,
                                                  theme.text_color,
                                                  width=width,
                                                  height=height,
                                                  align="center",
                                                  valign="middle",
                                                  background_color=theme.background_color,
                                                  font_size=theme.font_size,
                                                  font_name=theme.font_name)
        text_image_mouse_over = arcade.get_text_image(text,
                                                      theme.text_color_mouse_over,
                                                      width=width,
                                                      height=height,
                                                      align="center",
                                                      valign="middle",
                                                      background_color=theme.background_color_mouse_over,
                                                      font_size=theme.font_size,
                                                      font_name=theme.font_name)
        text_image_mouse_press = arcade.get_text_image(text,
                                                       text_color=theme.text_color_mouse_press,
                                                       width=width,
                                                       height=height,
                                                       align="center",
                                                       valign="middle",
                                                       background_color=theme.background_color_mouse_press,
                                                       font_size=theme.font_size,
                                                       font_name=theme.font_name)

        rect = [0, 0, text_image_normal.width - theme.border_width / 2, text_image_normal.height - theme.border_width / 2]

        if theme.border_color and theme.border_width:
            d = ImageDraw.Draw(text_image_normal)
            d.rectangle(rect, fill=None, outline=theme.border_color, width=theme.border_width)

        if theme.border_color_mouse_over:
            d = ImageDraw.Draw(text_image_mouse_over)
            d.rectangle(rect, fill=None, outline=theme.border_color_mouse_over, width=theme.border_width)

        if theme.border_color_mouse_press:
            d = ImageDraw.Draw(text_image_mouse_press)
            d.rectangle(rect, fill=None, outline=theme.border_color_mouse_press, width=theme.border_width)

        self.texture = arcade.Texture(image=text_image_normal, name=text)
        self.normal_texture = self.texture
        self.mouse_press_texture = arcade.Texture(image=text_image_mouse_press, name=text+"4")
        self.mouse_over_texture = arcade.Texture(image=text_image_mouse_over, name=text+"5")


# ====================================================================
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ====================================================================

import sys, lucene, unittest
from PyLuceneTestCase import PyLuceneTestCase

from org.apache.lucene.analysis.core import WhitespaceAnalyzer
from org.apache.lucene.document import Document
from org.apache.lucene.index import DirectoryReader, IndexWriterConfig
from org.apache.pylucene.index import PythonIndexDeletionPolicy

class MyDeletionPolicy(PythonIndexDeletionPolicy):

    onInitCalled = False
    onCommitCalled = False

    def onInit(self, commits):
      self.onInitCalled = True

    def onCommit(self, commits):
      self.onCommitCalled = True

class IndexDeletionPolicyTestCase(PyLuceneTestCase):

    def getConfig(self, analyzer):

        self.policy = MyDeletionPolicy()
        config = IndexWriterConfig(self.TEST_VERSION, analyzer)
        config.setIndexDeletionPolicy(self.policy)

        return config

    def testIndexDeletionPolicy(self):

        writer = self.getWriter()

        # no commits exist in the index yet
        self.assertTrue(self.policy.onInitCalled)
        # we haven't called commit yet
        self.assertFalse(self.policy.onCommitCalled)

        doc = Document()
        writer.addDocument(doc)
        writer.commit()

        # now we called commit
        self.assertTrue(self.policy.onCommitCalled)

        # external IR sees 1 commit:
        self.assertEquals(1, DirectoryReader.listCommits(self.directory).size())

        # commit again:
        writer.addDocument(doc)
        writer.commit()

        # external IR sees 2 commits:
        self.assertEquals(2, DirectoryReader.listCommits(self.directory).size())

        writer.close()

        # open same index, make sure both commits survived:
        writer = self.getWriter()

        self.assertTrue(self.policy.onInitCalled)
        self.assertFalse(self.policy.onCommitCalled)
        self.assertEquals(2, DirectoryReader.listCommits(self.directory).size())
        writer.close()

        # 3 from closing writer again
        self.assertEquals(3, DirectoryReader.listCommits(self.directory).size())

if __name__ == "__main__":
    lucene.initVM()
    if '-loop' in sys.argv:
        sys.argv.remove('-loop')
        while True:
            try:
                unittest.main()
            except:
                pass
    else:
         unittest.main()


import pandas as pd
import os
import json

# remove retweets for file in test folder and export result to no_retweets

PATH = '/Users/peaceforlives/Documents/Projects/cyberbullying/data/'
infile = 'test/'
outfile='no_retweets/'
filename='tweets_some.json'

def remove_tweets(PATH, infile, outfile, filename):

    data = pd.read_json(PATH + infile + filename, orient='records', lines=True)
    #data = pd.read_json(PATH + infile + filename)

    df = data[-data.text.str.startswith(('RT'))]
    df.to_json(PATH + outfile + filename, orient='records', lines=True)

#remove_tweets(PATH=PATH, infile=infile, outfile=outfile, filename=filename)

for file in os.listdir(PATH + infile):
    remove_tweets(PATH=PATH, infile=infile, outfile=outfile, filename=file)
    #print(file)


n,c=map(int, input().split())
al=[int(input()) for _ in range(n)]
ans=10**18
for i in range(1,11):
    for j in range(1,11):
        if i==j:continue
        v=0
        for k in range(n):
            if k%2==0 and al[k]!=i:v+=c
            if k%2==1 and al[k]!=j:v+=c
        ans=min(ans,v)
print(ans)


import graphene
from django.core.exceptions import ValidationError
from django.core.exceptions import ObjectDoesNotExist

from ...checkout.models import Checkout, CheckoutLine
from ...product.models import ProductVariant
from .types import CheckoutLineType, CheckoutType

class CheckoutLineCreateInput(graphene.InputObjectType):
    quantity = graphene.Int(required=True, description="The number of items purchased.")
    variant_id = graphene.ID(required=True, description="ID of the product variant.")

class CheckoutCreateInput(graphene.InputObjectType):
    user_email = graphene.String()
    lines = graphene.List(CheckoutLineCreateInput, required=True)

class CheckoutCreate(graphene.Mutation):
    checkout = graphene.Field(CheckoutType)

    class Arguments:
        input = CheckoutCreateInput(required=True)

    @classmethod
    def mutate(cls, root, info, input):
        lines = input.pop('lines')
        checkout = Checkout.objects.create(**input)

        checkout_lines = []
        for line in lines:
            checkout_lines.append(
                CheckoutLine(checkout_id=checkout.id, **line)
            )
        checkout.lines.bulk_create(checkout_lines)
        return CheckoutCreate(checkout=checkout)

class CheckoutLineCreate(graphene.Mutation):
    checkout_line = graphene.Field(CheckoutLineType)

    class Arguments:
        input = CheckoutLineCreateInput(required=True)
        checkout_id = graphene.ID(required=True)

    @classmethod
    def mutate(cls, root, info, input, checkout_id):

        variant_id = input.pop('variant_id')
        input_quantity = input.pop('quantity')

        try:
            checkout_line = CheckoutLine.objects.get(checkout_id=checkout_id, variant=variant_id)
        except ObjectDoesNotExist():
            checkout_line = CheckoutLine.objects.create(
                checkout_id=checkout_id,
                variant_id=variant_id,
                quantity=input_quantity)

            return CheckoutLineCreate(checkout_line=checkout_line)

        quantity = checkout_line.quantity + input_quantity

        checkout_line.quantity = quantity
        checkout_line.save()

        return CheckoutLineCreate(checkout_line=checkout_line)


def rotate_array(arr, n, k):
    rotate_by_block = gcd(n, k)
    print(rotate_by_block)
    for i in range(rotate_by_block):
        j = i
        temp = array[i]
        while True:
            s = (j + k) % n
            if s == i:
                break
            arr[j] = arr[s]
            j = s
        arr[j] = temp

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def rotate_array_using_reversal_algorithm(arr, start, end, k):
    reverse_arr(arr, start, k - 1)
    reverse_arr(arr, k, end)
    reverse_arr(arr, start, end)

def reverse_arr(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1
    return arr

if __name__ == '__main__':
    array = [1, 2, 3, 4, 5]
    # rotate_array(array, len(array), 2)
    # print(array)
    # rotate_array_using_reversal_algorithm(array, 0, len(array)-1, 2)
    # print(array)
    t = int(input())
    for _ in range(t):
        n, pos = tuple(map(int, input().split()))
        array = list(map(int, input().split()))
        rotate_array(array, len(array), 2)


# Name: Alexis Raymond
# Date: Mar 27, 2020
# Exercise: Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word.

##### Method #####
def is_palindrome(word): # returns whether the word is a palindrome or not
	return list(word) == list(word)[::-1] # checks if the word is the same in reverse

def shortest_palindrome(word): # returns the palindrome that can be created by adding the fewest number of letters to the word
	if(is_palindrome(word)): # if the word is already a palindrome, return the word
		return word

	alphabet = 'abcdefghijklmnopqrstuvwxyz' # create a list of all the letters in the alphabet

	possibilities = [] # create an empty list to contain all the possibilities

	for i in range(len(word) + 1): # iterate through the number of letters in the word
		for letter in alphabet: # iterate through the letters in the alphabet
			copy = list(word) # create a copy of the word in the form of a list
			copy.insert(i, letter) # insert the iterated letter in the iterated spot of the word

			if(is_palindrome(''.join(copy))): # if the new word is a palindrome, return it
				return ''.join(copy)

			possibilities.append(''.join(copy)) # if it is not a palindrome, add it to the list of possibilities

	while 1 == 1: # create an infinite loop
		for possibility in possibilities: # iterate through all the possibilities already found
			for i in range(len(possibility) + 1): # iterate through the number of letters in the possibility
				for letter in alphabet: # iterate through the letters in the alphabet
					copy = list(possibility) # create a copy of the possibility in the form of a list
					copy.insert(i, letter) # insert the iterated letter in the iterated spot of the possibility

					if(is_palindrome(''.join(copy))): # if the new word is a palindrome, return it
						return ''.join(copy)

					possibilities.append(''.join(copy)) # if it is not a palindrome, add it to the list of possibilities

##### Testing #####
print("Test #1: google") # display test label
print(shortest_palindrome("google")) # display test result
print("---------------\n") # show a line to separate the tests

print("Test #2: race") # display test label
print(shortest_palindrome("race")) # display test result
print("---------------\n") # show a line to separate the tests

print("Test #3: ab") # display test label
print(shortest_palindrome("ab")) # display test result
print("---------------\n") # show a line to separate the tests

print("Test #4: abc") # display test label
print(shortest_palindrome("abc")) # display test result
print("---------------\n") # show a line to separate the tests

print("Test #5: home") # display test label
print(shortest_palindrome("home")) # display test result