"""
We are writing a tool to help users manage their calendars. Given an unordered list of times of day when people are busy, write a function that tells us the intervals during the day when ALL of them are available.

Each time is expressed as an integer using 24-hour notation, such as 1200 (12:00), 1530 (15:30), or 800 (8:00).

Sample input:

p1_meetings = [
  (1230, 1300),
  ( 845, 900),
  (1300, 1500),
]

p2_meetings = [
  ( 0, 844),
  ( 930, 1200),
  (1515, 1546),
  (1600, 2400),
]

p3_meetings = [
  ( 845, 915),
  (1515, 1545),
  (1235, 1245),
]

p4_meetings = [
  ( 1, 5),
  (844, 900),
  (1515, 1600)
]

schedules1 = [p1_meetings, p2_meetings, p3_meetings]
schedules2 = [p1_meetings, p3_meetings]
schedules3 = [p2_meetings, p4_meetings]

Expected output:

findAvailableTimes(schedules1)
 => [  844,  845 ],
    [  915,  930 ],
    [ 1200, 1230 ],
    [ 1500, 1515 ],
    [ 1546, 1600 ]

findAvailableTimes(schedules2)
 => [    0,  845 ],
    [  915, 1230 ],
    [ 1500, 1515 ],
    [ 1545, 2400 ]

findAvailableTimes(schedules3)
    [  900,  930 ],
    [ 1200, 1515 ]

n = number of meetings per schedule
s = number of schedules
"""
p1_meetings = [
    (1230, 1300),
    (845, 900),
    (1300, 1500),
]
# 0 - 2400
p2_meetings = [
    (0, 844),
    (930, 1200),
    (1515, 1546),
    (1600, 2400),
]

p3_meetings = [
    (845, 915),
    (1515, 1545),
    (1235, 1245),
]

p4_meetings = [
    (1, 5),
    (844, 900),
    (1515, 1600)
]

schedules1 = [p1_meetings, p2_meetings, p3_meetings]
schedules2 = [p1_meetings, p3_meetings]
schedules3 = [p2_meetings, p4_meetings]

def mintohrs(timeList, last):

    try:
        for i in range(len(timeList)):
            if timeList[i] + 1 != timeList[i+1]:
                output.append((timeList[0], timeList[i]+1))
                timeList = timeList[i+1:]
                break
            else:
                continue

        if output[-1][1] != last:
            mintohrs(timeList, last)
    except:
        if timeList[0] != timeList[-1]:
            output.append((timeList[0], timeList[-1]))

    return output

def findAvailableTimes(schedules):
    timeList = [m for m in range(2401)]
    for p in schedules:
        for time in p:
            for i in range(time[0], time[1]):
                try:
                    timeList.remove(i)
                except:
                    pass

    output = mintohrs(timeList, timeList[-1])
    return output

output = []
print(findAvailableTimes(schedules1))

output = []
print(findAvailableTimes(schedules2))

output = []
print(findAvailableTimes(schedules3))


import csv
import json
import os

from flask import Blueprint, request, render_template, \
    abort, jsonify

from app import db, app
from .models import ICD_Object

icd = Blueprint('icd', __name__, url_prefix='/icd')

@icd.route('/')
def index():
    result = []
    term = request.args.get('q', '')
    if term:
        result = ICD_Object.query.filter(ICD_Object.DESCRIPTION.contains(term)).all()
    return render_template('icd/home.html', title="ICD", result=result, value=term)

@icd.route('/code/')
def individual(CODE):
    q = db.session.query(ICD_Object).filter(ICD_Object.ALT_CODE == CODE).one_or_none()
    if q:
        return render_template('icd/ind.html', object=q, title = "ICD" + q.CODE)
    abort(404)

@icd.route('/api')
def icd_api():
    exact = request.args.get('exact')
    q = request.args.get('q')
    res = []
    if exact:
        result = ICD_Object.query.filter(ICD_Object.ALT_CODE == q).one_or_none()
    else:
        result = ICD_Object.query.filter(ICD_Object.ALT_CODE.contains(q)).all()
    for obj in result:
        res += [obj.to_dict()]
    return json.dumps(res)

@icd.route('/upload', methods=['GET', 'POST'])
def file_upload():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            file.save(os.path.join(app.config['DATA_DIR'], file.filename))
            regen(os.path.join(app.config['DATA_DIR'], file.filename))
            return 'Boom goes the dynamite: %s' % file.filename
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

def regen(path):
    db.session.query(ICD_Object).delete()
    db.session.commit()
    with open(path, encoding='utf-8') as f:
        reader = csv.DictReader(f, delimiter='\t')
        for row in reader:
            t = creator(row)
            db.session.add(t)
            db.session.commit()

def creator(d):
    d = {k: v for k, v in d.items() if v}
    numerics = ['USAGE_UK', 'GENDER_MASK', 'MIN_AGE', 'MAX_AGE']
    for k in numerics:
        if k in d.keys():
            d[k] = int(d[k])
    return ICD_Object(d)


from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed
from django.views.decorators.csrf import ensure_csrf_cookie

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser

from .serializers import ShippingSerializer
from .models import ShippingModel
from authentication.models import CustomerModel
from django.contrib.auth.models import User

from rest_framework import status
import jwt
import os

@api_view(['GET'])
def get_shipping(request):
    try:
        shippie = ShippingModel.objects.get(addressee=request.user.id)

    except ShippingModel.DoesNotExist:
        shippie = None

    if shippie:
        address = ShippingSerializer(shippie, many=False)
        return Response(address.data)
    else:
        message = {'message': "No address on record"}
        return Response(message)

@api_view(['POST'])
def create_shipping(request):
    address = request.data
    user = request.user
    # ShippingModel.MultipleObjectsReturned
    user_address = ShippingModel.objects.filter(addressee=user)

    if not user_address.exists():
        try:
            shipping_address = ShippingModel.objects.create(
                addressee=user,
                address=address['address'],
                city=address['city'],
                postal_code=address['postal_code'],
                state=address['state'],
                country=address['country']
            )

            serializer = ShippingSerializer(shipping_address, many=False)
            return Response(serializer.data)
        except:
            message = {'message': 'Field cannot be blank.'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)

    message = {'message': "You already have an address on file"}
    return Response(message)

@api_view(['PUT'])
def update_shipping(request):
    updated_data = request.data
    print(f'Address Data: {updated_data}')
    print(f'User ID: {request.user.id}')

    shipping = ShippingModel.objects.get(addressee_id=request.user.id)

    if updated_data['address'] != "":
        shipping.address = updated_data['address']

    if updated_data['city'] != "":
        shipping.city = updated_data['city']

    if updated_data['state'] != "":
        shipping.state = updated_data['state']

    if updated_data['postal_code'] != "":
        shipping.postal_code = updated_data['postal_code']

    if updated_data['country'] != "":
        shipping.country = updated_data['country']

    shipping.save()
    address_serializer = ShippingSerializer(shipping, many=False).data

    return Response(address_serializer)


#!/usr/bin/python
# Track target(s) for a specified time.

# The *with* keyword is standard in Python 2.6, but has to be explicitly imported in Python 2.5
from __future__ import with_statement

import time
from katcorelib import standard_script_options, verify_and_connect, collect_targets, start_session, user_logger
import katpoint

# Set up standard script options
parser = standard_script_options(usage="%prog [options] <'target/catalogue'> [<'target/catalogue'> ...]",
                                 description='Track one or more sources for a specified time. At least one '
                                             'target must be specified. Note also some **required** options below.')
# Add experiment-specific options
parser.add_option('-t', '--track-duration', type='float', default=60.0,
                  help='Length of time to track each source, in seconds (default=%default)')
parser.add_option('-m', '--max-duration', type='float', default=None,
                  help='Maximum duration of the script in seconds, after which script will end '
                       'as soon as the current track finishes (no limit by default)')
parser.add_option('--repeat', action="store_true", default=False,
                  help='Repeatedly loop through the targets until maximum duration (which must be set for this)')

# Set default value for any option (both standard and experiment-specific options)
parser.set_defaults(description='Target track',dump_rate=0.1)
# Parse the command line
opts, args = parser.parse_args()

if len(args) == 0:
    raise ValueError("Please specify at least one target argument via name ('Cygnus A'), "
                     "description ('azel, 20, 30') or catalogue file name ('sources.csv')")

# Check options and build KAT configuration, connecting to proxies and devices
with verify_and_connect(opts) as kat:
    observation_sources = collect_targets(kat, args)

    # Quit early if there are no sources to observe
    if len(observation_sources.filter(el_limit_deg=opts.horizon)) == 0:
        user_logger.warning("No targets are currently visible - please re-run the script later")
    else:
        # Start capture session, which creates HDF5 file
        with start_session(kat, **vars(opts)) as session:
            session.standard_setup(**vars(opts))
            session.capture_start()

            start_time = time.time()
            targets_observed = []
            # Keep going until the time is up
            keep_going = True
            while keep_going:
                keep_going = (opts.max_duration is not None) and opts.repeat
                targets_before_loop = len(targets_observed)
                # Iterate through source list, picking the next one that is up
                for target in observation_sources.iterfilter(el_limit_deg=opts.horizon):
                    session.label('track')
                    user_logger.info("Initiating %g-second track on target '%s'" % (opts.track_duration, target.name,))
                    # Split the total track on one target into segments lasting as long as the noise diode period
                    # This ensures the maximum number of noise diode firings
                    total_track_time = 0.
                    while total_track_time < opts.track_duration:
                        next_track = opts.track_duration - total_track_time
                        # Cut the track short if time ran out
                        if opts.max_duration is not None:
                            next_track = min(next_track, opts.max_duration - (time.time() - start_time))
                        if opts.nd_params['period'] > 0:
                            next_track = min(next_track, opts.nd_params['period'])
                        if next_track <= 0 or not session.track(target, duration=next_track, announce=False):
                            break
                        total_track_time += next_track
                    if opts.max_duration is not None and (time.time() - start_time >= opts.max_duration):
                        user_logger.warning("Maximum duration of %g seconds has elapsed - stopping script" %
                                            (opts.max_duration,))
                        keep_going = False
                        break
                    targets_observed.append(target.name)
                if keep_going and len(targets_observed) == targets_before_loop:
                    user_logger.warning("No targets are currently visible - stopping script instead of hanging around")
                    keep_going = False
            user_logger.info("Targets observed : %d (%d unique)" % (len(targets_observed), len(set(targets_observed))))


# Complete the findDigits function below.
def findDigits(n):
    str_num = str(n)
    sum = 0
    for i in range(len(str_num)):
        if int(str_num[i]) != 0:
            if n % int(str_num[i]) == 0:
                sum = sum + 1

    print(sum)

findDigits(12)


import string
from vll.util import make_generator

O_PAREN = "("
C_PAREN = ")"
FUNC_DEF = "$"
FUNC_CALL = "@"

