from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views import generic
from django.views import View

from adn3.services import preregistrations_open
from courses.models import Course
from misc.models import Software
from news.models import New
from .models import FlyIn
from .forms import FlyInForm, RolForm, DeleteForm
from adn3 import mixins

class FlyInsActiveMixin(UserPassesTestMixin):
    login_url = reverse_lazy('flyins:rol_authentication')

    def test_func(self):
        is_authenticated = self.request.session.get('rol', False)
        return preregistrations_open() and is_authenticated

class RolAuthenticationView(UserPassesTestMixin, View):
    template_name = 'flyins/rol_authentication.html'

    def get(self, request):
        if request.session.get('rol', False):
            return redirect(reverse_lazy('flyins:course_list'))
        return render(request, self.template_name)

    def post(self, request):
        initial = {
            'rol': self.request.POST.get('rol')
        }
        form = RolForm(initial)

        if form.is_valid():
            request.session.set_expiry(1200)
            request.session['rol'] = self.request.POST.get('rol')

            return redirect(reverse_lazy('flyins:course_list'))
        else:
            return render(request, self.template_name, {
                'form': form
            })

    def test_func(self):
        return preregistrations_open()

class CourseListView(FlyInsActiveMixin, generic.ListView):
    model = Course
    template_name = 'flyins/course_list.html'

    def get_queryset(self):
        # Filter courses already pre-registered and courses on another campus.
        return super().get_queryset().\
            exclude(status=False).\
            exclude(deactivate_preregistrations=True)

class NewListView(FlyInsActiveMixin, mixins.CourseMixin, generic.ListView):
    model = New
    template_name = 'flyins/new_list.html'

    def get_queryset(self):
        return self.get_course().new_set

class FlyInDetailView(FlyInsActiveMixin, generic.DetailView):
    model = FlyIn

    def get(self, request, *args, **kwargs):
        preinscription = self.get_object()
        if preinscription.rol != self.request.session.get('rol') or preinscription.seen:
            return redirect(reverse_lazy('flyins:course_list'))

        preinscription.seen = True
        preinscription.save()

        return super().get(self, request, *args, **kwargs)

class FlyInCreateView(FlyInsActiveMixin, mixins.CourseMixin, View):
    template_name = 'flyins/preregistration_form.html'
    form_class = FlyInForm

    def get(self, request, course_pk):
        rol = self.request.session.get('rol', False)
        course = self.get_course()

        if course.deactivate_preregistrations:
            return redirect('flyins:course_list')

        preinscription = FlyIn.objects.filter(rol=rol, course__pk=course_pk).first()
        if preinscription:
            return redirect(preinscription.get_delete_url())

        # has_pr = FlyIn.objects.filter(rol=rol, course=course).exists()
        # if has_pr:
        # return render(request, 'flyins/preregistration_exists.html', {
        #         'course': course,
        #     })

        return render(request, self.template_name, {
            'software_list': Software.objects.all(),
            'course': course,
            'view': self,
        })

    def post(self, request, course_pk):
        rol = self.request.session.get('rol', False)

        preinscription = FlyIn.objects.filter(rol=rol, course__pk=course_pk).first()

        if preinscription:
            return redirect(preinscription.get_delete_url())

        preferences = request.POST.getlist('block')
        sel_names = ['first_preference', 'second_preference', 'third_preference',
                     'fourth_preference', 'fifth_preference']
        selections = {}

        for i, p in enumerate(sel_names):
            selections[p] = preferences[i] if len(preferences) > i else ''

        initial = {
            'course': self.get_course().pk,
            'software': self.request.POST.get('software'),
            'previous_experience': self.request.POST.get('previous_experience'),
            'parallel': self.request.POST.get('parallel'),
            'first_name': self.request.POST.get('first_name'),
            'last_names': self.request.POST.get('last_names'),
            'rol': self.request.POST.get('rol'),
            'usm_priority': self.request.POST.get('usm_priority').replace(',', '.'),
        }
        initial.update(selections)

        form = FlyInForm(initial)

        if form.is_valid():
            instance = form.save()
            return redirect(instance.get_absolute_url())

        return render(request, self.template_name, {
            'form': form,
            'course': self.get_course(),
            'view': self,
        })

class FlyInDeleteView(FlyInsActiveMixin, View):
    template_name = 'flyins/flyin_confirm_delete.html'

    def get(self, request, pk):
        rol = self.request.session.get('rol', False)

        preinscription = FlyIn.objects.filter(rol=rol, pk=pk).first()

        if not preinscription:
            return redirect(reverse_lazy('flyins:course_list'))

        return render(request, self.template_name, {
            'flyin': preinscription
        })

    def post(self, request, pk):
        rol = self.request.session.get('rol', False)

        preinscription = FlyIn.objects.filter(rol=rol, pk=pk).first()

        if not preinscription:
            return redirect(reverse_lazy('flyins:course_list'))

        secret = self.request.POST.get('secret') if self.request.POST.get('secret') is not None else "NULL"

        initial = {
            'rol': self.request.POST.get('rol'),
            'secret': secret,
            'pk': self.request.POST.get('pk'),
        }

        form = DeleteForm(self.request, initial)

        if form.is_valid():
            re = reverse_lazy('flyins:preregistration_create', args=[preinscription.course.pk])
            preinscription.delete()
            return redirect(re)

        return render(request, self.template_name, {
            'form': form,
            'flyin': preinscription,
        })


import sys

def fibonacciNoRecursivo(n: int) -> int:
  longMax: int = n+1
  l: list[int] = []
  maxFibonacci: int = 0;
  indice: int = 0
  while(indice < longMax):
     if(len(l) == 0):
        l.append(0)
     elif(len(l) == 1):
         l.append(1)
     else:
        terminoSiguiente: int = l[indice-1] + l[indice-2]
        l.append(terminoSiguiente)
     indice+=1

  maxFibonacci = l[len(l)-1]
  return maxFibonacci

"""
(∃l : seq⟨Z⟩)(|l| = n + 1 ∧ esSecuenciaFiibonacci(l) ∧ l[|l|−1] = result)
La secuencia de fibonacci que tengo que hacer va hasta n +1.
Luego, devuelvo el último valor de la lista.
print("fibonacci 0: " + str(fibonacciNoRecursivo(0)))
print("fibonacci 1: " + str(fibonacciNoRecursivo(1)))
print("fibonacci 2: " + str(fibonacciNoRecursivo(2)))
print("fibonacci 3: " + str(fibonacciNoRecursivo(3)))
print("fibonacci 4: " + str(fibonacciNoRecursivo(4)))
print("fibonacci 5: " + str(fibonacciNoRecursivo(5)))
print("fibonacci 6: " + str(fibonacciNoRecursivo(6)))
print("fibonacci 7: " + str(fibonacciNoRecursivo(7)))
print("fibonacci 8: " + str(fibonacciNoRecursivo(8)))
print("fibonacci 9: " + str(fibonacciNoRecursivo(9)))
print("fibonacci 10: " + str(fibonacciNoRecursivo(10))) """

if __name__ == '__main__':
  x = int(input())
  print(fibonacciNoRecursivo(x))


# Import requests, shutil python module.
import requests
import shutil
import io,pickle
import urllib.request
from multiprocessing import Pool
from concurrent import futures
from urllib.error import URLError, HTTPError
from PIL import Image
from threading import Lock, Thread
from socket import timeout
import time
import datetime

def get_num_pixels(filepath):
    width, height = Image.open(filepath).size
    return width*height

pickle_in = open("url2captionORIGINAL.pickle",'rb')
url2captionORIGINAL = pickle.load(pickle_in)
url2caption ={}
filepath = '/home/ying/Downloads/SBUCaptionedPhotoDataset/dataset/SBU_captioned_photo_dataset_urls.txt'
urllists1 =[]
urllists2 =[]
urllists3 =[]
urllists4 =[]
urllists5 =[]
validurls =[]
url_list =[urllists1,urllists2,urllists3,urllists4,urllists5]
pickle_list = ['url2caption1.pickle','url2caption2.pickle','url2caption3.pickle','url2caption4.pickle','url2caption5.pickle']
count = 0
lock = Lock()
with open(filepath) as fp:
    url_count =0
    for cnt, line in enumerate(fp):
        url = line.strip('\n')
        if url_count <20:
            urllists1.append(url)

        if url_count >= 20 and url_count < 40:
            urllists2.append(url)

        if url_count >= 40 and url_count < 60:
            urllists3.append(url)

        if url_count >= 60 and url_count < 80:
            urllists4.append(url)

        if url_count >= 800000:
            urllists5.append(url)
        url_count+=1
print(len(urllists1),len(urllists2),len(urllists3),len(urllists4),len(urllists5))
fp.close()
def get_valid_images(url):
    lock.acquire()
    global count
    count += 1
    lock.release()
    try:
        f = urllib.request.urlopen(url,timeout=10)
    except HTTPError as e:
        pass
        #print('The server couldn\'t fulfill the request.')
        #print('Error code: ', e.code)
    except URLError as e:
        pass
        #print('We failed to reach a server.')
        #print('Reason: ', e.reason)
    except timeout:
        pass
    except:
        pass
    else:
        b = io.BytesIO(f.read())
        im = Image.open(b)
        width, height = im.size
        #print(width, height)
        if width * height > 300 * 500:
            lock.acquire()
            validurls.append(url)
            lock.release()

def parallel(urllists,pick_name):
    count = 0
    with futures.ThreadPoolExecutor(max_workers=100) as executor:
        executor.map(get_valid_images, urllists)

        lock.acquire()
        while count != len(urllists):
            tmp = count
            lock.release()
            print(tmp, '/', len(urllists))
            time.sleep(5)
            lock.acquire()
        lock.release()
    for url in validurls:
        url2caption[url] = url2captionORIGINAL[url]
    print(len(url2caption))
    pickle_out = open(pick_name, 'wb')
    pickle.dump(url2caption, pickle_out)
    pickle_out.close()
    validurls.clear()
    url2caption.clear()

for i in range(5):
    parallel(url_list[i],pickle_list[i] )
    print("finish",(i+1)*200000)

# image_url = "https://www.dev2qa.com/demo/images/green_button.jpg"
# # Open the url image, set stream to True, this will return the stream content.
# resp = requests.get(image_url, stream=True)
# # Open a local file with wb ( write binary ) permission.
# local_file = open('local_image.jpg', 'wb')
# # Set decode_content value to True, otherwise the downloaded image file's size will be zero.
# resp.raw.decode_content = True
# # Copy the response stream raw data to local image file.
# shutil.copyfileobj(resp.raw, local_file)
# # Remove the image url response object.
# del resp