WHITESPACE = [" ", "\n", "\t"]
NUMBER = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
QUOTE = ['"', "'"]
OPS = ["+", "=", "-"]
ALPHANUMERIC = [char for char in string.ascii_lowercase] + [char for char in string.ascii_uppercase] + NUMBER

def tokenize(string):
    return list(_tokenize(make_generator(string)))

def _tokenize(generator):
    for character in generator:
        if character == O_PAREN or character == C_PAREN or character in OPS:
            yield character
        elif character in NUMBER:
            numbers, remaining = _tokenize_number(generator)
            yield "".join([character] + numbers)

            if remaining and remaining not in WHITESPACE:
                yield remaining
        elif character in QUOTE:
            string = _tokenize_string(generator, sentinel=character)
            yield "".join(string)
        elif character in WHITESPACE:
            pass
        elif character == FUNC_DEF or character == FUNC_CALL:
            characters, remaining = _tokenize_funcname(generator)
            yield "".join([character] + characters)

            if remaining and remaining not in WHITESPACE:
                yield remaining
        else:
            raise Exception("Symbol {} is unrecognized".format(character))

def _tokenize_number(generator):
    tokens = []

    for character in generator:
        if character not in NUMBER:
            return tokens, character
        tokens.append(character)
    raise Exception("End of number never found")

def _tokenize_string(generator, sentinel):
    tokens = []

    for character in generator:
        if character == sentinel:
            return tokens
        tokens.append(character)
    raise Exception("No matching quote found for {}".format(sentinel))

def _tokenize_funcname(generator):
    tokens = []
    for character in generator:
        if character not in ALPHANUMERIC:
            return tokens, character
        tokens.append(character)
    raise Exception("Function names must end with a whitespace character")


from flask import session, redirect, url_for, render_template, request
from . import main

# for analysis
from flask_socketio import emit

# for scientific_names, validate_locations
import json

# for validate_locations
import subprocess

import os
import ast
import re
import random, string

from .utils.parse import krakenReadCount
from .utils.notification import send_email, send_sms

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

@main.route('/is_database_downloaded', methods=['GET'])
def is_database_downloaded():
    if (request.method == 'GET'):
        app_location = request.args.get('app_location')
        app_location = app_location if app_location.endswith('/') else app_location + '/'

        if subprocess.call(['ls',app_location + '.download_in_progress']) == 0:
            return json.dumps({ 'status': 200 })
        else:
            return json.dumps({ 'status': 404 })
    else:
        return json.dumps({ 'status': 400 })

@main.route('/get_timeline_info',methods=["GET"])
def get_timeline_info():
    if request.method == 'GET':
        app_location = request.args.get('app_location')
        app_location = app_location if app_location.endswith('/') else app_location + '/'

        if subprocess.call(['ls',app_location + 'analysis.timeline']) == 0:
            with open(app_location + 'analysis.timeline','r') as analysis_timeline:
                try:
                    line = analysis_timeline.readline()
                    (num_total_reads,num_classified_reads) = line.split("\t")

                    return json.dumps( \
                        { \
                            'status': 200, \
                            'num_total_reads': int(num_total_reads), \
                            'num_classified_reads': int(num_classified_reads) \
                        })

                except:
                    return json.dumps({ 'status': 404 })

@main.route('/get_sankey_data', methods=['GET'])
def get_sankey_data():
    if request.method == 'GET':
        app_location = request.args.get('app_location')
        app_location = app_location if app_location.endswith('/') else app_location + '/'

        if subprocess.call(['ls',app_location + 'centrifuge/sankey.data']) == 0:
            with open(app_location + 'centrifuge/sankey.data','r') as sankey_file:
                lines = sankey_file.read()
                if "None" in lines:
                    return json.dumps({ 'status': 204 })
                else:
                    try:
                        jsonRecord = ast.literal_eval(lines)
                        return json.dumps({ 'status': 200, 'nodes': jsonRecord[0], 'links': jsonRecord[1] })
                    except:
                        print("TAYAB! TAKE A LOOK!")
                        print(lines)
                        return json.dumps({ 'status': 404 })
        else:
            return json.dumps({ 'status': 404 })
    else:
        return json.dumps({ 'status': 400 })

@main.route('/get_alert_info', methods=['GET'])
def get_alert_info():
    if (request.method == 'GET'):
        app_location = request.args.get('app_location')
        app_location = app_location if app_location.endswith('/') else app_location + '/'

        if subprocess.call(['ls',app_location + 'alertinfo.cfg']) == 0:
            alert_sequences_list = ""
            already_alerted_list = ""
            alert_sequences_threshold = 100
            email_address = None
            phone_number = None
            with open(app_location + 'alertinfo.cfg','r') as config_file:
                for line in config_file:
                    if "alert_sequences" in line:
                        alert_sequences_list = line
                    if "alert_sequence_threshold" in line:
                        alert_sequences_threshold = int(line.split("=")[1].strip())
                    if "email_address" in line:
                        email_address = line.split("=")[1].strip()
                    if "phone_number" in line:
                        phone_number = line.split("=")[1].strip()
                    if "already_alerted" in line:
                        already_alerted_list = line

            finalList = []
            otherFinalList = []

            alert_sequences_list = alert_sequences_list.split("=")[1].strip()
            alert_sequences_list = ast.literal_eval(alert_sequences_list)

            already_alerted_list = already_alerted_list.split("=")[1].strip()
            already_alerted_list = ast.literal_eval(already_alerted_list)

            for alert in alert_sequences_list:
                krakenResult = krakenReadCount(app_location + 'centrifuge/final.out.kraken',int(alert))
                if(krakenResult == None):

                    # with open(os.path.abspath('./app/main/data/scientific_names.json'),'r') as f:
                    #     for line in f:
                    #         if alert in line:
                    #             name = re.search(r'\"label\":\W(\"[^"]{1,}\")', line).group(1)
                    #             int_dict = {"tax_id": int(alert), "name": alert, "num_reads": 0 }
                    #             otherFinalList.append(int_dict)
                    #             break
                    int_dict = {"tax_id": int(alert), "name": alert, "num_reads": 0 }
                    otherFinalList.append(int_dict)
                else:
                    # taxid, num_reads, name
                    int_dict = {"tax_id": int(alert), "name": krakenResult[2].rstrip(), "num_reads": krakenResult[1] }
                    finalList.append(int_dict)

                    # Send an email if the # of reads are greater than the alert_sequence_threshold
                    if int(krakenResult[1]) >= alert_sequences_threshold and (alert not in already_alerted_list):
                        if email_address is not None:
                            send_email(krakenResult[2].strip(), krakenResult[1],email_address)
                        if phone_number is not None:
                            send_sms(krakenResult[2].strip(), krakenResult[1],phone_number)

                        # Update alertconfig file for already_alerted sequences.
                        other_info = ""
                        list_of_sequences = ""
                        line_number = -1
                        with open(app_location + 'alertinfo.cfg','r') as read_file:
                            for idx,line in enumerate(read_file):
                                if "already_alerted" not in line:
                                    other_info += line
                                else:
                                    list_of_sequences = line.split("=")[1]

                        list_of_sequences = ast.literal_eval(list_of_sequences.strip())
                        list_of_sequences.append(str(alert))
                        new_list_of_sequences = "already_alerted = " + str(list_of_sequences)
                        with open(app_location + 'alertinfo.cfg','w') as write_file:
                            write_file.write(other_info)
                            write_file.write(new_list_of_sequences)

            if(len(finalList) > 0):
                return json.dumps({ 'status': 200, 'alerts': finalList, 'alert_sequences_threshold': alert_sequences_threshold })
            elif(len(otherFinalList) > 0):
                return json.dumps({ 'status': 200, 'alerts': otherFinalList, 'alert_sequences_threshold': alert_sequences_threshold  })
        else:
            return json.dumps({ 'status': 404 })
    else:
        return json.dumps({ 'status': 400 })

def get_uid():
    # generate a random unique id
    uid  = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(5))

    # check to see if this id already exists
    micas_cache_file = os.getenv('HOME') + "/.micas"
    cache_dict = {"ids": [], "micas_paths": [], "minion_paths": []}
    with open(micas_cache_file) as cache_fs:
        for line in cache_fs:
            rec = line.split("\t")
            cache_dict["ids"].append(rec[0])
            cache_dict["micas_paths"].append(rec[1])
            cache_dict["minion_paths"].append(rec[2])

    # keep generating the uid until its unique
    while uid in cache_dict["ids"]:
        uid  = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(5))

    return uid

@main.route('/get_analysis_info', methods=['GET'])
def get_analysis_info():
    if( request.method == 'GET'):
        uid = request.args.get('uid')

        # get minion and micas location
        micas_path = ""
        minion_path = ""
        micas_cache_file = os.getenv("HOME") + '/.micas'
        with open(micas_cache_file, 'r') as cache_fs:
            found = False
            for line in cache_fs:
                entry = line.split("\t")
                entry_id = entry[0]
                entry_micas_path = entry[1]
                entry_minion_path = entry[2]
                if uid == entry_id:
                    micas_path = entry_micas_path
                    minion_path = entry_minion_path
                    found = True
                    break

        if found == False:
            return json.dumps({ 'status': 404, 'message': "Couldn't find the analysis data with UID: " + uid })
        else:

            print(get_alert_info("sup"))

            return json.dumps({
                'status': 200,
                'data': {
                    "minion_path": minion_path,
                    "micas_path": micas_path,
                }
            })

    else:
        return "Unexpected request method. Expected a GET request."

@main.route('/analysis',methods=['GET'])
def analysis():

    if (request.method == 'GET'):

        app_location = request.args.get('app_location')
        minion = request.args.get('minion')

        session['app_location'] = app_location
        session['minion'] = minion

        error = []

        # Location for the applicaiton data directory
        app_location = app_location if app_location.endswith('/') else app_location + '/'

        # check if app_location is valid
        if subprocess.call(['ls',app_location]) == 0:
            # if app_location exists
            if subprocess.call(['ls',app_location + 'alertinfo.cfg']) == 0:
                # if minion location exists
                if subprocess.call(['ls',minion]) == 0:
                    # locations are valid

                    # is another user already on that page? If so, bounce this user
                    if subprocess.call(['ls',app_location + 'analysis_busy']) == 0 and False:
                        error.append({'message': 'This route is busy. Please try again!'})
                    else:

                        analysis_started_date = None
                        if subprocess.call(['ls', app_location + 'analysis_started']) == 0:
                            with open(app_location + 'analysis_started','r') as f:
                                analysis_started_date = f.readline()
                        else:
                            import datetime, time
                            d = datetime.datetime.utcnow()
                            for_js = int(time.mktime(d.timetuple())) * 1000
                            analysis_started_date = for_js
                            print("D: " + str(d))
                            print("FOR_JS: " + str(for_js))
                            with open(app_location + 'analysis_started','w') as f:
                                f.write(str(analysis_started_date))

                        subprocess.call(['touch',app_location + 'analysis_busy'])
                        return render_template('analysis.html',app_loc=app_location,minion_loc=minion,start_time=analysis_started_date)
                else:
                    error.append({'message': 'MinION location is not valid.'})
            else:
                error.append({'message': 'Alert configuration file is not found.'})
        else:
            error.append({'message': 'App location was not found'})
    return json.dumps(error)