from math import ceil, floor
from typing import List

def smallestDivisor(nums: List[int], threshold: int) -> int:
    """Return smallest divisor such that sum of `nums` normalised
    with respect to the divisor is at most `threshold`."""

    lo = 1
    hi = max(nums)

    while lo < hi:
        mid = floor((lo + hi) / 2)
        normalisedSum = sum(ceil(num / mid) for num in nums)

        if normalisedSum <= threshold:
            # Can try smaller threshold, but keep `mid` as candidate
            hi = mid
        else:
            # Sum too large, need bigger divisor
            lo = mid + 1

    return lo


from collections import defaultdict, Counter
from time import time
class ProblemA():
	#def setup(self):
	#	pass
	#def transform(self, vals):
	#	pass
	#def solveAll(self):
	#	pass

	spawntimer = 7
	newborntimer = 2
	days = 80

	def readFish(self, line):
		# Performance on 1048576 days: defaultdict(int) = 3.2s, Counter = 4.2s
		fish = defaultdict(int)
		fish |= Counter(map(int, line.split(",")))
		return fish

	def solveInstance(self, line):
		fish = self.readFish(line)

		for day in range(self.days):
			spawn = day + self.spawntimer
			newborn = spawn + self.newborntimer
			today = fish.pop(day, 0)
			fish[spawn] += today
			fish[newborn] = today # =: 3.2s, +=: 5.8s. lmao

		return sum(fish.values())

class ProblemB(ProblemA):
	days = 1048576

if __name__ == '__main__': # Run when this script is not imported by another script(e.g. Unittest)
    start_time = int(round(time() * 1000))
    with open("6/example1.txt") as f:
        lines = f.readlines()
    print(ProblemB().solveInstance(lines[0]))

    print("### total run time is %s miliseconds" % (int(round(time() * 1000)) - start_time))


import utilities as util
import displays as display
from displays import clear_screen, header_text, logo
import sounds
'''game_menu is where player can know more about the game
such as: about the game, the instructions. This is where also the
player can proceed to the main game.
'''

def run_game_menu(player_name):
    while True:
        clear_screen()
        header_text(f"# WELCOME TO SINGING BEE {player_name}!")
        display.print_position(3, 20, logo)
        display.game_menu_options()
        player_choice = util.get_input_position(1, 31, ">>")

        if player_choice.upper() in ['P', 'A', 'H', 'Q']:
            if player_choice.upper() == 'A':
                sounds.play_sound("sounds/game_sounds\\select_sound.wav")
                clear_screen()
                display.about_game_screen()

            elif player_choice.upper() == 'H':
                sounds.play_sound("sounds/game_sounds\\select_sound.wav")
                clear_screen()
                display.help_screen()

            elif player_choice.upper() == 'Q':
                sounds.play_sound("sounds/game_sounds\\select_sound.wav")
                sounds.stop_sound()
                clear_screen()
                display.quit_screen(player_name)

            elif player_choice.upper() == 'P':
                sounds.play_sound("sounds/game_sounds\\select_sound.wav")
                clear_screen()
                display.loading_screen()
                break
        else:
            display.invalid_option(0, 30)


import tkinter as tk
from tkinter import filedialog
import RunData as rd
import socket
import numpy as np
from time import sleep

root = tk.Tk()
root.geometry('400x400')

#global signal recieved for example
signal = True

# based on EMG signals, we could change background color

#Set Text indicator
w = tk.Label(root, text = 'Not Running')
w.pack()

#SOCKET AND BOOLEAN STUFF
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.settimeout(1.0)
# Match with OpenBCI_GUI
host = "127.0.0.1"
port = 12345
s.bind((host,port))

# 0 for data stream
# 1 for rand testing
test = 1
run = None

#threshold for ON ::: Need to test for this
th = 0.1
x = np.array([1,1])
y = np.array([0,0])

####

def clock():
    global x, y, run
    data = rd.RunData(test, s, th, x, y)
    muscle = data[0]
    x = data[1]
    y = data[2]
    print(muscle)

    if muscle == True:
        message = "signal recieved"
        root.configure(background='green')
    else:
        message = "no signal"
        root.configure(background='red')

    w.config(text=message)
    startStop.configure(text='Stop Stream', command=stopStream)
    run = root.after(500, clock) # run itself again after X ms

def file_save():
    f = filedialog.asksaveasfilename(defaultextension=".txt")
    if f is None:
        return
    np.savetxt(f,np.transpose((x,y)),delimiter=',', header=' Set 1  ,  Set 2  ,', fmt = '%.4e')

def stopStream():
    #If already running, stop the data reading
    root.after_cancel(run)
    w.config(text = 'Not Running')
    startStop.configure(text='Start Stream', command=clock)
    root.configure(background='DarkOrchid3')

#Set Buttons
save = tk.Button(root, text='SAVE DATA', command=file_save)
save.pack(pady=10)
startStop = tk.Button(root,text='Start Stream', command=clock)
startStop.pack()

root.mainloop()


import streamlit as st
import tensorflow as tf
import cv2
from PIL import Image, ImageOps
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf

from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

# st.image("""omdena.png""")
# st.title("Disaster & Non-Disaster Image Classification")
# st.header("Please input an image to be classified:")
# st.write("Created by Omdena South-Africa Team")
st.set_page_config(page_title='Omdena South Africa Chapter', layout='wide')

@st.cache(allow_output_mutation=True)

def classifying(img, weights_file):
    # Load the model
    model = keras.models.load_model(weights_file)
    # Create the array of the right shape to feed into the keras model
    data = np.ndarray(shape=(1, 200, 200, 3), dtype=np.float32)
    image = img
    # image sizing
    size = (200, 200)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)
    # turn the image into a numpy array
    image_array = np.asarray(image)
    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 255)
    # Load the image into the array
    data[0] = normalized_image_array
    # run the inference
    prediction_percentage = model.predict(data)
    prediction = prediction_percentage.round()
    return prediction, prediction_percentage

st.markdown(
        """
        <style>
        .block-container.css-18e3th9.egzxvld2 {
        padding-top: 0;
        }
        header.css-vg37xl.e8zbici2 {
        background: none;
        }
        .css-1mr91h5 {
            background-color: transparent;
        }
        span.css-10trblm.e16nr0p30 {
        text-align: center;
        color: #2c39b1;
        }
        .css-1dp5vir.e8zbici1 {
        background-image: linear-gradient(
        90deg, rgb(130 166 192), rgb(74 189 130)
        );
        }
        .css-tw2vp1.e1tzin5v0 {
        gap: 10px;
        }
        .css-50ug3q {
        font-size: 1.2em;
        font-weight: 600;
        color: #2c39b1;
        }
        .row-widget.stSelectbox {
        padding: 10px;
        background: #ffffff;
        border-radius: 7px;
        }
        .row-widget.stRadio {
        padding: 10px;
        background: #ffffff;
        border-radius: 7px;
        }
        label.css-cgyhhy.effi0qh3, span.css-10trblm.e16nr0p30 {
        font-size: 1.1em;
        font-weight: bold;
        font-variant-caps: small-caps;
        border-bottom: 3px solid #F8BE37;
        }
        .css-12w0qpk.e1tzin5v2 {
        background: #d2d2d2;
        border-radius: 8px;
        padding: 5px 10px;
        }
        label.css-18ewatb.e16fv1kl2 {
        font-variant: small-caps;
        font-size: 1em;
        }
        .css-1xarl3l.e16fv1kl1 {
        float: right;
        }
        div[data-testid="stSidebarNav"] li div a {
        margin-left: 1rem;
        padding: 1rem;
        width: 300px;
        border-radius: 0.5rem;
        }
        div[data-testid="stSidebarNav"] li div::focus-visible {
        background-color: rgba(151, 166, 195, 0.15);
        }
        svg.e1fb0mya1.css-fblp2m.ex0cdmw0 {
        width: 2rem;
        height: 2rem;
        }
        .css-11wiv6u {
        background-color: #f1dfc9;
        }
        </style>
        """, unsafe_allow_html=True
    )

st.image("assets/logo-long.png")
st.title("Disaster & Non-Disaster Image Classification")
st.header("Please input an image to be classified:")
st.write("Created by Omdena South-Africa Team")
st.write("VGG16 is a convolution neural network which has been trained on a subset of the 'ImageNet' dataset, a collection of over 14 million images belonging to 22,000 categories.")
st.write("We use the pre-trained model's architecture to create a new dataset from our input images in this approach.")
st.write("We pass our images through VGG16's convolution layers, it gives  an output of feature stack of the detected visual features.")
st.write("The Implementation Process:")
st.write("VGG16 has been imported from the keras.applications")
st.write("Bringing in a new top portion for the model with using the weights from 'Imagenet'")
st.write("The pre-trained convolution layers are freezed")
st.write("The model summary")
st.write("The images have to be first kept in their respective folders with labels for 'Train' and and an unlabelled folder of images was taken for the 'Test' data.")
st.write("The images in the dataset was  processed before using it to classify while passing through the model. We used the 'Image Data Generator' function imported from keras library to do this")
st.write("After getting the data preprocessed, it was fit into the model to analyze the accuracy  and the history is mapped to get the details")
st.write("The vgg16 model gave us a respectable model accuracy")
st.write("With this the vgg16 model was used on an unlabelled set of images to classify it into two categories based on the type of data entered.")
st.write("The dataset in this case being a set of 'Crimes Images' and the 'Disaster Images'.")

uploaded_file = st.file_uploader("Please upload an image file here... (JPEG or PNG)", type="jpg")

if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption='Uploaded file', use_column_width=True)
    st.write("")
    label,perc = classifying(image, 'disaster_model.h5')
    if label == 1:
        st.write('This is a disaster image!')
    else:
        st.write('This is a non-disaster image')


from flask import (Blueprint, render_template, g, redirect, url_for, flash, request, jsonify)
from jpApp.db import (get_db, updateDB)

bp = Blueprint("main", __name__)

@bp.route('/wordList')
def wordList():
    db = get_db()
    jpWords = db.execute(
        'SELECT id, jpWord, pronunciation, meaning, dateRevised FROM jpVocab'
    ).fetchall()
    print("JP WORDS LIST: ")
    for item in jpWords:
        for x in item:
            print(x)
    flash("hi")
    return render_template('main/wordList.html', jpWords = jpWords)

@bp.route('/addWord', methods=('GET', 'POST'))
def addWord():
    if request.method == 'POST':
        jpWord = request.form['jpWord']
        pronunciation = request.form['pronunciation']
        meaning = request.form['meaning']
        error = None

        if not jpWord:
            error = "Please enter a japanese word."
        if not pronunciation:
            error = "Please enter the pronunciation"
        if not meaning:
            error = "Please enter the meaning"

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO jpVocab (jpWord, pronunciation, meaning)'
                ' VALUES (?,?,?)',
                (jpWord, pronunciation, meaning)
            )
            db.commit()
            return redirect(url_for('main.wordList'))
    return render_template("main/addWord.html")

@bp.route('/clearAllRecords', methods=('GET', 'POST'))
def clearAllRecords():
    db = get_db()
    db.execute('DELETE FROM jpVocab')
    db.commit()
    return redirect(url_for("main.wordList"))

@bp.route('/dbRecords', methods=('GET', 'POST'))
def dbRecords():
    db = get_db()
    records = db.execute('SELECT * FROM jpVocab').fetchall()
    return render_template('main/dbRecords.html', records = records)

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

@bp.route('/getJpWordInfo', methods=['GET'])
def getJpWordInfo():
    jpWord = request.args.get('jpWord')

    db = get_db()
    dbWord = db.execute(
        'SELECT * FROM jpVocab'
        ' WHERE jpWord = ?',
        (jpWord, )
    ).fetchone()
    meaning = dbWord['meaning']
    prc = dbWord['pronunciation']
    print("prc :  "  +prc)
    print("meaning: " +  meaning)
    json = jsonify({"meaning":meaning, "prc":prc})
    print(json)
    return json


import optparse
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware

def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'text/plain')])
    return [b'You have to call the url_prefix']

def load_options(default_host="127.0.0.1",
             default_port="5000", url_prefix=""):
    """
    Parses command-line flags to configure the app.
    """

    # Set up the command-line options
    parser = optparse.OptionParser()
    parser.add_option("-H", "--host",
                      help="Hostname of the Flask app " +
                           "[default %s]" % default_host,
                      default=default_host)
    parser.add_option("-P", "--port",
                      help="Port for the Flask app " +
                           "[default %s]" % default_port,
                      default=default_port)

    parser.add_option("-U", "--url_prefix",
                      help="Url Prefix for the Flask app " +
                           "[default %s]" % url_prefix,
                      default=url_prefix)

    # Two options useful for debugging purposes, but
    # a bit dangerous so not exposed in the help message.
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug",
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("-p", "--profile",
                      action="store_true", dest="profile",
                      help=optparse.SUPPRESS_HELP)

    options, _ = parser.parse_args()
    return options

def flaskrun(app, options=None):
    """
    Takes a flask.Flask instance and runs it.
    """

    # Set up the command-line options
    if options is None:
        options = load_options()

    if not options.debug:
        options.debug = False

    # If the User selects the profiling option, then we need
    # to do a little extra setup
    if options.profile:
        # noinspection PyPackageRequirements
        from werkzeug.contrib.profiler import ProfilerMiddleware

        app.config['PROFILE'] = True
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
                                          restrictions=[30])
        options.debug = True

    app.wsgi_app = DispatcherMiddleware(simple, {options.url_prefix: app.wsgi_app})

    app.config["APPLICATION_ROOT"] = options.url_prefix

    app.run(
        debug=options.debug,
        host=options.host,
        port=int(options.port)
    )


"""
Input	                        Output
a b c d e f g h                 ['a', 'c', 'e', 'g', 'b', 'd', 'f', 'h']
5

one two three four              ['one', 'three', 'two', 'four']
3
"""
text = str(input())
count_of_shuffles = int(input())
text_list = text.split(" ")

for x in range (0, count_of_shuffles):
    first_half_list = []
    second_half_list = []
    shuffle_list = []
    elements = 0
    for i in range (0, len(text_list)):
        if i < len(text_list)/2:
            first_half_list.append(text_list[i])
        else:
            second_half_list.append(text_list[i])
    while elements < len(first_half_list):
        for j in range (0, len(first_half_list)):
            shuffle_list.append(first_half_list[j])
            shuffle_list.append(second_half_list[j])
            elements += 1
        text_list = shuffle_list
print(shuffle_list)

Python Programming Fundamentals/Ex_03_Lists Basics/Ex3_05 Faro Shuffle.py


# coding=utf-8
from __future__ import absolute_import

### (Don't forget to remove me)
# This is a basic skeleton for your plugin's __init__.py. You probably want to adjust the class name of your plugin
# as well as the plugin mixins it's subclassing from. This is really just a basic skeleton to get you started,
# defining your plugin as a template plugin, settings and asset plugin. Feel free to add or remove mixins
# as necessary.
#
# Take a look at the documentation on what other plugin mixins are available.
import re
import string
import octoprint.plugin

class Nc2marlinPlugin(octoprint.plugin.SettingsPlugin,
                      octoprint.plugin.AssetPlugin,
                      octoprint.plugin.TemplatePlugin):

    def __init__(self):
        self._fan_gcode   = 'M106'
        self._wait_gcode  = 'G4'
        self._last_mcode  = ''
        self._last_gcode  = 'G0'
        self._mode        = ''
        self._wait        = 0

    # mode : none, marlin, laser, plotter
    def get_settings_defaults(self):
        return dict(mode = 'none', wait = '0')

    def get_settings_version(self):
        return 1

    def get_template_configs(self):
        return [
            dict(type = "settings", custom_bindings = False)
            #dict(type="settings", template="nc2marlin_settings.jinja2", custom_bindings=True)
        ]

    def get_assets(self):
        return dict(
            #js=['js/nc2marlin.js'],
            css=['css/nc2marlin.css'],
            less=['less/nc2marlin.less']
        )

    def get_template_vars(self):
        return dict(
            mode = self._settings.get(['mode']),
            wait = self._settings.get(['wait']),
        )

    def get_update_information(self):
        # Define the configuration for your plugin to use with the Software Update
        # Plugin here. See https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html
        # for details.
        return dict(
            nc2marlin=dict(
                displayName='nc2marlin',
                displayVersion=self._plugin_version,

                # version check: github repository
                type='github_release',
                user='pinggusoft',
                repo='OctoPrint-nc2marlin',
                current=self._plugin_version,

                # update method: pip
                pip='https://github.com/pinggusoft/OctoPrint-nc2marlin/archive/{target_version}.zip'
            )
        )

    def get_settings(self):
        self._mode = self._settings.get(['mode'])
        self._wait = int(self._settings.get(['wait']))

    def on_after_startup(self):
        self.get_settings()

    # use below function only when custom_bindings is True
    #def on_settings_save(self, data):
    #    self._logger.info('SAVE data:' + data)
    #    octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
    #    self.get_settings()

    ###############################################################################################
    #  Codes
    ###############################################################################################
    def toFanCmd(self, out, strSpeed):
        speed = 0;
        isInv = True if self._mode == 'plotter' else False

        if strSpeed:
            speed = int(strSpeed)
        if isInv:
            speed = 255 - speed

        code = self._fan_gcode + ' S' + str(speed)
        if code != self._last_mcode:
            out.append(code)
            self._last_mcode = code
            if self._wait != 0:
                out.append(self._wait_gcode + ' P' + str(self._wait))

    def rewrite_gcode(self, comm_instance, phase, cmd, cmd_type, gcode, subcode, tags, *args, **kwargs):
        self.get_settings()
        #self._logger.info('Processing queuing: [' + cmd + ',' + str(cmd_type)+ ',' + str(tags) + ']')
        #self._logger.info('mode:' + self._mode + ', wait:' + str(self._wait))

        # return immediately if the mode is none
        if self._mode == 'none':
            return cmd

        line = cmd
        out  = []

        find = re.search('^[G|M|\(|;|T|\s].*', line)            # find valid commands G, M, (, ;, T, blank
        if find == None:                                        # if not, add last gcode to the begining
            line = self._last_gcode + ' ' + line

        # find available gcode
        find = re.search('^(G[0-3][^0-9]).*', line)             # find G0-G3
        if find:
            items = find.groups();
            self._last_gcode = items[0]

        # only add skipped gcode with marlin mode
        if self._mode == 'marlin':
            out.append(line)
            return out

        find = re.search('^(G[0-3][^0-9])(.*)S([0-9]*)', line)  # find G0-G3 with S parameter
        if find:
            items = find.groups();
            self.toFanCmd(out, items[2])
            if len(items[1]) > 1:
                out.append(items[0] + items[1])
        else:
            find = re.search('(^M[3-4]$|^M[3-4][^0-9])\s*S*([0-9]*)', line)        # find M3, M4 w/wo S
            if find:
                items = find.groups();
                strSpeed = '255' if len(items[1]) == 0 else items[1]
                self.toFanCmd(out, strSpeed)
            else:
                find = re.search('^M5$', line)                      # find M5
                if find:
                    strSpeed = '0'
                    self.toFanCmd(out, strSpeed)
                else:
                    out.append(line)

        #self._logger.info(out)
        return out

# If you want your plugin to be registered within OctoPrint under a different name than what you defined in setup.py
# ('OctoPrint-PluginSkeleton'), you may define that here. Same goes for the other metadata derived from setup.py that
# can be overwritten via __plugin_xyz__ control properties. See the documentation for that.
__plugin_name__ = 'nc2marlin'

# Starting with OctoPrint 1.4.0 OctoPrint will also support to run under Python 3 in addition to the deprecated
# Python 2. New plugins should make sure to run under both versions for now. Uncomment one of the following
# compatibility flags according to what Python versions your plugin supports!
#__plugin_pythoncompat__ = '>=2.7,<3' # only python 2
#__plugin_pythoncompat__ = '>=3,<4' # only python 3
__plugin_pythoncompat__ = '>=2.7,<4' # python 2 and 3

def __plugin_load__():
    global __plugin_implementation__
    __plugin_implementation__ = Nc2marlinPlugin()

    global __plugin_hooks__
    __plugin_hooks__ = {
        'octoprint.plugin.softwareupdate.check_config': __plugin_implementation__.get_update_information,
        'octoprint.comm.protocol.gcode.queuing': __plugin_implementation__.rewrite_gcode,
    }


from flask import Flask, render_template, request, redirect, url_for
import csv
import os

app = Flask(__name__)

# Helper functions

def read_info():
    subjs_info = []
    curr_dir = os.path.dirname(os.path.abspath(__file__))
    file_name = os.path.join(curr_dir, "static/data/subjects.csv")

    with open(file_name, "r") as f:
        csvreader = csv.reader(f)
        _ = next(csvreader)  # remove header line

        for row in csvreader:
            subjs_info.append(row)

    return subjs_info

subjs_info = read_info()