@main.route('/validate_locations', methods=['POST','GET'])
def validate_locations():
    if( request.method == 'POST'):
        print("INSIDE VALIDATE_LOCATIONS")
        minION_location = request.form['minION']
        app_location = request.form['App']
        queries = request.form['Queries']

        _queries = queries.split(';')[:-1]

        if(len(_queries) > 0):
            query_output = -1
            for query in _queries:
                query_output = subprocess.call(['ls',query])
        else:
            query_output = 0

        minION_output = subprocess.call(['ls', minION_location])
        app_output = subprocess.call(['ls', app_location])

        centrifuge_output = -1
        centrifuge_output = subprocess.call(['which', 'centrifuge']) + \
                            subprocess.call(['which', 'centrifuge-download']) + \
                            subprocess.call(['which', 'centrifuge-kreport']) + \
                            subprocess.call(['which', 'centrifuge-build'])

        print("minION_output = " + str(minION_output))
        print("app_output = " + str(app_output))
        print("query_output = " + str(query_output))
        print("centrifuge_output = " + str(centrifuge_output))

        if(minION_output == 0 and app_output == 0 and query_output == 0 and centrifuge_output == 0):
            uid = get_uid()
            return json.dumps({ "code": 0, "message": "SUCCESS", "uid": uid })
        else:
            if minION_output == 1:
                return json.dumps([{ "code": 1, "message": "Invalid minION location"}])
            elif app_output == 1:
                return json.dumps([{ "code": 1, "message": "Invalid App location" }])
            return json.dumps([{ "code": 1, "message": "Invalid Queries location"}])
    else:
        return "N/a"


import cv2
import os

from src.utils.utils import get_all_video_paths
from src.utils.utils import get_logger

logger = get_logger("video_preprocessor")

frame_directory_name = 'frames'

def preprocess_videos(path):
    frame_dir = os.path.join(path, frame_directory_name)
    video_paths = get_all_video_paths(path)

    if os.path.exists(frame_dir):
        logger.info("Frame directory already exists, no preprocessing needed!")
        return
    else:
        os.makedirs(frame_dir)

    logger.info(f"Preprocessing {len(video_paths)} videos.")
    for path in video_paths:
        logger.info(f"Preprocessing {path}...")
        extract_video_frames(path, frame_dir)

def extract_video_frames(video_path, frame_directory):
    videoCapture = cv2.VideoCapture(video_path)
    if not videoCapture.isOpened():
        logger.info('Error opening video {}'.format(video_path))
        return

    ret, frame = videoCapture.read()
    if len(frame.shape) != 3 or frame.shape[2] != 3:
        logger.info('Wrong image {} with shape {}'.format(video_path, frame.shape))
        return

    image_format = ".jpg"
    directory_name, file_name = os.path.split(video_path)
    video_name = os.path.splitext(file_name)[0]
    if frame_directory is None:
        frame_directory = os.path.join(directory_name, frame_directory_name)

    if not os.path.exists(frame_directory):
        os.makedirs(frame_directory)
    frame_index = 0
    while ret:
        frame_file_name = os.path.join(frame_directory, video_name + "_" + str(frame_index).zfill(6) + image_format)
        cv2.imwrite(frame_file_name, frame)
        ret, frame = videoCapture.read()
        frame_index += 1

    logger.info(f"Extracted {frame_index} frames.")
    videoCapture.release()


#!/bin/env python
import unittest
from unittest.mock import Mock
from pyats.topology import Device

from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
                                       SchemaMissingKeyError
from genie.libs.parser.iosxe.show_run import ShowRunPolicyMap, ShowRunInterface

class TestShowRunPolicyMap(unittest.TestCase):
    device = Device(name='aDevice')
    empty_output = {'execute.return_value': ''}

    golden_parsed_output = {
        "policy_map": {
            "L3VPN-0_in": {
                "class": {
                    "HEY_in": {
                        "police": {
                            "cir_bps": "365",
                            "pir_bps": "235",
                            "conformed": "transmit",
                            "exceeded": "drop"
                        }
                    },
                    "OSPF": {
                        "police": {
                            "cir_bps": "543",
                            "pir_bps": "876",
                            "conformed": "transmit",
                            "exceeded": "drop"
                        }
                    },
                    "class-default": {
                        "police": {
                            "cir_bps": "2565",
                            "cir_bc_bytes": "4234",
                            "conformed": "transmit",
                            "exceeded": "drop"
                        },
                        "service_policy": "child"
                    }
                }
            }
        }
    }

    golden_output = {'execute.return_value': '''\
        show run policy-map L3VPN-0_in
        Building configuration...

        Current configuration : 56 bytes
        !
        policy-map L3VPN-0_in
        class HEY_in
        police cir 365 pir 235 conform-action transmit  exceed-action drop
        class OSPF
        police cir 543 pir 876 conform-action transmit  exceed-action drop
        class class-default
        police cir 2565 bc 4234 conform-action transmit  exceed-action drop
        service-policy child
        !
        end
    '''}

    def test_empty(self):
        self.device1 = Mock(**self.empty_output)
        obj = ShowRunPolicyMap(device=self.device1)
        with self.assertRaises(SchemaEmptyParserError):
            parsed_output = obj.parse(name= 'L3VPN-0_in')

    def test_golden(self):
        self.device1 = Mock(**self.golden_output)
        obj = ShowRunPolicyMap(device=self.device1)
        parsed_output = obj.parse(name= 'L3VPN-0_in')
        self.assertEqual(parsed_output,self.golden_parsed_output)

class TestShowRunInterface(unittest.TestCase):

    maxDiff = None
    device = Device(name='aDevice')
    empty_output = {'execute.return_value': ''}

    golden_parsed_output = {
        'interfaces': {
            'GigabitEthernet1/0/13': {
                'authentication_control_direction': 'in',
                'authentication_event_fail_action': 'next-method',
                'authentication_fallback': 'dot1x',
                'authentication_host_mode': 'multi-auth',
                'authentication_order': 'dot1x mab',
                'authentication_periodic': True,
                'authentication_port_control': 'auto',
                'authentication_priority': 'dot1x mab',
                'authentication_timer_inactivity': '65535',
                'authentication_timer_reauthenticate_server': True,
                'authentication_violation': 'restrict',
                'description': 'ISE Controlled Port',
                'dot1x_pae_authenticator': True,
                'dot1x_timeout_quiet_period': '5',
                'dot1x_timeout_server_timeout': '10',
                'dot1x_timeout_tx_period': '5',
                'ip_arp_inspection_limit_rate': '1024',
                'ip_dhcp_snooping_limit_rate': '100',
                'load_interval': '30',
                'mab': True,
                'snmp_trap_link_status': False,
                'snmp_trap_mac_notification_change_added': True,
                'snmp_trap_mac_notification_change_removed': True,
                'spanning_tree_bpduguard': 'enable',
                'spanning_tree_portfast': True,
                'switchport_access_vlan': '70',
                'switchport_mode': 'access',
                'switchport_nonegotiate': 'nonegotiate',
            },
        },
    }
    golden_output = {'execute.return_value': '''\
        #show running-config interface Gi1/0/13

        Building configuration...

        Current configuration : 914 bytes

        !

        interface GigabitEthernet1/0/13
         description ISE Controlled Port
         switchport access vlan 70
         switchport mode access
         switchport nonegotiate
         ip arp inspection limit rate 1024
         load-interval 30
         authentication control-direction in
         authentication event fail action next-method
         authentication host-mode multi-auth
         authentication order dot1x mab
         authentication priority dot1x mab
         authentication port-control auto
         authentication periodic
         authentication timer reauthenticate server
         authentication timer inactivity 65535
         authentication violation restrict
         authentication fallback dot1x
         mab
         snmp trap mac-notification change added
         snmp trap mac-notification change removed
         no snmp trap link-status
         dot1x pae authenticator
         dot1x timeout quiet-period 5
         dot1x timeout server-timeout 10
         dot1x timeout tx-period 5
         spanning-tree portfast
         spanning-tree bpduguard enable
         ip dhcp snooping limit rate 100
        end
    '''}

    golden_parsed_output1 = {
        'interfaces': {
            'GigabitEthernet0': {
                'description': '"Boot lan interface"',
                'ipv4': {
                    'ip': '10.1.21.249',
                    'netmask': '255.255.255.0',
                },
                'negotiation_auto': True,
                'vrf': 'Mgmt-intf',
            },
        },
    }
    golden_output1 = {'execute.return_value': '''\
        #show running-config interface GigabitEthernet0
        Building configuration...

        Current configuration : 150 bytes
        !
        interface GigabitEthernet0
         description "Boot lan interface"
         vrf forwarding Mgmt-intf
         ip address 10.1.21.249 255.255.255.0
         negotiation auto
        end
    '''}

    golden_parsed_output2 = {
        'interfaces': {
            'Port-channel1.100': {
                'encapsulation_dot1q': '201',
                'ipv4': {
                    'ip': '202.0.0.1',
                    'netmask': '255.255.255.0',
                },
                'ipv6': ['2002::1/112'],
                'ipv6_ospf': {
                    '1': {
                        'area': '0',
                    },
                },
            },
        },
    }
    golden_output2 = {'execute.return_value': '''\
        interface Port-channel1.100
         encapsulation dot1Q 201
         ip address 202.0.0.1 255.255.255.0
         ipv6 address 2002::1/112
         ipv6 ospf 1 area 0
        end
    '''}

    golden_parsed_output3 = {
        'interfaces': {
            'GigabitEthernet0/0/3': {
                'ip_ospf': {
                    '2': {
                        'area': '0',
                    },
                },
                'ipv4': {
                    'ip': '99.99.110.1',
                    'netmask': '255.255.255.0',
                },
                'ipv6': ['2003::1/112'],
                'ipv6_ospf': {
                    '1': {
                        'area': '0',
                    },
                },
                'negotiation_auto': True,
            },
        },
    }
    golden_output3 = {'execute.return_value': '''\
        interface GigabitEthernet0/0/3
         ip address 99.99.110.1 255.255.255.0
         ip ospf 2 area 0
         negotiation auto
         ipv6 address 2003::1/112
         ipv6 ospf 1 area 0
        end
    '''}

    golden_parsed_output4 = {
        'interfaces': {
            'GigabitEthernet0/0/0.101': {
                'encapsulation_dot1q': '101',
                'ipv4': {
                    'ip': '201.0.0.1',
                    'netmask': '255.255.255.0',
                },
                'ipv6': ['2001::1/112'],
                'ipv6_enable': True,
                'ipv6_ospfv3': {
                    '1': {
                        'area': '0',
                    },
                },
                'vrf': 'VRF1',
            },
        },
    }
    golden_output4 = {'execute.return_value': '''\
        interface GigabitEthernet0/0/0.101
         encapsulation dot1Q 101
         vrf forwarding VRF1
         ip address 201.0.0.1 255.255.255.0
         ipv6 address 2001::1/112
         ipv6 enable
         ospfv3 1 ipv6 area 0
        end
    '''}

    golden_parsed_output5 = {
        'interfaces': {
            'Loopback1': {
                'ipv4': {
                    'ip': '200.1.0.2',
                    'netmask': '255.255.255.0',
                },
                'ipv6': ['1:1:1::1/64', '2000:1::2/112'],
                'vrf': 'VRF1',
            },
        },
    }
    golden_output5 = {'execute.return_value': '''\
        interface Loopback1
         vrf forwarding VRF1
         ip address 200.1.0.2 255.255.255.0
         ipv6 address 1:1:1::1/64
         ipv6 address 2000:1::2/112
        end
    '''}

    golden_parsed_output6 = {
        'interfaces': {
            'GigabitEthernet0/0/0': {
                'carrier_delay': ['up 60', 'down 60'],
                'ipv6': ['1::1/112'],
                'negotiation_auto': True,
            },
        },
    }
    golden_output6 = {'execute.return_value': '''\
        interface GigabitEthernet0/0/0
         no ip address
         carrier-delay up 60
         carrier-delay down 60
         negotiation auto
         ipv6 address 1::1/112
        end
    '''}

    def test_empty(self):
        self.device1 = Mock(**self.empty_output)
        obj = ShowRunInterface(device=self.device1)
        with self.assertRaises(SchemaEmptyParserError):
            parsed_output = obj.parse(interface='GigabitEthernet0/0/0')

    def test_golden(self):
        self.device1 = Mock(**self.golden_output)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='Gi1/0/13')
        self.assertEqual(parsed_output,self.golden_parsed_output)

    def test_golden1(self):
        self.device1 = Mock(**self.golden_output1)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='GigabitEthernet0')
        self.assertEqual(parsed_output,self.golden_parsed_output1)

    def test_golden2(self):
        self.device1 = Mock(**self.golden_output2)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='Port-channel1.100')
        self.assertEqual(parsed_output,self.golden_parsed_output2)

    def test_golden3(self):
        self.device1 = Mock(**self.golden_output3)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='GigabitEthernet0/0/3')
        self.assertEqual(parsed_output,self.golden_parsed_output3)

    def test_golden4(self):
        self.device1 = Mock(**self.golden_output4)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='GigabitEthernet0/0/0.101')
        self.assertEqual(parsed_output,self.golden_parsed_output4)

    def test_golden5(self):
        self.device1 = Mock(**self.golden_output5)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='Loopback1')
        self.assertEqual(parsed_output,self.golden_parsed_output5)

    def test_golden6(self):
        self.device1 = Mock(**self.golden_output6)
        obj = ShowRunInterface(device=self.device1)
        parsed_output = obj.parse(interface='GigabitEthernet0/0/0')
        self.assertEqual(parsed_output,self.golden_parsed_output6)

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