def score_to_grade_gpa(score):
    matrix = {
        85: ("A*", 5.0), 75: ("A1", 4.0), 70: ("A2", 3.5),
        65: ("B3", 3.0), 60: ("B4", 2.5), 55: ("C5", 2.0),
        50: ("C6", 1.5), 45: ("D7", 1.0), 40: ("E8", 0.5),
        0: ("F9", 0.0)
    }
    for cutoff_point in matrix:
        if score >= cutoff_point:
            return matrix[cutoff_point]

def normal_gpa(subjs):
    # this will simply calculate average gpa for all subjs for sec 1 to 3
    total_gpa = 0
    total_weightage = 0

    for row in subjs:
        if row[1] == "ss":
            total_gpa += row[-1] * 0.5
            total_weightage += 0.5
        else:
            total_gpa += row[-1]
            total_weightage += 1.0

    return round(total_gpa / total_weightage, 2)

def sec4_gpa(user_subjs):
    best_sci = ["subj", 0]
    best_hum = ["subj", 0]
    best_other = ["subj", 0]

    for subj in user_subjs:
        if subj[2] == "Science" and subj[7] >= best_sci[1]:
            best_sci = [subj[1], subj[7]]
        elif subj[2] == "Humanities" and subj[7] >= best_hum[1] \
                and subj[1] != "ss":
            best_hum = [subj[1], subj[7]]

    for subj in user_subjs:
        if subj[2] == "Science" and subj[1] != best_sci[0] \
                and subj[7] >= best_other[1]:
            best_other = [subj[1], subj[7]]
        elif subj[2] == "Humanities" and subj[1] != best_hum[0] \
                and subj[7] >= best_other[1] and subj[1] != "ss":
            best_other = [subj[1], subj[7]]
        elif subj[2] == "Maths" and subj[7] >= best_other[1]:
            best_other = [subj[1], subj[7]]

    total_gpa = 0
    total_weight = 0

    for subj in user_subjs:
        if subj[1] in ["el", "hcl", "maths", "cid"] or \
                subj[1] in [best_sci[0], best_hum[0], best_other[0]]:
            total_gpa += subj[7]
            total_weight += 1
            if best_other[0] == "maths" and subj[1] == "maths":
                subj.append("D")
            else:
                subj.append("C")
        elif subj[1] == "ss":
            total_gpa += subj[7] * 0.5
            total_weight += 0.5
            subj.append("C")
        else:
            subj.append("U")

    return round(total_gpa/total_weight, 2)

# Flask functions

@app.route('/')
def index():
    return render_template('p1_index.html', level=1)

@app.route('/subjs_selection/')
def subjs_selection():
    level = request.args["level"]

    if level in "12":
        # user selected sec 1 or 2
        return redirect(url_for("gpa_calc", level=level))
    else:
        # user selected sec 3 or 4
        compul_subjs = []
        opt_sci_subjs = []
        opt_hum_subjs = []

        for row in subjs_info:
            if level in row[3] and row[4] == "T":
                # this subj is compulsory for this level
                compul_subjs.append(row)
            elif level in row[3] and row[2] == "Science" and row[4] == "F":
                # this sci subj is optional for this level
                opt_sci_subjs.append(row)
            elif level in row[3] and row[2] == "Humanities" and row[4] == "F":
                # this hum subj is optional for this level
                opt_hum_subjs.append(row)

        return render_template(
            "p2_subjs_selection.html", level=level, compul_subjs=compul_subjs,
            opt_sci_subjs=opt_sci_subjs, opt_hum_subjs=opt_hum_subjs
        )

@app.route('/gpa_calc/', methods=["GET", "POST"])
def gpa_calc():
    if request.method == "GET":
        level = request.args["level"]
        user_subjs = []

        if level in "12":
            # sec 1 or 2
            for row in subjs_info:
                if level in row[3]:
                    # all subjs are compulsory for sec 1&2
                    user_subjs.append(row)

            opt_sci_subjs = []
            opt_hum_subjs = []
        else:
            # sec 3 or 4
            opt_sci_subjs = request.args.getlist("opt_sci_subjs")
            opt_hum_subjs = request.args.getlist("opt_hum_subjs")
            # print(sci_subjs, hum_subjs)
            for row in subjs_info:
                if level in row[3] and row[4] == "T":
                    # this subj is compulsory for this level
                    user_subjs.append(row)
                elif row[1] in opt_sci_subjs or row[1] in opt_hum_subjs:
                    # this optional subj is selected by user
                    user_subjs.append(row)

            # print(subjs)
        return render_template(
            "p3_scores_entry.html", level=level, user_subjs=user_subjs,
            opt_sci_subjs=opt_sci_subjs, opt_hum_subjs=opt_hum_subjs,
        )
    else:
        # process the subjs data
        level = request.form["level"]

        user_subjs = []
        opt_sci_subjs = []
        opt_hum_subjs = []

        for key in request.form:
            for row in subjs_info:
                if row[1] == key:
                    new_row = row.copy()
                    # append the score of the subj to the new list
                    new_row.append(int(request.form[key]))
                    # add the subj info with score to subjs
                    user_subjs.append(new_row)
                    # only 1 subj will match the condition
                    break

        # print(subjs)

        # process the score to grade and gpa
        for row in user_subjs:
            if row[4] == "F" and row[2] == "Science":
                opt_sci_subjs.append(row[1])
            elif row[4] == "F" and row[2] == "Humanities":
                opt_hum_subjs.append(row[1])

            # print(row)
            # print(score_to_grade_gpa(row[-1]))
            grade, gpa = score_to_grade_gpa(row[-1])

            row.append(grade)
            row.append(gpa)

        # print(subjs)
        if level in "123":
            gpa = normal_gpa(user_subjs)
        else:
            gpa = sec4_gpa(user_subjs)

        # print(user_subjs, gpa)
        return render_template(
            "p4_result.html", level=level, subjs=user_subjs, gpa=gpa,
            opt_sci_subjs=opt_sci_subjs, opt_hum_subjs=opt_hum_subjs
        )

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


#!/bin/python3

import json
import datetime
import subprocess

today = datetime.datetime.today()

log_file_name = f'/var/log/{today.strftime("%Y-%m-%d-awesome-monitoring.log")}'
timestamp = today.strftime("%H-%M-%S")

print(log_file_name)
with open ('/proc/loadavg','r', encoding = 'utf-8') as info:
    info_dict = info.read().split(' ')
    loadavg =  {'Load 1 m':info_dict[0],
                'Load 5 m':info_dict[1],
                'Load 15 m':info_dict[2],
                }

with open ('/proc/meminfo','r', encoding = 'utf-8') as info:
    info_dict = info.read().split('\n')
    MemAvailable = info_dict[2].split('     ')
    SwapFree = info_dict[15].split('     ')
    meminfo = { MemAvailable[0][:-1]:MemAvailable[1].strip(),
                SwapFree[0][:-1]:SwapFree[1].strip()
            }

inodes = {}
useless_cat_call = subprocess.Popen(["df","-li"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
df = useless_cat_call.communicate()
df1 = str(df).split('\\n')
for inodes_parameter in df1:
    if inodes_parameter[0] == "/":
        params = inodes_parameter.split(' ')
        disk_name = inodes_parameter.split(' ')[0]
        for index in range(len(params)):
            if params[index] != '' and params[index][0] != '/':
                free_inodes = params[index+2]
                inodes.setdefault(disk_name,free_inodes)
                break

awesome_monitoring = {  'timestamp':timestamp,
                        'loadavg':loadavg,
                        'meminfo':meminfo,
                        'free inodes':inodes
                        }

with open (log_file_name,'a', encoding = 'utf-8') as log:
    json.dump(awesome_monitoring, log)


import csv
import json
import datetime

eos_contract_address = '0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf'
eos_contract_file_name = 'txs_'+eos_contract_address+'.json'

cmcAssetsListFile = 'assetsList.json'

try:
    with open(cmcAssetsListFile, 'r') as fAssets:
        assets = json.load(fAssets)
        fAssets.close
except:
    assets = {}

# https://stackoverflow.com/questions/26944274/valueerror-dict-contains-fields-not-in-fieldnames
csvfile = open(cmcAssetsListFile+'.csv','wb')
writer = csv.writer(csvfile, delimiter = ';')

writer.writerow(["asset","rank", "cmcUrl", "linkType", "linkUrl"])

bttThreads = {}
for asset in assets:
    bttThreads[asset] = []
    for link in assets[asset]["links"]:
        if link["linkType"] not in ['Rank','Tags']:
            writer.writerow([ asset,
                              assets[asset]["rank"],
                              assets[asset]["cmcUrl"],
                              link["linkType"],
                              link["linkUrl"] ])
        if assets[asset]["rank"] < 1000 and link["linkType"] == 'Announcement' and link["linkUrl"].find('bitcointalk.org') != -1:
            # bttThreads.append( { asset : link["linkUrl"] } )
            bttThreads[asset].append({"btt":link["linkUrl"]})

csvfile.close()

with open('assetsListBtt.json', 'w') as fAssetsListBtt:
    json.dump(bttThreads, fAssetsListBtt, sort_keys=True, indent=4)
fAssetsListBtt.close


#import modules
import json
import pandas as pd
from binance.client import Client
from envs import env
import time
import re

#import classes from ./ folder
import postgresdbAccess

#read fibonacci retracements  from json
with open('fibLvl.json') as file:
    fibLvl = json.load(file)

class liveAccess:
    def __init__(self):
        try:
            self.liveVolume=env("liveVolume")
            apiSecret=env('apiSecret')
            apiKey=env('apiKey')
            self.dbTable=env('dbTable')
            self.baseCurrency=env('baseCurrency')
            self.brokerFees=float(env('brokerFees'))
            self.liveTrading=env("liveTrading", 'False').lower() in ('true', '1', 't')
        except KeyError:
            print("No env variables set.")
            sys.exit(1)
        self.client = Client(apiKey, apiSecret, {'timeout':600})

    def closeTrade(self, resultData, i):
        stopId = resultData[resultData[0] == resultData[0].min()]
        if self.liveTrading == True:
            #get assets before sale
            symbolIsolated = re.sub(self.baseCurrency, '', self.bA[1][i])
            #wait a bit because otherwise api error
            time.sleep(1)
            assetsBefore = float(self.client.get_asset_balance(asset=self.baseCurrency)['free'])
            try:
                self.client.order_market_sell(symbol = self.bA[1][i], quantity = float(self.client.get_asset_balance(asset = symbolIsolated)['free']))
            except:
                print("Sell order was not executed on symbol: " + str(self.bA[1][i]))
                self.client.order_market_sell(symbol = self.bA[1][i], quantity = float(self.client.get_asset_balance(asset = symbolIsolated)['free'])*0.9)
            time.sleep(5)
            #get assets after sale
            assetsAfter = float(self.client.get_asset_balance(asset = self.baseCurrency)['free'])
            assetsResult = assetsAfter - assetsBefore
            percentChange = ((assetsResult / self.bA[5][i])*100)-100
        else:
            percentChange = ((stopId[2] - self.bA[4][i]) / self.bA[4][i]) * 100 - self.brokerFees * 3.5
        #update database to include result
        sql = ("UPDATE " + self.dbTable + " SET" +
            " resultpercent = '" + str(float(percentChange)) +
            "', stopid = '" + str(float(stopId[0])) +
            "' WHERE id = '" + str(self.bA[0][i]) +
            "';")
        self.postgres.sqlUpdate(sql)

    def validate(self):
        self.postgres = postgresdbAccess.postgresAccess()
        sql = ("SELECT id, symbol, takeprofit, stoploss, askprice, positioncost" +
            " FROM " + self.dbTable + " WHERE" +
            " resultpercent IS NULL " +
            " AND takeprofit IS NOT NULL;")
        self.bA = pd.DataFrame(self.postgres.sqlQuery(sql))
        self.bA[0] = pd.to_numeric(self.bA[0])
        self.bA[2] = pd.to_numeric(self.bA[2])
        self.bA[3] = pd.to_numeric(self.bA[3])
        self.bA[4] = pd.to_numeric(self.bA[4])
        self.bA[5] = pd.to_numeric(self.bA[5])
        for i, row in self.bA.iterrows():
            sql = ("select id, askprice, bidprice from " + self.dbTable + " where id > '" + str(self.bA[0][i]) +
            "' and symbol = '" + str(self.bA[1][i]) + "';")
            validated = pd.DataFrame(self.postgres.sqlQuery(sql))
            if len(validated) > 0:
                validated = validated.apply(pd.to_numeric, errors='coerce')
                tpData = validated[validated[1] >= self.bA[2][i]]
                slData = validated[validated[1] <= self.bA[3][i]]
                if (len(slData) > 0 and len(tpData) > 0 and
                    slData[0].min() < tpData[0].min()):
                    self.closeTrade(slData, i)
                elif (len(slData) > 0 and len(tpData) > 0 and
                    slData[0].min() > tpData[0].min()):
                    self.closeTrade(tpData, i)
                elif len(slData) > 0:
                    self.closeTrade(slData, i)
                elif len(tpData) > 0:
                    self.closeTrade(tpData, i)
        self.postgres.databaseClose()


from IPython.display import HTML, display
from tic_tac_toe.Player import Player
from tic_tac_toe.Board import Board, GameResult, CROSS, NAUGHT
import tensorflow as tf

def print_board(board):
    display(HTML("""
    <style>
    .rendered_html table, .rendered_html th, .rendered_html tr, .rendered_html td {
      border: 1px  black solid !important;
      color: black !important;
    }
    </style>
    """ + board.html_str()))

def play_game(board: Board, player1: Player, player2: Player):
    player1.new_game(CROSS)
    player2.new_game(NAUGHT)
    board.reset()

    finished = False
    while not finished:
        result, finished = player1.move(board)
        if finished:
            if result == GameResult.DRAW:
                final_result = GameResult.DRAW
            else:
                final_result = GameResult.CROSS_WIN
        else:
            result, finished = player2.move(board)
            if finished:
                if result == GameResult.DRAW:
                    final_result = GameResult.DRAW
                else:
                    final_result = GameResult.NAUGHT_WIN

    # noinspection PyUnboundLocalVariable
    player1.final_result(final_result)
    # noinspection PyUnboundLocalVariable
    player2.final_result(final_result)
    return final_result

def battle(player1: Player, player2: Player, num_games: int = 100000, silent: bool = False):
    board = Board()
    draw_count = 0
    cross_count = 0
    naught_count = 0
    for _ in range(num_games):
        result = play_game(board, player1, player2)
        if result == GameResult.CROSS_WIN:
            cross_count += 1
        elif result == GameResult.NAUGHT_WIN:
            naught_count += 1
        else:
            draw_count += 1

    if not silent:
        print("After {} game we have draws: {}, Player 1 wins: {}, and Player 2 wins: {}.".format(num_games, draw_count,
                                                                                cross_count,
                                                                                naught_count))

        print("Which gives percentages of draws: {:.2%}, Player 1 wins: {:.2%}, and Player 2 wins:  {:.2%}".format(
            draw_count / num_games, cross_count / num_games, naught_count / num_games))

    return cross_count, naught_count, draw_count

def evaluate_players(p1: Player, p2: Player, games_per_battle=100, num_battles=100,
                     writer=None, silent: bool = False):
    p1_wins = []
    p2_wins = []
    draws = []
    game_number = []
    game_counter = 0

    for i in range(num_battles):
        p1win, p2win, draw = battle(p1, p2, games_per_battle, silent)
        p1_wins.append(p1win)
        p2_wins.append(p2win)
        draws.append(draw)
        game_counter = game_counter + 1
        game_number.append(game_counter)
        if writer is not None:
            summary = tf.compat.v1.Summary(value=[tf.compat.v1.Summary.Value(tag='Player 1 Win', simple_value=p1win),
                                        tf.compat.v1.Summary.Value(tag='Player 2 Win', simple_value=p2win),
                                        tf.compat.v1.Summary.Value(tag='Draw', simple_value=draw)])
            writer.add_summary(summary, game_counter)

    return game_number, p1_wins, p2_wins, draws


import pickle
import numpy as np
import traceback
from folder_utils import *
from data_utils import *

class DataProcessing:
    def __init__(self, rows=None, window_size=0):
        self.file_rows = rows
        self.window = window_size
        self.bag_of_sensors = get_empty_bag_of_sensors(rows)

    def process_data(self):
        i = 0
        feature_vector = []
        label_array = []
        # Sensor events from raw data
        rows = self.file_rows
        # Represents activities that began but didn't end
        activities_not_finished = []

        # Fixed Windows size
        if self.window > 0:
            total_windows = len(rows) - self.window + 1
            for i in range(0, total_windows):
                window_rows = rows[i:self.window + i]

                if window_rows:
                    features = generate_feature_vector(window_rows, activities_not_finished, self.bag_of_sensors)

                    if features[1] != "Other":
                        feature_vector.append(features[0])
                        label_array.append(features[1])
                else:
                    feature_vector = []

        # Dynamic Windows size
        else:
            raw_filtered, windows_size = get_dynamic_window(rows)
            bag_of_sensors = get_empty_bag_of_sensors(raw_filtered)
            previous_window = 0

            for i, window in zip(range(0, len(windows_size)), windows_size):
                window_rows = raw_filtered[previous_window:window + previous_window]
                previous_window += window

                if window_rows:
                    features = generate_feature_vector(window_rows, activities_not_finished, bag_of_sensors)

                    if features[1] != "Other":
                        feature_vector.append(features[0])
                        label_array.append(features[1])
                else:
                    feature_vector = []

        feature_vector_array = normalize_data(feature_vector)
        unique_activities_list = np.unique(np.array(label_array))
        return [feature_vector_array, label_array, unique_activities_list]

if __name__ == '__main__':
    # Get path from files
    ROOT_DIR = get_root_dirname()
    FILES_DIR = join_paths(ROOT_DIR, "datasets")

    # Get datasets on directory
    dataFiles = list_directory(FILES_DIR)

    # Window size
    windowSize = [0, 30]

    for window in windowSize:
        print("Window size: ", window)
        # Filename to save
        filename = "__window_" + str(window)
        for file in dataFiles:
            if not file.startswith('.'):
                print("File to be processed: ", file)
                try:
                    file_rows = open_dataset_files(join_paths(FILES_DIR, file + "/ann.txt"))
                    dataProcessed = DataProcessing(file_rows, window)
                    data_array = dataProcessed.process_data()

                    inputData, labelData, uniqueActivitiesList = data_array

                    dir_name = os.path.dirname(join_paths(ROOT_DIR, "input_data/"))
                    if not os.path.exists(dir_name):
                        os.makedirs(dir_name)

                    if window == 0:
                        path = join_paths(dir_name, "Dynamic") + "/" + file + filename
                    else:
                        path = join_paths(dir_name, "Static") + "/" + file + filename

                    with open(path, 'wb') as fp:
                        pickle.dump(inputData, fp)
                        pickle.dump(labelData, fp)
                        pickle.dump(uniqueActivitiesList, fp)
                        fp.close()

                except:
                    print('Exception : ' + file)
                    traceback.print_exc()
                    pass


import sqlite3
import datetime

class db_creation:

    def vehical_details(self):
        conn = sqlite3.connect('Parking_Management_System.db')

        conn.execute('''CREATE TABLE Vehical_details
                (ID                   INTEGER     PRIMARY KEY   AUTOINCREMENT  NOT NULL,
                VehicalNumber         TEXT                                     NOT NULL,
                ParkingSpaceNumber    INTEGER                                  NOT NULL,
                ParkingStarttime      Text              ,
                ParkingEndtime        Text
                 );
                ''')

        conn.close()

    def ParkingSpot_details(self):
        conn = sqlite3.connect('Parking_Management_System.db')

        conn.execute('''
                CREATE TABLE ParkingSpot_details
                (
                ParkingSpotNumber     INTEGER     PRIMARY KEY   AUTOINCREMENT   NOT NULL,
                Spot                  TEXT        NOT NULL      ,
                VehicalNumber         TEXT
                 );
                ''')

        for i in range(1,51):
            conn.execute(''' INSERT INTO ParkingSpot_details (Spot, VehicalNumber) \
                    VALUES ( "Empty" , Null )''');

            conn.commit()

        conn.close()

class db_operations:

    def get_empty_parking_spot(self):
                conn = sqlite3.connect('Parking_Management_System.db')
                cursor = conn.cursor()

                empty_spot = cursor.execute(''' Select *
                                            FROM ParkingSpot_details
                                            Where Spot = "Empty" ;
                                            ''')
                conn.commit()
                return empty_spot

    def get_Occupied_parking_spot(self):
                conn = sqlite3.connect('Parking_Management_System.db')
                cursor = conn.cursor()

                Occupied_spot = cursor.execute(''' Select *
                                            FROM ParkingSpot_details
                                            Where Spot = "Occupied" ;
                                            ''')
                conn.commit()

                return Occupied_spot

    def park_vehical(self,VehicalNumber):
        conn = sqlite3.connect('Parking_Management_System.db')
        cursor = conn.cursor()

        empty_spot = self.get_empty_parking_spot()
        empty_spot = empty_spot.fetchone()

        if empty_spot is None:

            return "No Parking Spots available"

        else:
            cursor.execute('''
                Update ParkingSpot_details  Set VehicalNumber = ?,
                Spot = "Occupied"
                Where  ParkingSpotNumber = ? ;
                ''', (VehicalNumber, str(empty_spot[0])))

            cursor.execute( " INSERT INTO Vehical_details (VehicalNumber, ParkingSpaceNumber, ParkingStarttime) \
                            VALUES ( ? , ?, ? )", (VehicalNumber, str(empty_spot[0]), datetime.datetime.now() ))

            conn.commit()

            parking_details = " Please Park Your Vehical " + VehicalNumber + " at Spot Number " + str(empty_spot[0])

            return parking_details

    def Departing_vehical(self, VehicalNumber ):
            conn = sqlite3.connect('Parking_Management_System.db')
            cursor = conn.cursor()

            departing_VehicalNumber = cursor.execute("Select * FROM ParkingSpot_details Where VehicalNumber == ? ;", (VehicalNumber,) )
            departing_Vehical_Number = departing_VehicalNumber.fetchone()

            if departing_Vehical_Number is None:

                result =  "This Vehical is not Parked in Parking Lot"

            else:
                cursor.execute('''
                                Update ParkingSpot_details  Set VehicalNumber = NULL,
                                Spot = "Empty"
                                Where  VehicalNumber == ?;
                                ''', (str(departing_Vehical_Number[2]),))

                cursor.execute('''
                                Update Vehical_details  Set ParkingEndtime = ?
                                Where  VehicalNumber == ? ;
                                ''', ( datetime.datetime.now(),str(departing_Vehical_Number[2])))

                conn.commit()

                result = "Vehical " + VehicalNumber + " is departed from Spot "  + str(departing_Vehical_Number[0]) + " and total fare is " + str(self.fare_calculator(VehicalNumber)) + " Rs "

            return result

    def fare_calculator(self, VehicalNumber):
        conn = sqlite3.connect('Parking_Management_System.db')
        cursor = conn.cursor()

        departing_VehicalNumber = cursor.execute("Select ParkingStarttime, ParkingEndtime FROM Vehical_details Where VehicalNumber == ? ;", (VehicalNumber,) )
        departing_Vehical_Number = departing_VehicalNumber.fetchone()

        starttime = datetime.datetime.strptime(departing_Vehical_Number[0], '%Y-%m-%d %H:%M:%S.%f').hour
        endtime = datetime.datetime.strptime(departing_Vehical_Number[1], '%Y-%m-%d %H:%M:%S.%f').hour
        total_hours = endtime - starttime
        if total_hours <= 0:
            return 10
        else:
            return total_hours*10

    def search_vehical(self, VehicalNumber):
        conn = sqlite3.connect('Parking_Management_System.db')
        cursor = conn.cursor()

        Vehical = cursor.execute("Select VehicalNumber, ParkingSpotNumber  FROM ParkingSpot_details Where VehicalNumber == ? ;", (VehicalNumber,) )

        Vehical = Vehical.fetchone()

        if Vehical is None:

            result =  "This Vehical is not Parked in Parking Lot"

        else:

            result = "Vehical " + str(Vehical[0]) + " is parked at spot " + str(Vehical[1])

        return result

#if __name__ == "__main__":
    # create = db_creation()
    # create.ParkingSpot_details()
    # create.vehical_details()

    #data =  db_operations()
    # print(data.get_empty_parking_spot())
    #print(data.get_Occupied_parking_spot())
    # print(data.park_vehical("MH23645"))
    #print(data.search_vehical("876ghhhttyft"))
    # print(data.fare_calculator("MH23645"))


import pygame
import random

pygame.init()

#red green blue
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')

clock = pygame.time.Clock()

appleThickness = 25
block_size = 15.0
FPS = 30
font = pygame.font.SysFont(None, 25)

def snake(block_size, snakelist):
    for XnY in snakelist:
        pygame.draw.rect(gameDisplay, black, [XnY[0], XnY[1], block_size, block_size])

def msg2screen(msg, color):
    screen_text = font.render(msg, True, color)
    gameDisplay.blit(screen_text, [display_width/3.5, display_height/2])

def score(msg, color):
    screen_text = font.render(msg, True, color)
    gameDisplay.blit(screen_text, [display_width / 2, display_height / 10])

def gameLoop():
    gameExit = False
    gameOver = False

    lead_x = display_width / 2
    lead_y = display_height / 2
    lead_x_change = 0
    lead_y_change = 0

    points = 0
    snakeList=[]
    snakeLength = 1

    randAppleX = round(random.randrange(0, display_width- appleThickness)/block_size)*block_size
    randAppleY = round(random.randrange(0, display_height- appleThickness)/block_size)*block_size

    while not gameExit:

        while gameOver == True :
            gameDisplay.fill(white)
            msg2screen("Game Over,press C to continue or Q to quit", red)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameExit = True
                    gameOver = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    lead_x_change = -block_size
                    lead_y_change = 0
                elif event.key == pygame.K_RIGHT:
                    lead_x_change = block_size
                    lead_y_change = 0
                elif event.key == pygame.K_UP:
                    lead_y_change = -block_size
                    lead_x_change = 0
                elif event.key == pygame.K_DOWN:
                    lead_y_change = block_size
                    lead_x_change = 0

        lead_x += lead_x_change
        lead_y += lead_y_change

        gameDisplay.fill(white)

        score(str(points), green)
        pygame.draw.rect(gameDisplay, red, [randAppleX,randAppleY,appleThickness,appleThickness])

        snakeHead = []
        snakeHead.append(lead_x)
        snakeHead.append(lead_y)
        snakeList.append(snakeHead)

        if len(snakeList) > snakeLength:
            del snakeList[0]
        snake(block_size, snakeList)
        pygame.display.update()

        for eachSegment in snakeList[:-1]:
            if eachSegment == snakeHead:
                gameOver = True

        if lead_x > randAppleX and lead_x < randAppleX + appleThickness or lead_x + block_size > randAppleX and lead_x + block_size < randAppleX + appleThickness:
            if lead_y > randAppleY and lead_y < randAppleY + appleThickness or lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + appleThickness:
                randAppleX = round(random.randrange(0, display_width - appleThickness) / block_size) * block_size
                randAppleY = round(random.randrange(0, display_height - appleThickness) / block_size) * block_size
                snakeLength += 1
                points += 1
            elif lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + appleThickness:
                randAppleX = round(random.randrange(0, display_width - appleThickness) / block_size) * block_size
                randAppleY = round(random.randrange(0, display_height - appleThickness) / block_size) * block_size
                snakeLength += 1
                points += 1

        if lead_x >= display_width or lead_x <= -block_size or lead_y >= display_height or lead_y <= -block_size:
            gameOver = True

        clock.tick(FPS)

    pygame.quit()
    quit()

gameLoop()


def get_melon_counts(filename):
    """Return tally of melons by type"""

    with open(filename) as order_data:
        melon_counts = {
            'musk': 0,
            'hybrid': 0,
            'watermelon': 0,
            'winter': 0
        }
        for line in order_data:
            _, melon_type, melon_count = line.rstrip().split('|')
            melon_counts[melon_type.lower()] += int(melon_count)

        return melon_counts

def get_total_revenue(counts):
    """Prints revenue for each melon type"""

    total_revenue = 0

    melon_prices = {
        'musk': 1.15,
        'hybrid': 1.30,
        'watermelon': 1.75,
        'winter': 4.00
    }

    for melon_type in counts:
        price = melon_prices[melon_type]
        revenue = counts[melon_type] * melon_prices[melon_type]
        total_revenue += revenue
        print(f"We sold {counts[melon_type]} {melon_type} melons at ${price:.2f} each for a total of ${revenue:.2f}")

def get_sales_by_type(filename):
    """Compare sales revenue of online orders and orders from salespeople"""

    with open(filename, 'r') as sales_data:
        online_revenue = 0
        salesperson_revenue = 0

        for line in sales_data:
            _, sales_type, _, amt = line.rstrip().split('|')

            if sales_type == "0":
                online_revenue += float(amt)
            else:
                salesperson_revenue += float(amt)

        print(f"Salespeople generated ${salesperson_revenue:.2f} in revenue.")
        print(f"Internet sales generated ${online_revenue:.2f} in revenue.")

        if salesperson_revenue > online_revenue:
            print("Guess there's some value to those salespeople after all.")
        else:
            print("Time to fire the sales team! Online sales rule all!")

def main():
    """Add comment here"""

    # Get the order counts
    counts = get_melon_counts('orders-by-type.txt')

    # Get the total revenue
    print('*' * 50)
    get_total_revenue(counts)

    # Get the revenue by type
    print('*' * 50)
    get_sales_by_type('orders-with-sales.txt')

# Call main function
main()


'''
Este programa é parte dos trabalhos práticos do segundo bimestre
da disciplina de Processamento Digital de Imagens,
ministrada na FCT-UNESP em 2022.

Autores:
Carlos Eduardo Fernandes de Santana
Daniel Henrique Serezane Pereira

///

Aula 10.1
Prática:
1) Implementar o Laplaciano e o Laplaciano da Gaussiana (LoG) exibindo os dois resultados lado a lado
2) Normalizar ou Equalizar as imagens resultantes, para uma boa visualização
'''

from PIL import Image
from numpy import array as nparray, empty
from numba import njit

@njit
def colorizar(img):
    width, height = img.shape[:2]

    # Loopando e aplicando pseudocores
    subs = empty(3)
    for i in range(width):
        for j in range(height):
            tom = img[i, j][0]
            if(tom < 64):
                subs[0] = 0
                subs[1] = 0
                subs[2] = tom * 4
            elif(tom >= 64 and tom < 128):
                subs[0] = 0
                subs[1] = (tom - 64) * 4
                subs[2] = 255
            elif(tom >= 128 and tom < 192):
                subs[0] = 0
                subs[1] = 255
                subs[2] = 255 - ((tom - 128) * 4)
            elif(tom >= 192):
                subs[0] = (tom - 192) * 4
                subs[1] = 255
                subs[2] = 0
            img[i, j] = subs

# Abrindo imagem e representando como matriz
# Já fazemos a conversão de escala de cinza para RGB
# (a imagem mantém-se cinza, mas cada tom agora está em uma cor RGB)
img = nparray(Image.open("imagens/Fig0622(a)(tropical_rain_grayscale.tif").convert('RGB'))

colorizar(img)

# Remontando e exibindo a imagem após a colorização
img = Image.fromarray(img)
img.show()


import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from pycompss.api.api import compss_wait_on
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

import dislib as ds
from dislib.classification import CascadeSVM, RandomForestClassifier

def main():
    h = .02  # step size in the mesh

    names = ["Linear C-SVM", "RBF C-SVM", "Random forest"]

    classifiers = [
        CascadeSVM(kernel="linear", c=0.025, max_iter=5),
        CascadeSVM(gamma=2, c=1, max_iter=5),
        RandomForestClassifier(random_state=1)
    ]

    x, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
                               random_state=1, n_clusters_per_class=1)
    rng = np.random.RandomState(2)
    x += 2 * rng.uniform(size=x.shape)
    linearly_separable = (x, y)

    datasets = [make_moons(noise=0.3, random_state=0),
                make_circles(noise=0.2, factor=0.5, random_state=1),
                linearly_separable
                ]

    preprocessed_data = dict()
    scores = dict()
    mesh_accuracy_ds = dict()
    for ds_cnt, data in enumerate(datasets):
        # preprocess dataset, split into training and test part
        x, y = data
        x = StandardScaler().fit_transform(x)
        x_train, x_test, y_train, y_test = \
            train_test_split(x, y, test_size=.4, random_state=42)
        ds_x_train = ds.array(x_train, block_size=(20, 2))
        ds_y_train = ds.array(y_train.reshape(-1, 1), block_size=(20, 1))
        ds_x_test = ds.array(x_test, block_size=(20, 2))
        ds_y_test = ds.array(y_test.reshape(-1, 1), block_size=(20, 1))

        x_min, x_max = x[:, 0].min() - .5, x[:, 0].max() + .5
        y_min, y_max = x[:, 1].min() - .5, x[:, 1].max() + .5
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                             np.arange(y_min, y_max, h))
        preprocessed_data[ds_cnt] = x, x_train, x_test, y_train, y_test, xx, yy

        for name, clf in zip(names, classifiers):
            clf.fit(ds_x_train, ds_y_train)
            scores[(ds_cnt, name)] = clf.score(ds_x_test, ds_y_test)

            mesh = np.c_[xx.ravel(), yy.ravel()]
            mesh_array = ds.array(mesh, (mesh.shape[0], 2))

            if hasattr(clf, "decision_function"):
                mesh_proba = clf.decision_function(mesh_array)
            else:
                mesh_proba = clf.predict_proba(mesh_array)
            mesh_accuracy_ds[(ds_cnt, name)] = mesh_proba

    # Synchronize while plotting the results
    plt.figure(figsize=(27, 9))
    i = 1
    for ds_cnt, data in enumerate(datasets):
        x, x_train, x_test, y_train, y_test, xx, yy = preprocessed_data[ds_cnt]

        # just plot the dataset first
        cm = plt.cm.RdBu
        cm_bright = ListedColormap(['#FF0000', '#0000FF'])
        ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
        if ds_cnt == 0:
            ax.set_title("Input data")
        # Plot the training points
        ax.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=cm_bright,
                   edgecolors='k')
        # Plot the testing points
        ax.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=cm_bright,
                   alpha=0.6,
                   edgecolors='k')
        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xticks(())
        ax.set_yticks(())
        i += 1

        # iterate over classifiers
        for name, clf in zip(names, classifiers):
            ax = plt.subplot(len(datasets), len(classifiers) + 1, i)

            score = compss_wait_on(scores[(ds_cnt, name)])
            mesh_proba = mesh_accuracy_ds[(ds_cnt, name)]

            if hasattr(clf, "decision_function"):
                Z = mesh_proba.collect()
            else:
                Z = mesh_proba.collect()[:, 1]

            # Put the result into a color plot
            Z = Z.reshape(xx.shape)
            ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)

            # Plot the training points
            ax.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=cm_bright,
                       edgecolors='k')
            # Plot the testing points
            ax.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=cm_bright,
                       edgecolors='k', alpha=0.6)

            ax.set_xlim(xx.min(), xx.max())
            ax.set_ylim(yy.min(), yy.max())
            ax.set_xticks(())
            ax.set_yticks(())
            if ds_cnt == 0:
                ax.set_title(name)
            ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
                    size=15, horizontalalignment='right')
            i += 1

    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    main()