# coding: utf-8
def leon(n):
    fib1 = 1
    fib2 = 1
    i = 0
    while i < n - 2:
        fib_sum = fib1 + fib2
        fib1 = fib2
        fib2 = fib_sum
        i = i + 1
    return fib2
    a = fib(n)
    leo = 2 * a - 1
    return leo

def main():
    n = 1
    while n != 'exit':
        print("Введите число:  (P.S.напишите 'exit' для завершения программы): ")
        n = input()
        if n == 'exit':
            break
        elif not n.isnumeric():
            print("Некорректный ввод. Введите число:")
        else:
            print(leon(int(n)))

if __name__ == "__main__":
    main()


""" define the top class for all analyzers  """
from __future__ import absolute_import, unicode_literals
import datetime
from .analyzer import Analyzer
from .utils import calculate_hash_sum, is_number
from analyzer.models import ActualColumnProfile

class AnalyzerActualColumn(Analyzer):
    def __init__(self, recordset, dataset_profile, data_types, column, row_count, index):
        super().__init__()
        self.recordset = recordset
        self.dataset_profile = dataset_profile
        self.data_types = data_types
        self.column = column
        self.row_count = row_count
        self.index = index

    def find_data_type(self):
        for data in self.data_types:
            if data[0] == self.column:
                return data[1]
        return None

    def _execute_session(self):
        profile = {}
        min_value = self.recordset.get_column_min(self.column)
        if is_number(min_value) or isinstance(min_value, datetime.datetime):
            profile['min'] = min_value
        else:
            profile['min'] = None

        max_value = self.recordset.get_column_max(self.column)

        if is_number(max_value) or isinstance(max_value, datetime.datetime):
            profile['max'] = max_value
        else:
            profile['max'] = None

        profile['uniqueness'] = len(self.recordset.get_column_distinct(self.column)) / self.row_count
        profile['datatype'] = self.find_data_type()
        profile['nullable'] = True
        profile['order'] = self.index

        profile['hash_sum'] = calculate_hash_sum(profile)

        ActualColumnProfile.objects.create(dataset_profile=self.dataset_profile,
                                           name=self.column,
                                           min=profile['min'],
                                           max=profile['max'],
                                           uniqueness=profile['uniqueness'],
                                           datatype=profile['datatype'],
                                           nullable=profile['nullable'],
                                           order=profile['order'],
                                           hash_sum=profile['hash_sum'])

        return profile


import random
import math

#Added """Settings""" to the top,so that its easier to swap between """methods"""

#Murder one boss per week, instead of all 3 a week. Saves 120 resin worth of time, if you're only trying to max one character
#Murder all three bosses per week, instead of 1. Yes I know the max resin is 160, but the time waited doesnt differ.

#Options are 1 and 3 respectfully
Boss_Method = 3

#Standard Outcrops - Ley Line Outcrops
#Rhodias Rage - Limited Event starting April 9th 2021, but lets pretend its inifnitely

#Options are "EXP" and "RhoRage" respectfully
EXP_Method = "EXP"

CharactersList = {
    #"Name": (Element, "Weekly Boss Talent Ascention Material (based on Fandom)", "Domain Talent Ascention Material (Also fandom)", "Weapon Name (Based on Game8 reccomended Weapon, or if a 4-star is reccomended, a random 5-star bow is chosen instead, since im too lazy to account for 4-stars. (+ indicates first reccomendation, - indicates other reccomendation, no sign indicates random selection)", "Weapon Ascention Material (Based on Game8")
    "Venti": ("Anemo", "Tail", "Ballad", "Skyward Harp", "Wolf"), #-
    "Sucrose": ("Anemo", "Locket", "Freedom", "Skyward Atlas", "Wolf"), #-
    "Jean": ("Anemo", "Plume", "Resistance", "Aquila Favonia", "Decarabian"), #+
    "TravelerA": ("Anemo", "Sigh", "ThreeMondstat", "Skyward Blade", "Wolf"), #+
    "Xiao": ("Anemo", "Shadow", "Prosperity", "Primordial Jade Winged-Spear", "Guyun"), #+

    "Qiqi": ("Cryo", "Tail", "Prosperity", "Skyward Blade", "Wolf"), #+
    "Kaeya": ("Cryo", "Locket", "Ballad", "Aquila Favonia", "Decarabian"), #+
    "Chongyun": ("Cryo", "Sigh", "Dilligence", "Skyward Pride", "Wolf"), #+
    "Diona": ("Cryo", "Legacy", "Freedom", "Amos' Bow", "Dandelion"),
    "Ganyu": ("Cryo", "Shadow", "Dilligence", "Amos' Bow", "Dandelion"), #+
    "Rosaria": ("Cryo", "Shadow", "Ballad", "Primordial Jade Winged-Spear", "Guyun"), #+

    "Keqing": ("Electro", "Ring", "Prosperity", "Aquila Favonia", "Decarabian"), #+
    "Fishcl": ("Electro", "Locket", "Ballad", "Skyward Harp", "Wolf"), #+
    "Lisa": ("Electro", "Claw", "Ballad", "Lost Prayer to the Sacred Winds", "Dandelion"),
    "Razor": ("Electro", "Claw", "Resistance", "Wolf's Gravestone", "Dandelion"), #+
    "Beidou": ("Electro", "Sigh", "Gold", "Wolf's Gravestone", "Dandelion"), #+

    "TravelerG": ("Geo", "Tail+Sigh", "Everything", "Gods dont need weapons", "None"),
    "Ninguang": ("Geo", "Locket", "Prosperity", "Memory of Dust", "Aero_Chocolate"), #+
    "Noelle": ("Geo", "Claw", "Resistance", "The Unforged", "Elixer"), #-
    "Albedo": ("Geo", "Tusk", "Ballad", "Skyward Blade", "Wolf"), #-
    "Zhongli": ("Geo", "Tusk", "Gold", "Vortex Vanquisher", "Aero_Chocolate"), #+

    "Xingqui": ("Hydro", "Tail", "Gold", "Skyward Blade", "Wolf"), #+
    "Mona": ("Hydro", "Ring", "Resistance", "Skyward Atlas", "Wolf"), #-
    "Barbara": ("Hydro", "Ring", "Freedom", "Skyward Atlas", "Wolf"), #-
    "Tartagalia": ("Hydro", "Legacy", "Freedom", "Skyward Harp", "Wolf"), #+

    "Klee": ("Pyro", "Ring", "Freedom", "Lost Prayer to the Sacred Winds", "Dandelion"), #+
    "Diluc": ("Pyro", "Plume", "Resistance", "Wolf's Gravestone", "Dandelion"), #+
    "Bennett": ("Pyro", "Plume", "Resistance", "Skyward Blade", "Wolf"), #+
    "Xiangling": ("Pyro", "Claw", "Dilligence", "Skyward Spine", "Dandelion"), #+
    "Amber": ("Pyro", "Sigh", "Freedom", "Amos' Bow", "Dandelion"), #+
    "Xinyan": ("Pyro", "Tusk", "Gold", "The Unforged", "Elixer"), #+
    "Hu Tao": ("Pyro", "Legacy", "Dilligence", "Staff of Homa", "Aero_Chocolate") #+
}

Character_Count = len(CharactersList) * 5#For some reason, making a copy of the dictionary itself wasnt working, because the key got deleted from both Dictionaries at the smae time, which is weird because I never told it to edit a dictionary called "CharactersList2". So, I scrapped a second dictionary, and just did the calculations at the beginning.

Dvalin_Loot = ["Plume", "Claw", "Sigh"]
Wolf_Loot = ["Tail", "Ring", "Locket"]
Childe_Loot = ["Tusk", "Legacy", "Shadow"]

#I know there's a way to set multiple variables at once, but im just so used to this anything else looks weird
Weeks_Waited = 0

Dvalin_Body_Count = 0
Wolf_Body_Count = 0
Childe_Body_Count = 0

Plume = 0
Claw = 0
Sigh = 0
Tail = 0
Ring = 0
Locket = 0
Tusk = 0
Legacy = 0
Shadow = 0

def Boss_Check(WiiSports2):
    global Tail
    global Sigh
    if WiiSports == "Tail+Sigh":
        if Tail >= 12 and Sigh >= 6:
            Tail -= 12
            Sigh -= 6
            return True
    else:
        if eval(WiiSports2) >= 18:#If Geo Traveler didnt require both Tails and Sighs, I could have just done this all at once, without needed the function
            globals()[WiiSports2] = eval(WiiSports2) - 18
            return True

def Boss_Loot(WiiSports2):
    global Dvalin_Body_Count
    global Wolf_Body_Count
    global Childe_Body_Count
    global Tail
    global Sigh

    if WiiSports2 in Dvalin_Loot:
        for x in random.sample(Dvalin_Loot, 2):
            globals()[x] = eval(x) + 1
        Dvalin_Body_Count += 1

    if WiiSports2 in Wolf_Loot:
        for x in random.sample(Wolf_Loot, 2):
            globals()[x] = eval(x) + 1
        Wolf_Body_Count += 1

    if WiiSports2 in Childe_Loot:
        for x in random.sample(Childe_Loot, 2):
            globals()[x] = eval(x) + 1
        Childe_Body_Count += 1

    if WiiSports2 == "Tail+Sigh":
        if Tail < 12:
            for x in random.sample(Wolf_Loot, 2):
                globals()[x] = eval(x) + 1
            Wolf_Body_Count += 1
        else:
            for x in random.sample(Dvalin_Loot, 2):
                globals()[x] = eval(x) + 1
            Dvalin_Body_Count += 1

    if WiiSports2 == "ALL":
        for x in random.sample(Dvalin_Loot, 2):
            globals()[x] = eval(x) + 1
        Dvalin_Body_Count += 1
        for x in random.sample(Wolf_Loot, 2):
            globals()[x] = eval(x) + 1
        Wolf_Body_Count += 1
        for x in random.sample(Childe_Loot, 2):
            globals()[x] = eval(x) + 1
        Childe_Body_Count += 1

Minutes_Spent = 0
Total_Resin = 160
Mora_Cost = 0
Resin_Count = 160

EXP_Blossom_Count = 0
Rhodia_Count = 0
Mora_Blossom_Count = 0
Mondstat_Domain_Count = 0
Liyue_Domain_Count = 0
Any_Artifact_Domain_Count = 0
Mondstat_Domain_Count2 = 0#Might aswell count which province domain im doing for weapon Ascention materials
Liyue_Domain_Count2 = 0

Wits = 0
Experience = 0
Advice = 0
Three_Star_Artifacts = 0
Four_Star_Artifacts = 0
Mystic_Enchancement = 0
Magic_Crystal_Needed = 0
Spares = False

PrimoShards = 0

for x in range(len(CharactersList)):#Do for every character in the Dictionary
    Character_EXP = 0
    Name = random.choice(list(CharactersList.keys()))
    Character = CharactersList.pop(Name)#Get which character they are
    Element = Character[0] #what element they are
    WiiSports = Character[1] #and their required Materials, shortened to mat, lenghtned to Matt, lenghtned to WiiSports
    Teachings = Character[2]
    WeaponName = Character[3]
    Ascentions = Character[4]

    ElementFragment = Element + "Fragment"
    ElementShard = Element + "Shard"
    ElementChunk = Element + "Chunk"
    ElementGem = Element + "Gem"
    ElementBossSpecific = Element + "Boss"
    ElementBossBodyCount = Element + "BodyCount"
    TeachingsCommon = Teachings + "Common"
    TeachingsRare = Teachings + "Rare"
    TeachingsEpic = Teachings + "Epic"
    if Teachings in ["Freedom", "Resistance", "Ballad"]:#Counting each domain
        Talent_Domain = "Mondstat_Domain_Count"
    else:
        Talent_Domain = "Liyue_Domain_Count"
    AscentionsUncommon = Ascentions + "Uncommon"
    AscentionsRare = Ascentions + "Rare"
    AscentionsEpic = Ascentions + "Epic"
    AscentionsLeggy = Ascentions + "Leggy"
    if Ascentions in ["Decarabian", "Wolf", "Dandelion"]:#Counting each domain
        Weapon_Domain = "Mondstat_Domain_Count2"
    else:
        Weapon_Domain = "Liyue_Domain_Count2"

    if ElementFragment not in globals():#Im too lazy to write out each variable, so I'll force python to do it for me
        globals()[ElementFragment] = 0
        globals()[ElementShard] = 0
        globals()[ElementChunk] = 0
        globals()[ElementGem] = 0
        globals()[ElementBossSpecific] = 0
        globals()[ElementBossBodyCount] = 0
    if TeachingsCommon not in globals():
        globals()[TeachingsCommon] = 0
        globals()[TeachingsRare] = 0
        globals()[TeachingsEpic] = 0
    if AscentionsUncommon not in globals():
        globals()[AscentionsUncommon] = 0
        globals()[AscentionsRare] = 0
        globals()[AscentionsEpic] = 0
        globals()[AscentionsLeggy] = 0

    if Name != "TravelerG": #Subtract Traveler 2's EXP cost, since a lvl 90 Anemo is also a lvl 90 Geo. oh and their weapon too. None of that allowed
        while Character_EXP < 8363300: #Level character to 90 based on Ley Lines
            Minutes_Spent += 8
            Resin_Count += 1
            Total_Resin += 1

            if EXP_Method == "EXP":
                if Resin_Count >= 20:
                    EXP_Blossom_Count += 1
                    Wits += random.randint(4, 5)
                    Experience += random.randint(6, 7)
                    Resin_Count -= 20

            if EXP_Method == "RhoRage":
                if Resin_Count >= 40:
                    Rhodia_Count += 1
                    Wits += 10
                    Experience += random.randint(16, 18)
                    Advice += random.randint(19, 21)

            if Advice > 0:
                Advice - 1
                Character_EXP += 1000
                Mora_Cost += 200

            if Experience > 0:
                Experience -= 1
                Character_EXP += 5000
                Mora_Cost += 1000

            if Wits > 0:#Instead of adding EXP directly, this allows EXP to carry over to other Characters
                Wits -= 1
                Character_EXP += 20000
                Mora_Cost += 4000

        Weapon_EXP = 0#Its weapon time
        while Weapon_EXP < 9064450:#Might aswell save 1 line and do this under the same "If" statement
            Minutes_Spent += 8#I would have normally put weapons at the very end but thats ok
            Resin_Count += 1
            Total_Resin += 1
            if Resin_Count >= 10:
                Magic_Crystal_Needed += 3
                Resin_Count -= 10
                Mystic_Enchancement += 6
                Mora_Cost += 100

            if Spares:
                Weapon_EXP += Spare_EXP
                Mora_Cost += Spare_EXP/5
                Spare_EXP = 0
                Spares = False

            if Mystic_Enchancement > 0:
                Mystic_Enchancement -= 1
                Weapon_EXP += 10000
                Mora_Cost += 1000
                if Weapon_EXP > 9064450:
                    Spare_EXP = Weapon_EXP - 9064450 #I could put this in one line but im too lazy
                    Spare_EXP = Spare_EXP/400
                    Spare_EXP = math.floor(Spare_EXP)
                    Spare_EXP = Spare_EXP * 400
                    Spares = True

        while True:
            Minutes_Spent += 8
            Resin_Count += 1
            Total_Resin += 1
            if Resin_Count >= 20:
                globals()[Weapon_Domain] = eval(Weapon_Domain) + 1
                globals()[AscentionsUncommon] = eval(AscentionsUncommon) + 3
                globals()[AscentionsRare] = eval(AscentionsRare) + 2
                Resin_Count -= 20
                Mora_Cost -= 1850

            #Since I did the Talent Domains, and bosses Code first, this is all techincally stolen from down below.
            if eval(AscentionsLeggy) < 6: #Check if we have enough leggy
                if eval(AscentionsEpic) >= 3: #Try and craft a leggy
                    globals()[AscentionsLeggy] = eval(AscentionsLeggy) + 1
                    globals()[AscentionsEpic] = eval(AscentionsEpic) - 3
                    Mora_Cost += 1075

            if eval(AscentionsEpic) < 14: #Check if we have enough epic
                if eval(AscentionsRare) >= 3: #Try and craft a epic
                    globals()[AscentionsEpic] = eval(AscentionsEpic) + 1
                    globals()[AscentionsRare] = eval(AscentionsRare) - 3
                    Mora_Cost += 350

            if eval(AscentionsRare) < 14: #Check if we have enough uncommon
                if eval(AscentionsUncommon) >= 3: #Try and craft a uncommon
                    globals()[AscentionsRare] = eval(AscentionsRare) + 1
                    globals()[AscentionsUncommon] = eval(AscentionsUncommon) - 3
                    Mora_Cost += 125

            if eval(AscentionsLeggy) >= 6 and eval(AscentionsEpic) >= 14 and eval(AscentionsRare) >= 14 and eval(AscentionsUncommon) >= 5:#Im going to check all at once because I dont trust myself to use my previous statements, that are also checking for quantity of chunks and shards
                globals()[AscentionsLeggy] = eval(AscentionsLeggy) - 6
                globals()[AscentionsEpic] = eval(AscentionsEpic) - 14
                globals()[AscentionsRare] = eval(AscentionsRare) - 14
                globals()[AscentionsUncommon] = eval(AscentionsUncommon) - 5
                break #exit the loop
        print(WeaponName + " Maxed...")#Just so that I know things are actually going on, and a loop isnt running inifnitely because I wrote some code wrong

    while not Boss_Check(WiiSports): #Check if we have enough weekly boss materials
        Minutes_Spent += 8
        Resin_Count += 1
        Total_Resin += 1

        if Boss_Method == 1:
            if Resin_Count >= 60:
                Boss_Loot(WiiSports)
                Weeks_Waited += 1
                Resin_Count -= 60
                Mora_Cost -= 8000 #I just googled how much they give, and then took the level that I personally could beat. also Stormterror was 7600 mora, but I dont care :)

        if Boss_Method == 3:
            if Resin_Count >= 180:
                Boss_Loot("ALL")
                Weeks_Waited += 1
                Resin_Count -= 180
                Mora_Cost -= 24000

    if Name not in ["TravelerA", "TravelerG"]: #Traveler doesnt require Anemo or Geo materials, so exclude them
        while True: #just loops untill all conditions inside are met
            Minutes_Spent += 8
            Resin_Count += 1
            Total_Resin += 1
            if Resin_Count >= 40:
                globals()[ElementBossBodyCount] = eval(ElementBossBodyCount) + 1
                globals()[ElementFragment] = eval(ElementFragment) + 3
                globals()[ElementShard] = eval(ElementShard) + 1
                globals()[ElementBossSpecific] = eval(ElementBossSpecific) + 2
                Resin_Count -= 40
                Mora_Cost -= 4725

            if eval(ElementGem) < 6: #Check if we have enough gems
                if eval(ElementChunk) >= 3: #Try and craft a gem
                    globals()[ElementGem] = eval(ElementGem) + 1
                    globals()[ElementChunk] = eval(ElementChunk) - 3
                    Mora_Cost += 2700

            if eval(ElementChunk) < 9: #Check if we have enough chunks
                if eval(ElementShard) >= 3: #Try and craft a chunk
                    globals()[ElementChunk] = eval(ElementChunk) + 1
                    globals()[ElementShard] = eval(ElementShard) - 3
                    Mora_Cost += 900

            if eval(ElementShard) < 9: #Check if we have enough shards
                if eval(ElementFragment) >= 3: #Try and craft a shard
                    globals()[ElementShard] = eval(ElementShard) + 1
                    globals()[ElementFragment] = eval(ElementFragment) - 3
                    Mora_Cost += 300

            if eval(ElementGem) >= 6 and eval(ElementChunk) >= 9 and eval(ElementShard) >= 9 and eval(ElementFragment) >= 1:#Im going to check all at once because I dont trust myself to use my previous statements, that are also checking for quantity of chunks and shards
                globals()[ElementGem] = eval(ElementGem) - 6
                globals()[ElementChunk] = eval(ElementChunk) - 9
                globals()[ElementShard] = eval(ElementShard) - 9
                globals()[ElementFragment] = eval(ElementFragment) - 1
                break #exit the loop

        while True:#Might aswell do the Teachings and what not under the same "If"
            Minutes_Spent += 8
            Resin_Count += 1
            Total_Resin += 1
            if Resin_Count >= 20:
                globals()[Talent_Domain] = eval(Talent_Domain) + 1
                globals()[TeachingsCommon] = eval(TeachingsCommon) + 3
                globals()[TeachingsRare] = eval(TeachingsRare) + 2
                Resin_Count -= 20
                Mora_Cost -= 2735

            if eval(TeachingsEpic) < 114: #Check if we have enough gems
                if eval(TeachingsRare) >= 3: #Try and craft an Epic
                    globals()[TeachingsEpic] = eval(TeachingsEpic) + 1
                    globals()[TeachingsRare] = eval(TeachingsRare) - 3
                    Mora_Cost += 550

            if eval(TeachingsRare) < 63: #Check if we have enough gems
                if eval(TeachingsCommon) >= 3: #Try and craft an Epic
                    globals()[TeachingsRare] = eval(TeachingsRare) + 1
                    globals()[TeachingsCommon] = eval(TeachingsCommon) - 3
                    Mora_Cost += 175

            if eval(TeachingsEpic) >= 114 and eval(TeachingsRare) >= 63 and eval(TeachingsCommon) >= 9:
                globals()[TeachingsEpic] = eval(TeachingsEpic) - 114
                globals()[TeachingsRare] = eval(TeachingsRare) - 63
                globals()[TeachingsCommon] = eval(TeachingsCommon) - 9
                break
    else:
        if Teachings == "ThreeMondstat":
            TeachingsList = {#Use a janky method to save code space, rather thna have to copy and paste the domain code 3 times for each teaching
                "Freedom": (9, 18, 18),
                "Resistance": (0, 33, 36),
                "Ballad": (0, 12, 60)
            }
        if Teachings == "Everything":#I am using really janky methods to save space
            TeachingsList = {
                "Freedom": (3, 6, 6),
                "Resistance": (0, 11, 12),
                "Ballad": (0, 4, 20),
                "Prosperity": (6, 12, 12),
                "Dilligence": (0, 22, 24),
                "Gold": (0, 8, 40)
            }

        for x in range(len(TeachingsList)):
            Teachings = random.choice(list(TeachingsList.keys()))
            TeachingsCommon = Teachings + "Common"#Reuse previous code lol
            TeachingsRare = Teachings + "Rare"
            TeachingsEpic = Teachings + "Epic"
            if TeachingsCommon not in globals(): #Create variables just incase they havent already been made
                globals()[TeachingsCommon] = 0
                globals()[TeachingsRare] = 0
                globals()[TeachingsEpic] = 0

            Teaching2 = TeachingsList.pop(Teachings)
            Common_Needed = Teaching2[0]
            Rare_Needed = Teaching2[1]
            Epic_Needed = Teaching2[2]

            if Teachings in ["Freedom", "Resistance", "Ballad"]:#Counting each domain
                Talent_Domain = "Mondstat_Domain_Count"
            else:
                Talent_Domain = "Liyue_Domain_Count"

            while True:#this is literally the same code from above lol
                Minutes_Spent += 8
                Resin_Count += 1
                Total_Resin += 1
                if Resin_Count >= 20:
                    globals()[Talent_Domain] = eval(Talent_Domain) + 1
                    globals()[TeachingsCommon] = eval(TeachingsCommon) + 3
                    globals()[TeachingsRare] = eval(TeachingsRare) + 2
                    Resin_Count -= 20
                    Mora_Cost -= 2735

                if eval(TeachingsEpic) < Epic_Needed: #Check if we have enough gems
                    if eval(TeachingsRare) >= 3: #Try and craft an Epic
                        globals()[TeachingsEpic] = eval(TeachingsEpic) + 1
                        globals()[TeachingsRare] = eval(TeachingsRare) - 3
                        Mora_Cost += 550

                if eval(TeachingsRare) < Rare_Needed: #Check if we have enough gems
                    if eval(TeachingsCommon) >= 3: #Try and craft an Epic
                        globals()[TeachingsRare] = eval(TeachingsRare) + 1
                        globals()[TeachingsCommon] = eval(TeachingsCommon) - 3
                        Mora_Cost += 175

                if eval(TeachingsEpic) >= Epic_Needed and eval(TeachingsRare) >= Rare_Needed and eval(TeachingsCommon) >= Common_Needed:
                    globals()[TeachingsEpic] = eval(TeachingsEpic) - Epic_Needed
                    globals()[TeachingsRare] = eval(TeachingsRare) - Rare_Needed
                    globals()[TeachingsCommon] = eval(TeachingsCommon) - Common_Needed
                    break

    if Name in ["Xiao", "Rosaria", "Hu Tao"]:
        while PrimoShards < 46:
            Minutes_Spent += 8
            Resin_Count += 1
            Total_Resin += 1
            if Resin_Count >= 40:
                PrimoShards += 3
                Resin_Count -= 40
                Mora_Cost -= 8000
        PrimoShards -= 46
    else:
        globals()[ElementBossSpecific] = eval(ElementBossSpecific) - 46

    print(Name + " Maxed...")#Just so that I know things are actually going on, and a loop isnt running inifnitely because I wrote some code wrong
    print('-')#Break