import sys
import pygame

from game_func.settings import Settings
from entidades.nave import Nave
from game_func.pontos import Pontos
import game_func.game_functions as gf
from game_func.menu import Menu

def rodar_jogo():
    """Inicializa as estruturas de dados das entidades do jogo,
    inicializa as funções do pygame e roda o loop principal do jogo"""

    #Inicializa todos os módulos importados do pygame
    pygame.init()

    configuracoes = Settings()

    #Cria uma janela usando como base as configurações determinadas...
    #...em Settings
    screen = pygame.display.set_mode(
        (configuracoes.screen_width, configuracoes.screen_height))

    #Determina o nome da janela criada anteriormente
    pygame.display.set_caption("Alien Invasion")

    #Inicializa um relógio para determinar um limite de iterações por...
    #...segundos; será implementado no laço principal
    clock = pygame.time.Clock()

    #Cria uma lista de estrelas que irão compor no background
    estrelas = []

    #Cria uma lista de inimigos para cada tipo
    aliens_amarelos = []
    aliens_verdes = []
    aliens_vermelhos = []

    #Cria uma lista para cada tipo de projétil lançado pelos inimigos
    projeteis_verdes = []
    projeteis_vermelhos = []

    #Cria uma lsita auxiliar, que vai conter objetos de Vida, Moeda...
    #...Projetil, ProjetilVerde e ProjetilVermelho
    lista_auxiliar = []

    #Cria uma lista para cada iten que o jogador poderá coletar
    vidas = []
    moedas = []

    #Cria uma lista para os itens que serão mostrados no HUD,...
    #....e inicializa a lista com três vidas
    vidas_restantes = []
    gf.criar_vidas_hud_inicial(screen, vidas_restantes)

    #Cria ums lista para os efeitos de explosão
    explosoes = []

    #Cria um contador usado como temporizador para ativar certas...
    #..funcionalidades;
    #index 0: contador para criação de um novo alien
    #index 1: contador para mudança de dificuldade
    #index 2: tempo para a criação de um novo alien
    #index 3: contador para a criação de um novo item
    contador = [0, 0, 150, 0]

    #Cria 50 estrelas que compõe o background
    gf.criar_estrelas(screen, estrelas)

    #Cria um objeto de Pontos que irá desenhar a quantidade de pontos...
    #... ganhos pelo jogador na tela
    pontos = Pontos(screen)

    #Cria uma nave, o objeto que será controlado pelo jogador
    nave = Nave(screen)

    #Cria uma lista de projeteis que serão lançados pela nave
    projeteis = []

    #Cria um menu de opções
    menu = Menu(screen)

    while True:
        """Inicia o loop principal do jogo"""
        #Preenche o background
        screen.fill(configuracoes.bg_color)

        #Atualiza e desenha as erstrelas, que ficam presentes em...
        #.. todos os menus e no jogo em si
        gf.atualizar_estrelas(estrelas)

        if menu.opcao_menu == -1:
            #Exibe o menu principal
            gf.check_events_menu_principal(menu, aliens_amarelos,
                aliens_verdes, aliens_vermelhos, nave, pontos,
                explosoes, vidas_restantes, lista_auxiliar, screen,
                vidas, moedas, projeteis, projeteis_verdes,
                projeteis_vermelhos)
            menu.atualizar()

        elif menu.opcao_menu == 0:
            #Inicia o jogo
            #Aguarda eventos de entrada do mouse e do teclado
            gf.check_events(nave, screen, projeteis, lista_auxiliar,
                menu)

            #Atualiza entidades e as desenha na tela
            gf.update_screen(
                contador, configuracoes, screen, nave, projeteis,
                aliens_amarelos, aliens_verdes, explosoes,
                projeteis_verdes, aliens_vermelhos, projeteis_vermelhos,
                vidas, moedas, vidas_restantes, pontos, lista_auxiliar,
                menu)

        elif menu.opcao_menu == 1 or menu.opcao_menu == 5:
            #Exibe o menu de highscores(a ser feito) e a tela para...
            #...quando o jogador morre
            gf.check_events_highscore_morte(menu)
            menu.atualizar()

        elif menu.opcao_menu == 3:
            #Exibe o menu de pause
            gf.check_events_menu_pause(menu)
            menu.atualizar()

        elif menu.opcao_menu == 2:
            #Se o jogador pressionar 'Sair' o jogo é terminado
            sys.exit()

        pygame.display.flip()

        #Mantem o FPS do jogo estável em 100 iterações por segundo
        clock.tick(100)