for x in range(Character_Count):#5, 5-Star artifacts for each character, Both Travelers are included, because maybe you want one Anemo set up, and one Geo setup
    Artifact_EXP = 0
    while Artifact_EXP < 269800:
        Minutes_Spent += 8
        Resin_Count += 1
        Total_Resin += 1
        if Resin_Count >= 20:
            Any_Artifact_Domain_Count += 1
            Resin_Count -= 20
            Mora_Cost -= 2200
            Three_Star_Artifacts += 6
            Four_Star_Artifacts += 2

        if Four_Star_Artifacts > 0:
            Four_Star_Artifacts -= 1
            Artifact_EXP += 2520
            Mora_Cost += 2520

        if Three_Star_Artifacts > 0: #Instead of just adding EXP directly on, this lets any spare artifacts carry over.
            Three_Star_Artifacts -= 1
            Artifact_EXP += 1260
            Mora_Cost += 1260
print(str(Character_Count) + " artifacts maxed...")

print("")
print("")
print("Mora Cost (Before Mora Blossoms): " + str(Mora_Cost))#I also dont know how Escape percents or what ever they're called work, so yeah
while Mora_Cost > 0:
    Minutes_Spent += 8
    Resin_Count += 1
    Total_Resin += 1
    if Resin_Count >= 20:
        Resin_Count -= 20
        Mora_Cost -= 60000
        Mora_Blossom_Count += 1

CopyGlobals = globals()
for x in CopyGlobals: #use an illegal method to convert every variable into a string, so that I dont have to do str() in my print statements
    globals()[x] = str(eval(x))

print("---")
print("Resin:")
print("     Minutes Spent waiting for Resin: " + Minutes_Spent)
print("     Weeks Spent waiting for Resin: " + str(round(int(Minutes_Spent)/10080, 2)))
print("     Years Spent waiting for Resin: " + str(round(int(Minutes_Spent)/525600, 2)))
print("     Resin Spent: " + Total_Resin)
print("")
print("Domains, Outcrops and Mining: ")
if EXP_Blossom_Count == "0":
    print("    Rhodia Body Count " + Rhodia_Count)
if Rhodia_Count == "0":
    print("    EXP Ley Line Outcrops: " + EXP_Blossom_Count)
print("    Mora Ley Line Outcrops: " + Mora_Blossom_Count)
print("    Mondstat Talent Domains: " + Mondstat_Domain_Count)
print("    Liyue Talent Domains: " + Liyue_Domain_Count)
print("    Artifact Domains: " + Any_Artifact_Domain_Count)
print("    Mondstat Weapon Ascention Domains: " + Mondstat_Domain_Count2)
print("    Liyue Weapon Ascention Domains: " + Liyue_Domain_Count2)
print("    Magic Crystals: " + Magic_Crystal_Needed)
print("")
print("Bosses:")
print("     Dvalin's Body Count: " + Dvalin_Body_Count)#Body count as in how many of their bodies we have, not how many bodies they have. As in 100 Dvalin corpses, not the corpses of 100 people that Dvalin has slain.
print("     Wolf's Body Count: " + Wolf_Body_Count)
print("     Childe's Body Count: " + Childe_Body_Count)
print("     Weeks Spent waiting for Weekly Bosses: " + Weeks_Waited)
print("     Minutes Spent waiting for Weekly Bosses: " + str(int(Weeks_Waited)*10080))
print("     Years Spent waiting for Weekly Bosses: " + str(round(int(Weeks_Waited)/52.143,2)))
if int(Weeks_Waited)*10080 > int(Minutes_Spent):
    print("          Time spent waiting for weekly bosses is greater than time spent waiting for resin,")
    print("          Therefore, time spent waiting for resin is irrelevant.")
else:
    print("          Time spent waiting for resin is greater than time spent waiting for weekly bosses,")
    print("          Therefore, time spent waiting for weekly bosses is irrelevant.")
print("")
print("     Anemo Hyposasis' Body Count: " + AnemoBodyCount)#Once again, is how many of their bodies We have. Anemo Hypostasis' Body, as in the body of the Hypostasis, Count, as in how many we have. How many of the Anemo Hypostasis bodies do we have
print("     Cryo Regisvine's Body Count: " + CryoBodyCount)
print("     Electro Hyposasis' Body Count: " + ElectroBodyCount)
print("     Geo Hyposasis' Body Count: " + GeoBodyCount)
print("     Oceanid's Body Count: " + HydroBodyCount)
print("     Pyro Regisvine Body Count: " + PyroBodyCount)
print("")
print("Spare Loot:")
print("     Heros Wits: " + Wits)
print("     Adventurers Experience: " + Experience)
print("     Three-Star Artifacts: " + Three_Star_Artifacts)
print("     Four-Star Artifacts: " + Four_Star_Artifacts)
print("")
try:
    print("     Mora: " + str(abs(int(Mora_Cost))))