if __name__ == '__main__':
    rodar_jogo()


from . import render_engine
from . import context_hybridpro

from rprblender.operators.world import FOG_KEY

from rprblender.utils import logging
log = logging.Log(tag='render_engine_hybridpro')

class RenderEngine(render_engine.RenderEngine):
    _RPRContext = context_hybridpro.RPRContext

    def depsgraph_objects(self, depsgraph, with_camera=False):
        for obj in super().depsgraph_objects(depsgraph, with_camera):
            if obj.name == FOG_KEY:
                continue

            yield obj

    def _update_athena_data(self, data):
        data['Quality'] = "hybridpro"


# -*- coding: utf-8 -*-
# @File    : model2.py
# @Author  : Hua Guo
# @Time    : 2019/12/18 下午9:30
# @Disc    :
import tensorflow as tf
from tensorflow.keras.layers import LSTM,  Dense
from tensorflow.keras.layers import Input, Dense, Dropout, Flatten, BatchNormalization
from tensorflow.keras.layers import Bidirectional, GlobalMaxPool1D, MaxPooling1D, Add, Flatten, GlobalAveragePooling1D, GlobalMaxPooling1D, concatenate, SpatialDropout1D
from tensorflow.keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Conv1D, GRU, CuDNNGRU, CuDNNLSTM, BatchNormalization
from tensorflow.keras.layers import Embedding
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.optimizers import Adam