except:
    print("     Mora: " + str(int(abs(float(Mora_Cost))))) #Apparently "-52245.0" can't be converted into an integer so i'll convert it to a float instead, and then an int
print("")
print("     Plumes: " + Plume)
print("     Claws: " + Claw)
print("     Sighs: " + Sigh)
print("     Tails: " + Tail)
print("     Rings: " + Ring)
print("     Lockets: " + Locket)
print("     Tusks: " + Tusk)
print("     Legacys: " + Legacy)
print("     Shadows: " + Shadow)
print("")
print("     Anemo Slivers: " + AnemoFragment) #ok fine i just found out what they're called in-game
print("     Hurricane Seeds: " + AnemoBoss) #I used to hvae the Element Fragmenets here too, but no matter what I did they always result in 0, so there's really no point
print("     Cryo Slivers: " + CryoFragment) #Oh also, you're going to get a lot of "Undefined Variables", yeah just ignore him he's harmless
print("     Hoarfrost Cores: " + CryoBoss)
print("     Electro Slivers: " + ElectroFragment)
print("     Lightning Prisims: " + ElectroBoss)
print("     Geo Slivers: " + GeoFragment)
print("     Basalt Pillars: " + GeoBoss)
print("     Hydro Slivers: " + HydroFragment)
print("     Clensing Hearts: " + HydroBoss)
print("     Pyro Slivers: " + PyroFragment)
print("     Everflame Seeds: " + PyroBoss)
print("     Juvenile Jades: " + PrimoShards)
print("")
print("     Tile of Decarabian's Tower: " + DecarabianUncommon)
print("     Debris of Decarabian's City: " + DecarabianRare)
print("     Boreal Wolf's Milk Tooth: " + WolfUncommon)
print("     Boreal Wolf's Cracked Tooth: " + WolfRare)
print("     Fetters of the Dandelion Gladiator: " + DandelionUncommon)
print("     Chains of the Dandelion Gladiator: " + DandelionRare)
print("     Luminous Sands from Guyun: " + GuyunUncommon)
print("     Lustrous Stone from Guyun: " + GuyunRare)
print("     Mist Veiled Lead Elixir: " + ElixerUncommon)
print("     Mist Veiled Mercury Elixir: " + ElixerRare)
print("     Grain of Aerosiderite: " + Aero_ChocolateUncommon)
print("     Peice of Aerosiderite: " + Aero_ChocolateRare)
print("")
print(      "Mystic Enchancement: " + Mystic_Enchancement)


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm
# from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def posts_list(request):
	paginator_page_var = 'page'
	paginator_posts_count = 5
	queryset_list = Post.objects.all()
	paginator = Paginator(queryset_list, paginator_posts_count)
	page = request.GET.get(paginator_page_var)
	try:
		queryset = paginator.page(page)
	except PageNotAnInteger:
		queryset = paginator.page(1)
	except EmptyPage:
		queryset = paginator.page(paginator.num_pages)
	new_post = Post()
	context = {
		'posts': queryset,
		'paginator_page_var': paginator_page_var,
		'new_post': new_post,
	}
	return render(request, 'posts_list.html', context)

def post_details(request, pk=0):
	post = get_object_or_404(Post, pk=pk)
	context = { 'post': post }
	return render(request, 'post_details.html', context)

def post_create(request, test=False):
	form = PostForm(request.POST or None, request.FILES or None)
	if form.is_valid():
		instance = form.save(commit=False)
		instance.save()
		# messages.success(request, 'Post successfully created')
		return HttpResponseRedirect(instance.get_details_url())
	context = { 'form': form, 'test': test }
	return render(request, 'post_form.html', context)

def post_update(request, pk=0, test=False):
	instance = get_object_or_404(Post, pk=pk)
	form = PostForm(request.POST or None, request.FILES or None, instance=instance)
	if form.is_valid():
		instance = form.save(commit=False)
		instance.save()
		return HttpResponseRedirect(instance.get_details_url())
	context = {'form': form, 'test': test,}
	return render(request, 'post_form.html', context)

def post_delete(request, pk=0):
	instance = get_object_or_404(Post, pk=pk)
	instance.delete()
	return redirect('posts:list')


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jan  8 14:36:07 2018
@author: abhijeet
"""

# Importing libraries
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
import string
import re
import numpy as np
from collections import Counter

from sklearn.model_selection import KFold
from sklearn import metrics

#import nltk
#nltk.download('stopwords')
#nltk.download('wordnet')

stop = set(stopwords.words('english'))
exclude = set(string.punctuation)
lemma = WordNetLemmatizer()

# Cleaning the text sentences so that punctuation marks, stop words & digits are removed
def clean(doc):
    stop_free = " ".join([i for i in doc.lower().split() if i not in stop])
    punc_free = ''.join(ch for ch in stop_free if ch not in exclude)
    normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split())
    processed = re.sub(r"\d+","",normalized)
    y = processed.split()
    return y

print ("\nThere are 10 sentences of following three classes on which K-NN classification and K-means clustering"\
         " is performed : \n1. Cricket \n2. Artificial Intelligence \n3. Chemistry")
path = "Sentences.txt"

train_clean_sentences = []
fp = open(path,'r')
for line in fp:
    line = line.strip()
    cleaned = clean(line)
    cleaned = ' '.join(cleaned)
    train_clean_sentences.append(cleaned)

vectorizer = TfidfVectorizer(stop_words='english')
# data x
X = vectorizer.fit_transform(train_clean_sentences)

# Creating true labels for 30 training sentences
# data y
y_train = np.zeros(30)
y_train[10:20] = 1
y_train[20:30] = 2

true_test_labels = ['Cricket','AI','Chemistry']

#Data set untuk test
test_sentences = ["Chemical compunds are used for preparing bombs based on some reactions",\
                  "Cricket is a boring game where the batsman only enjoys the game",\
                  "Machine learning is an area of Artificial intelligence"]

# membersihkan data
test_clean_sentence = []
for test in test_sentences:
    cleaned_test = clean(test)
    cleaned = ' '.join(cleaned_test)
    cleaned = re.sub(r"\d+","",cleaned)
    test_clean_sentence.append(cleaned)

# Data set yang siap digunakan untuk test
Test = vectorizer.transform(test_clean_sentence)

#print data set untuk test
print ("\nBelow 3 sentences will be predicted against the learned nieghbourhood and learned clusters:\n1. ",\
        test_sentences[0],"\n2. ",test_sentences[1],"\n3. ",test_sentences[2])

print("\n-------------------PREDICTION USING CLASSIFICATION-------------------")

#Classification

#KNN
from sklearn.neighbors import KNeighborsClassifier
modelknn = KNeighborsClassifier(n_neighbors=5)
modelknn.fit(X,y_train)
predicted_labels_knn = modelknn.predict(Test)

print ("\n-------------------------PREDICTIONS BY KNN-------------------------")
print ("\n",test_sentences[0],":",true_test_labels[np.int(predicted_labels_knn[0])],\
        "\n",test_sentences[1],":",true_test_labels[np.int(predicted_labels_knn[1])],\
        "\n",test_sentences[2],":",true_test_labels[np.int(predicted_labels_knn[2])],"\n")

# Data untuk split ke dalam KFold
X = X.toarray()
Y = y_train

kf = KFold(n_splits=10)
acc=[]
for train_id, test_id in kf.split(X):
    x_train, x_test = X[train_id], X[test_id]
    y_train, y_test = Y[train_id], Y[test_id]
    modelknn.fit(x_train, y_train);
    y_pred = modelknn.predict(x_test)
    acc.append(metrics.accuracy_score(y_test, y_pred))

print("Akurasi dengan knn","dengan k =",5," = ",np.mean(acc),"\n")

#Naive Bayes
from sklearn.naive_bayes import GaussianNB
nb = GaussianNB()

nb.fit(X,Y)
predicted_labels_nb = nb.predict(Test.toarray())

print ("\n-------------------------PREDICTIONS BY NAIVE BAYES-------------------------")
print ("\n",test_sentences[0],":",true_test_labels[np.int(predicted_labels_nb[0])],\
        "\n",test_sentences[1],":",true_test_labels[np.int(predicted_labels_nb[1])],\
        "\n",test_sentences[2],":",true_test_labels[np.int(predicted_labels_nb[2])],"\n")

acc=[]
for train_id, test_id in kf.split(X):
    x_train, x_test = X[train_id], X[test_id]
    y_train, y_test = Y[train_id], Y[test_id]
    nb.fit(x_train, y_train);
    y_pred = nb.predict(x_test)
    acc.append(metrics.accuracy_score(y_test, y_pred))

print("Akurasi dengan naive bayes = ",np.mean(acc),"\n")

#Decision Tree
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier()

tree.fit(X,Y)
predicted_labels_tree=tree.predict(Test)

print ("\n-------------------------PREDICTIONS BY Decesion Tree-------------------------")
print ("\n",test_sentences[0],":",true_test_labels[np.int(predicted_labels_tree[0])],\
        "\n",test_sentences[1],":",true_test_labels[np.int(predicted_labels_tree[1])],\
        "\n",test_sentences[2],":",true_test_labels[np.int(predicted_labels_tree[2])])

acc=[]
for train_id, test_id in kf.split(X):
    x_train, x_test = X[train_id], X[test_id]
    y_train, y_test = Y[train_id], Y[test_id]
    tree.fit(x_train, y_train);
    y_pred = tree.predict(x_test)
    acc.append(metrics.accuracy_score(y_test, y_pred))

print("Akurasi dengan decision tree = ",np.mean(acc),"\n")

# Clustering the training 30 sentences with K-means technique
from sklearn.cluster import KMeans
modelkmeans = KMeans(n_clusters=3, init='k-means++', max_iter=200, n_init=100)
modelkmeans.fit(X)
predicted_labels_kmeans = modelkmeans.predict(Test)

print ("\n-------------------------PREDICTIONS BY K-Means-------------------------")
print ("\nIndex of Cricket cluster : ",Counter(modelkmeans.labels_[0:10]).most_common(1)[0][0])
print ("Index of Artificial Intelligence cluster : ",Counter(modelkmeans.labels_[10:20]).most_common(1)[0][0])
print ("Index of Chemistry cluster : ",Counter(modelkmeans.labels_[20:30]).most_common(1)[0][0])

print ("\n",test_sentences[0],":",true_test_labels[np.int(predicted_labels_kmeans[0])],\
        "\n",test_sentences[1],":",true_test_labels[np.int(predicted_labels_kmeans[1])],\
        "\n",test_sentences[2],":",true_test_labels[np.int(predicted_labels_kmeans[2])],"\n")

acc = []
dist = []
for train_id, test_id in kf.split(X):
    x_train, x_test = X[train_id], X[test_id]
    y_train, y_test = Y[train_id], Y[test_id]
    modelkmeans.fit(x_train);
    y_pred = modelkmeans.predict(x_test)
    acc.append(metrics.accuracy_score(y_test, y_pred))

print("Akurasi dengan K-Means = ",np.mean(acc),"\n")


import redis

from flask import Flask, render_template, request, flash

app = Flask(__name__)

app.secret_key = 'key'

r = redis.Redis()

last_id = 0

@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == 'POST':
        global last_id
        req = request.form
        name = req["full_name"]
        data = req['data']
        last_id = r.get('last_id')
        if last_id is None:
            last_id = 1
        else:
            last_id = int(last_id) + 1

        r.set("news:name:{0}".format(last_id), name)
        r.set("news:post:{0}".format(last_id), data)
        r.set("last_id", last_id)
        r.lpush("post_id", last_id)
        flash("Successfully created post", category="success")

    return render_template("home.html")

@app.route("/all")
def all_posts():
    post_ids = r.lrange('post_id', 0, -1)
    posts = dict()
    for post_id in post_ids:
        name = r.get("news:name:{0}".format(post_id.decode('utf-8'))).decode('utf-8')
        post_data = r.get("news:post:{0}".format(post_id.decode('utf-8'))).decode('utf-8')
        posts[name] = post_data
    return render_template("all.html", posts=posts)

@app.route('/latest')
def latest_posts():
    post_ids = r.lrange('post_id', 0, 2)
    posts = dict()
    for post_id in post_ids:
        name = r.get("news:name:{0}".format(post_id.decode('utf-8'))).decode('utf-8')
        post_data = r.get("news:post:{0}".format(post_id.decode('utf-8'))).decode('utf-8')
        posts[name] = post_data
    return render_template("latest.html", posts=posts)

app.run()


def solve(f):
    instructions = f.splitlines()
    accumulator = 0
    cur = 0

    visited = set()

    while True:
        if cur in visited:
            return accumulator
        else:
            visited.add(cur)

        inst, val = instructions[cur].split(" ")
        if inst == "nop":
            cur += 1
            continue
        elif inst == "acc":
            accumulator += int("".join(val))
            cur += 1
        elif inst == "jmp":
            cur = (cur + int("".join(val))) % len(instructions)

test = """\
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6"""

def main():

    with open("input.txt") as f:
        print(solve(f.read()))

if __name__ == "__main__":
    main()


# DT2119, Lab 1 Feature Extraction

# Function given by the exercise ----------------------------------

#************************* ****
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import *
from scipy.fftpack import *
from tools import *
from scipy.fftpack.realtransforms import *
#*************************

def mfcc(samples, winlen = 400, winshift = 200, preempcoeff=0.97, nfft=512, nceps=13, samplingrate=20000, liftercoeff=22):
    """Computes Mel Frequency Cepstrum Coefficients.

    Args:
        samples: array of speech samples with shape (N,)
        winlen: lenght of the analysis window
        winshift: number of samples to shift the analysis window at every time step
        preempcoeff: pre-emphasis coefficient
        nfft: length of the Fast Fourier Transform (power of 2, >= winlen)
        nceps: number of cepstrum coefficients to compute
        samplingrate: sampling rate of the original signal
        liftercoeff: liftering coefficient used to equalise scale of MFCCs

    Returns:
        N x nceps array with lifetered MFCC coefficients
    """
    frames = enframe(samples, winlen, winshift)
    preemph = preemp(frames, preempcoeff)
    windowed = windowing(preemph)
    spec = powerSpectrum(windowed, nfft)
    mspec = logMelSpectrum(spec, samplingrate)
    ceps = cepstrum(mspec, nceps)
    return lifter(ceps, liftercoeff)

def mspec(samples, winlen = 400, winshift = 200, preempcoeff=0.97, nfft=512, nceps=13, samplingrate=20000, liftercoeff=22):
    """Computes Mel Frequency Cepstrum Coefficients.

    Args:
        samples: array of speech samples with shape (N,)
        winlen: lenght of the analysis window
        winshift: number of samples to shift the analysis window at every time step
        preempcoeff: pre-emphasis coefficient
        nfft: length of the Fast Fourier Transform (power of 2, >= winlen)
        nceps: number of cepstrum coefficients to compute
        samplingrate: sampling rate of the original signal
        liftercoeff: liftering coefficient used to equalise scale of MFCCs

    Returns:
        N x nceps array with lifetered MFCC coefficients
    """
    frames = enframe(samples, winlen, winshift)
    preemph = preemp(frames, preempcoeff)
    windowed = windowing(preemph)
    spec = powerSpectrum(windowed, nfft)
    return logMelSpectrum(spec, samplingrate)

# Functions to be implemented ----------------------------------

def enframe(samples, winlen, winshift):
    """
    Slices the input samples into overlapping windows.

    Args:
        winlen: window length in samples. 20ms
        winshift: shift of consecutive windows in samples 10ms
    Returns:
        numpy array [N x winlen], where N is the number of windows that fit
        in the input signal
    """
    samples_len = len(samples)
    temp = np.zeros(winlen)
    N = 0
    if samples_len > winlen:
        temp = samples[0:winlen]
        N=N+1
        while(True):
            # compute start and end indexes
            end = winlen + N*(winlen-winshift)
            start = end-winlen
            # if it exceeds the total length, drop the last part
            if(end > samples_len):
                break
            # if it's not the last part, append the window to the array
            temp = np.vstack((temp, samples[start:end]))
            N=N+1
    else:
        temp = np.hstack((samples, np.zeros(winlen - samples_len)))
    return temp

def preemp(input, p=0.97):
    """
    Pre-emphasis filter.

    Args:
        input: array of speech frames [N x M] where N is the number of frames and
               M the samples per frame
        p: preemhasis factor (defaults to the value specified in the exercise)

    Output:
        output: array of pre-emphasised speech samples
    Note (you can use the function lfilter from scipy.signal)
    """
    preemph = np.zeros(input.shape[1])
    # a = [1,0,0,...,0]
    a = np.zeros(input.shape[1])
    a[0]=1
    # b = [1,-p,0,0,...,0]
    b = np.zeros(input.shape[1])
    b[0]=1
    b[1] = -p
    # y[n] = x[n]-ax[n-1]
    # lfilter: a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M] - a[1]*y[n-1] - ... - a[N]*y[n-N]
    # so, 1*y[n] = 1*x[n] + (-p)*x[n-1]
    for i in range(input.shape[0]):
        # a = 0 IIR -> FIR
        sig = lfilter(b, a, input[i],axis=-1, zi=None)
        preemph = np.vstack((preemph,sig))
    return preemph[1:]

def windowing(input):
    """
    Applies hamming window to the input frames.

    Args:
        input: array of speech samples [N x M] where N is the number of frames and
               M the samples per frame
    Output:
        array of windoed speech samples [N x M]
    Note (you can use the function hamming from scipy.signal, include the sym=0 option
    if you want to get the same results as in the example)
    """
    window = hamming(input.shape[1],sym=False)

    # plot the window shape
    # plt.plot(window)
    # plt.show()

    windowed = np.zeros(input.shape[1])
    for i in range(input.shape[0]):
        windowed = np.vstack((windowed, input[i] * window))
    return windowed[1:]

def powerSpectrum(input, nfft):
    """
    Calculates the power spectrum of the input signal, that is the square of the modulus of the FFT

    Args:
        input: array of speech samples [N x M] where N is the number of frames and
               M the samples per frame
        nfft: length of the FFT
    Output:
        array of power spectra [N x nfft]
    Note: you can use the function fft from scipy.fftpack
    """
    spec = np.zeros(nfft)
    for i in range(input.shape[0]):
        f_t = fft(input[i], nfft , axis=-1, overwrite_x=False)
        f_t = f_t.real**2+f_t.imag**2
        spec = np.vstack((spec,f_t))
    return spec[1:]

def logMelSpectrum(input, samplingrate):
    """
    Calculates the log output of a Mel filterbank when the input is the power spectrum

    Args:
        input: array of power spectrum coefficients [N x nfft] where N is the number of frames and
               nfft the length of each spectrum
        samplingrate: sampling rate of the original signal (used to calculate the filterbank shapes)
    Output:
        array of Mel filterbank log outputs [N x nmelfilters] where nmelfilters is the number
        of filters in the filterbank
    Note: use the trfbank function provided in tools.py to calculate the filterbank shapes and
          nmelfilters
    """
    nfft = input.shape[1]
    mspec = []
    fbank = trfbank(samplingrate, nfft, lowfreq=133.33, linsc=200 / 3., logsc=1.0711703, nlinfilt=13, nlogfilt=27,
                    equalareas=False)
    # plt.plot(fbank.T)
    # plt.show()
    for i in range(input.shape[0]):
        result = np.dot(input[i].reshape(1,-1),fbank.T)
        f_result = np.log(result)
        if(i == 0):
            mspec = f_result
        else:
            mspec = np.vstack((mspec, f_result))
    return mspec

def cepstrum(input, nceps):
    """
    Calulates Cepstral coefficients from mel spectrum applying Discrete Cosine Transform

    Args:
        input: array of log outputs of Mel scale filterbank [N x nmelfilters] where N is the
               number of frames and nmelfilters the length of the filterbank
        nceps: number of output cepstral coefficients
    Output:
        array of Cepstral coefficients [N x nceps]
    Note: you can use the function dct from scipy.fftpack.realtransforms
    """
    ceps = dct(input, type=2, axis=1, norm='ortho')[:, 0: nceps]
    return ceps

def dtw(x, y, dist):
    """Dynamic Time Warping.

    Args:
        x, y: arrays of size NxD and MxD respectively, where D is the dimensionality
              and N, M are the respective lenghts of the sequences
        dist: distance function (can be used in the code as dist(x[i], y[j]))

    Outputs:
        d: global distance between the sequences (scalar) normalized to len(x)+len(y)
        LD: local distance between frames from x and y (NxM matrix)
        AD: accumulated distance between frames of x and y (NxM matrix)
        path: best path thtough AD

    Note that you only need to define the first output for this exercise.
    """
    # compute local distances
    locD = np.zeros((x.shape[0],y.shape[0]))
    for i in range(x.shape[0]):
        for j in range(y.shape[0]):
            locD[i][j] = dist(x[i],y[j])
    # print(locD)

    # dynamic programming
    accD = np.zeros((x.shape[0], y.shape[0]))
    for h in range(accD.shape[0]):
        for k in range(accD.shape[1]):
            if h == 0 and k == 0:
                accD[h][k] = locD[h][k]
                continue
            if h == 0:
                accD[h][k] = locD[h][k] + accD[h][k - 1]
                continue
            if k == 0:
                accD[h][k] = locD[h][k] + accD[h - 1][k]
                continue
            accD[h][k] = locD[h][k] + min(accD[h - 1][k], accD[h - 1][k - 1], accD[h][k - 1])

    return accD[accD.shape[0]-1][accD.shape[1]-1]