def build_model(input_dim,
                lr = 1e-3,
                lr_d = 1e-10, units = 64, spatial_dr = 0.3, kernel_size1=3, kernel_size2=2,
                     dense_units=32, dr=0.1, conv_size=32
                     ):

    # inp = Input(shape=(max_len,))
    # 直接load训练好的为embedding_matrix 没在这儿训练
    # x = Embedding(19479, embed_size, weights=[embedding_matrix], trainable=False)(inp)
    inp = Input(shape=(1, input_dim))

    # x = Embedding(
    #     input_dim=char_dim,
    #     output_dim=embedding_dim,
    #     input_length=input_dim
    # )(inp)
    # gpu = tf.test.is_gpu_available()

    # 丢掉整个dim, 普通的丢掉几个元素而已
    # ? 下一步如何衔接dim?
    x1 = SpatialDropout1D(spatial_dr)(inp)

    # bidirection wrapper in rnn
    # CuDNN... 英伟达出品,只能在GPU上跑
    # if gpu:
    #     x_gru = Bidirectional(CuDNNGRU(units, return_sequences=True))(x1)
    # else:
    x_gru = Bidirectional(GRU(units, return_sequences=True))(x1)
    x1 = Conv1D(conv_size, kernel_size=kernel_size1, padding='valid', kernel_initializer='he_uniform')(x_gru)
    # global average pooling operation for temporal data
    avg_pool1_gru = GlobalAveragePooling1D()(x1)
    max_pool1_gru = GlobalMaxPooling1D()(x1)

    x3 = Conv1D(conv_size, kernel_size=kernel_size2, padding='valid', kernel_initializer='he_uniform')(x_gru)
    avg_pool3_gru = GlobalAveragePooling1D()(x3)
    max_pool3_gru = GlobalMaxPooling1D()(x3)

    # if gpu:
    #     x_lstm = Bidirectional(CuDNNLSTM(units, return_sequences=True))(x1)
    # else:
    x_lstm = Bidirectional(LSTM(units, return_sequences=True))(x1)
    x1 = Conv1D(conv_size, kernel_size=kernel_size1, padding='valid', kernel_initializer='he_uniform')(x_lstm)
    avg_pool1_lstm = GlobalAveragePooling1D()(x1)
    max_pool1_lstm = GlobalMaxPooling1D()(x1)

    x3 = Conv1D(conv_size, kernel_size=kernel_size2, padding='valid', kernel_initializer='he_uniform')(x_lstm)
    avg_pool3_lstm = GlobalAveragePooling1D()(x3)
    max_pool3_lstm = GlobalMaxPooling1D()(x3)

    x = concatenate([avg_pool1_gru, max_pool1_gru, avg_pool3_gru, max_pool3_gru,
                     avg_pool1_lstm, max_pool1_lstm, avg_pool3_lstm, max_pool3_lstm])
    x = BatchNormalization()(x)
    x = Dropout(dr)(Dense(dense_units, activation='relu')(x))
    x = BatchNormalization()(x)
    x = Dropout(dr)(Dense(int(dense_units / 2), activation='relu')(x))

    x = Dense(1, activation="sigmoid")(x)

    model = Model(inputs=inp, outputs=x)
    metrics = [
        tf.keras.metrics.TruePositives(name='tp'),
        tf.keras.metrics.FalsePositives(name='fp'),
        tf.keras.metrics.TrueNegatives(name='tn'),
        tf.keras.metrics.FalseNegatives(name='fn'),
        tf.keras.metrics.BinaryAccuracy(name='accuracy'),
        tf.keras.metrics.Precision(name='precision'),
        tf.keras.metrics.Recall(name='recall'),
        # tf.keras.metrics.AUC(name='auc'),
    ]
    optimizer = tf.train.AdamOptimizer(learning_rate=lr)
    model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=metrics)
    return model


from typing import List

def canPlaceFlowers(flowerBed: List[int], n: int) -> bool:
    """Return true iff 'n' new flowers can be added to the 'flowerBed'."""

    length = len(flowerBed)

    # Memoise results from 'maximumNewFlowers' function.
    cache = {}

    def maximumNewFlowers(index: int = 0):
        """Return maximum number of new flowers that can be placed in the
        'flowerBed', starting at the specified 'index'."""

        if index in cache:
            return cache[index]

        if index >= length:
            # Out of bounds.
            cache[index] = 0

        elif index + 1 == length:
            # Place flower here if current position is empty.
            cache[index] = 1 - flowerBed[index]

        elif flowerBed[index] == 1:
            # Current position is not empty.
            cache[index] = maximumNewFlowers(index + 2)

        elif flowerBed[index + 1] == 0:
            # Next position is empty -- place flower here.
            cache[index] = 1 + maximumNewFlowers(index + 2)

        else:
            # Next position is not empty.
            cache[index] = maximumNewFlowers(index + 1)

        return cache[index]

    return n <= maximumNewFlowers()


import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/'
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):

        quotes = response.css('div.quote')
        for qt in quotes:
            data = {
                'quote' : qt.css('span.text::text').extract_first(),
                'author' : qt.css('small.author::text').extract_first(),
                'tags' : qt.css('a.tag::text').extract()
            }
            yield data

        nxt_page = response.css("li.next > a::attr(href)").extract_first()
        if(nxt_page):
            url = response.urljoin(nxt_page)
            yield scrapy.Request(url = url , callback = self.parse)


import argparse
import torch
from pathlib import Path
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
import util.utils as utils
from albumentations import (HorizontalFlip,
                            VerticalFlip,
                            Normalize,
                            Compose)
from util.validation import validation
from util.models import TDSNet
from util.loss import LossHybrid
from util.dataset import RoboticsDataset
from util.train_val_split import get_split
from util.config import *

def make_loader(file_names, shuffle=False, transform=None, batch_size=1, works = 4):
    return DataLoader(
        dataset=RoboticsDataset(file_names, transform=transform),
        shuffle=shuffle,
        num_workers=works,
        batch_size=batch_size,
        pin_memory=torch.cuda.is_available()
    )

def train_transform(p=1):
    return Compose([
        VerticalFlip(p=0.5),
        HorizontalFlip(p=0.5),
        Normalize(p=1)
    ], p=p)

def val_transform(p=1):
    return Compose([
        Normalize(p=1)
    ], p=p)

def main():

    """
    Training script which could obtain trained model

    Args:
        some parameters saved in ./util/config.py
        alpha: weight of class task
        beta: weight of sync task
        gama: weight of scene task
        device-ids: the device id in computer
        fold: the validation set id
        root: model saved path
        batch-size: batch size
        n-epochs: maximum epochs
        lr: learning rate
        workers: cpu kernal numbers
        model: model which utilized
        num_classes: class/segment task numbers; num_scenes class numbers saved in ./util/config.py

    Returns:
        model saved in root path.
    Raises:
        None
    """

    parser = argparse.ArgumentParser()
    arg = parser.add_argument
    arg('--alpha', default=0.2, type=float)
    arg('--beta', default=0.4, type=float)
    arg('--gama', default=0.2, type=float)
    arg('--device-ids', type=str, default='0', help='For example 0,1 to run on two GPUs')
    arg('--fold', type=int, help='fold', default=0)
    arg('--root', default='runs/debug', help='checkpoint root')
    arg('--batch-size', type=int, default=1)
    arg('--n-epochs', type=int, default=100)
    arg('--lr', type=float, default=0.0001)
    arg('--workers', type=int, default=6)
    arg('--model', type=str, default='TDSNet')
    args = parser.parse_args()

    root = Path(args.root)
    root.mkdir(exist_ok=True, parents=True)

    if args.model == 'TDSNet':
        model = TDSNet(num_classes = num_classes, num_scenes = num_scenes, pretrained=True)
    if torch.cuda.is_available():
        if args.device_ids:
            device_ids = list(map(int, args.device_ids.split(',')))
        else:
            device_ids = None
        model = nn.DataParallel(model, device_ids=device_ids).cuda()
    cudnn.benchmark = True

    loss = LossHybrid(num_classes=num_classes)

    train_file_names, val_file_names = get_split(args.fold)
    print('num train = {}, num_val = {}'.format(len(train_file_names), len(val_file_names)))
    train_loader = make_loader(train_file_names, shuffle=True, transform=train_transform(p=1),
                               batch_size=args.batch_size)
    valid_loader = make_loader(val_file_names, transform=val_transform(p=1),
                               batch_size=args.batch_size)

    valid = validation

    utils.train(
        init_optimizer=lambda lr: Adam(model.parameters(), lr=lr),
        args=args,
        model=model,
        criterion=loss,
        train_loader=train_loader,
        valid_loader=valid_loader,
        validation=valid,
        fold=args.fold,
        num_classes=num_classes,
        weights = [args.alpha, args.beta, args.gama]
    )

if __name__ == '__main__':
    main()


from fpdf import FPDF

def main():
    name = input("Name")
    pdf = FPDF()
    pdf.add_page()
    pdf.image("shirtificate.png")
    pdf.set_font("helvetica", "B", 16)
    pdf.cell(40, 10, name, align="C")
    pdf.output("shirtificate.pdf")

if __name__ == "__main__":
    main()


from import_export.resources import ModelResource
from import_export.fields import Field
from nakhll_market.models import Product

class ProductResource(ModelResource):
    id = Field(
        attribute='ID',
        column_name='id',
        readonly=True
    )
    title = Field(
        attribute='title',
        column_name='عنوان',
        readonly=True
    )
    barcode = Field(
        attribute='barcode',
        column_name='بارکد',
        readonly=True
    )
    price = Field(
        attribute='price',
        column_name='قیمت با تخفیف',
        readonly=True
    )
    old_price = Field(
        attribute='old_price',
        column_name='قیمت بدون تخفیف',
        readonly=True
    )
    inventory = Field(
        attribute='inventory',
        column_name='موجودی',
        readonly=True
    )
    net_weight = Field(
        attribute='net_weight',
        column_name='وزن خالص',
        readonly=True
    )
    weight_with_packing = Field(
        attribute='weight_with_packing',
        column_name='وزن با بسته بندی',
        readonly=True
    )
    category_id = Field(
        attribute='category_id',
        column_name='دسته بندی',
        readonly=True
    )
    publish = Field(
        attribute='publish',
        column_name='وضعیت انتشار',
        readonly=True
    )

    class Meta:
        model = Product
        fields = [
            'title',
            'barcode',
            'price',
            'old_price',
            'inventory',
            'net_weight',
            'weight_with_packing',
            'category_id',
            'publish']


# 18. Дан одномерный массив числовых значений, насчитывающий N элементов.
# Исключить из массива элементы, принадлежащие промежутку [В; С].
import random

m = int(input("Введите колличество элементов массива:\n"))
b = int(input("Введите число B:\n"))
c = int(input("Введите число C:\n"))

# Создание списка со случайными значениями.
num_list = list()
for a in range(m):
    num_list.append(random.randint(0, 5))

print(num_list)
new_list = num_list[:b]
new_list += num_list[c:]
print(new_list)