#!/usr/bin/env python3

# -------
# imports
# -------

import os
import sys

# ---------
# user_read
# ---------

def user_read (mcache, direc) :
    """
    reads all files in the directory specified; expected all files to be plain text
    direc the directory to be read

    """
    assert os.path.isdir(direc)
    assert type(mcache) == list

    ucache = {}

    trat = 0
    tcnt = 0

    # iterate through every files in the directory
    for f in os.listdir(direc):
        # open each file in read only mode
        mrating = open(direc+"/"+f, 'r')
        # convert the first line to int to represent to movie ID
        mid = int(mrating.readline().replace(':',''))

        # iterate through all lines in the file
        for line in mrating:
            lst = line.split(',')

            uid = int(lst[0])
            rating = int(lst[1])

            mcache[mid-1][0]+=rating
            mcache[mid-1][1]+=1

            if not uid in ucache:
                ucache[uid] = [0.0,0.0]

            ucache[uid][0]+=rating
            ucache[uid][1]+=1

            trat += rating
            tcnt += 1

    assert len(ucache) <= 480189
    return (ucache, trat/tcnt)

# ----------
# movie_read
# ----------

def movie_read (titles) :
    """
    reads all movie IDs and their corresponding year into the movie dictionary
    also setup each entry in the movie dictionary
    titles the file that stored the information about movie titles
    """
    mcache = []
    for line in titles:
        lst = line.split(',')
        mcache.append([0.0,0.0])
        assert int(lst[0]) == len(mcache)
    return mcache

# ----------
# cal_offset
# ----------

def cal_offset (cache, avg):
    if type(cache) == dict:
        for i in cache:
            cache[i] = cache[i][0]/cache[i][1] - avg

    elif type(cache) == list:
        for i in range(len(cache)):
            cache[i] = cache[i][0]/cache[i][1] - avg

    else:
        print("cache input not a list or dict")

# ------------
# output_cache
# ------------

def output_cache(cache, w):
    w.truncate()
    if type(cache) == dict:
        for i in cache:
            w.write(str(i)+" "+str(cache[i])+"\n")

    elif type(cache) == list:
        w.write(str(cache[len(cache)-1])+"\n")
        for i in range(len(cache)-1):
            w.write(str(cache[i])+"\n")

    else:
        print("cache input not a list or dict")

# -------------
# cache_produce
# -------------

def cache_produce () :
    """
    calls the cache construction functions and output the result to the file specified
    """

    """
    list for movie
    each entry is the sum and count of all ratings received by each movie, which will be used later to calculate the user offset
    """
    mcache = movie_read(open('/u/downing/cs/netflix/movie_titles.txt', 'r', encoding = "ISO-8859-1"))

    """
    dictionaries for user caches
    each entry contain the sum and count of all ratings given by each user, which will be used later to calculate the user offset
    mean is the average of all ratings from all movies
    """
    ucache, mean = user_read(mcache, "/u/downing/cs/netflix/training_set")

    cal_offset(mcache, mean)
    cal_offset(ucache, mean)

    mcache.append(mean)

    output_cache(ucache, open('/u/wc6892/Documents/cs373-netflix/wc6892-ucacheoff.txt', 'w'))
    output_cache(mcache, open('/u/wc6892/Documents/cs373-netflix/wc6892-mcacheoff.txt', 'w'))

# ----
# main
# ----

if __name__ == "__main__" :
    cache_produce()


import requests
import json
import LMIPy
import os

# user input needed
# enter the location of the json file containing your minimal dataset info json (no layers)
dataset_json_data_loc = '' # ex: /home/data/aqueduct_rw_api_2021-02-19/aq_floods_minimal_2021-02-19.json
# enter the location of the folder containing your layer json files
layer_json_data_loc = '' # ex: /home/data/aqueduct_rw_api_2021-02-19/layers

# read in the minimal dataset json
dataset_f = open(dataset_json_data_loc)
dataset_json = json.load(dataset_f)
# get list of json files for all the layers
layer_files = os.listdir(layer_json_data_loc)

# import your API token
API_TOKEN = os.getenv('RW_API_KEY')

def create_headers():
    return {
        'content-type': "application/json",
        'authorization': "{}".format(os.getenv('apiToken')),
    }

def clone_ds_ly_from_json(dataset_json, layer_files, token=None, dataset_pub = False, layer_pub = True):
    """
    Create a clone of a target Dataset as a new staging or prod Dataset.
    INPUT   dataset_json: minimal json of dataset info (dictionary)
            layer_files: list of layer json files (list of strings)
            token: RW API token (string)
            dataset_pub: should the dataset be published when it is created (boolean)
            layer_pub: should the layers be published when it is created (boolean)
    """
    clone_server = 'https://api.resourcewatch.org'
    if not token:
        raise ValueError(f'[token] Resource Watch API token required to clone.')
    else:
        ### update dataset
        dataset_json.pop("id", None)
        dataset_json['attributes']['published'] = dataset_pub
        dataset_fields_to_drop = ["createdAt", "updatedAt", "userId"]

        for field in dataset_fields_to_drop:
            dataset_json['attributes'].pop(field, None)

        ### clone dataset
        url = f'{clone_server}/dataset'
        headers = create_headers()
        payload = {
            'dataset': {**dataset_json['attributes']
            }}
        display(json.dumps(payload))
        r = requests.post(url, data=json.dumps(payload), headers=headers)
        if r.status_code == 200:
            clone_dataset_id = r.json()['data']['id']
            clone_dataset = LMIPy.Dataset(id_hash=clone_dataset_id, server=clone_server)
            print('Dataset created:')
            print(r.json()['data']['id'])
        else:
            print(r.status_code)

        ### clone layers
        layer_fields_to_drop = ["createdAt", "updatedAt", "userId", "dataset"]

        for i in range(len(layer_files)):
            layer_f = open(os.path.join(layer_json_data_loc, layer_files[i]))
            layer_json = json.load(layer_f)
            layer_json.pop("id", None)
            layer_json['attributes']['published'] = layer_pub
            for field in layer_fields_to_drop:
                layer_json['attributes'].pop(field, None)
            url = f'{clone_server}/dataset/{clone_dataset_id}/layer'
            print(url)
            payload = {
            'layer': {**layer_json['attributes']
            }}
            r = requests.post(url, data=json.dumps(payload), headers=headers)
            if r.status_code == 200:
                clone_layer_id = r.json()['data']['id']
                clone_layer = LMIPy.Layer(id_hash=clone_layer_id, server=clone_server)
                print('Layer created:')
                print(r.json()['data']['id'])
            else:
                print(r.status_code)

clone_ds_ly_from_json(dataset_json, layer_files, token=API_TOKEN, dataset_pub=True, layer_pub=True)

# if you accidentally make a dataset incorrectly, you can delete it by
# entering the dataset id below and running the code that follows
dataset_id = ''
r = requests.delete(f'https://api.resourcewatch.org/dataset/{dataset_id}',
                headers=create_headers())
if r.status_code==200:
    print(f'Dataset {id} has been deleted.')


import random as rd

def reSult(ac):
    yut = ["도", "개", "걸", "윷", "모", "빽도", "낙"]
    ect = ["0", "1", "null"]
    zCount = 0
    oCount = 0
    nCount = 0
    pivo = rd.randint(0, 35)
    i = 0
    while((zCount+oCount+nCount) < 4):
        if ac[i] == ect[0]:
            zCount = zCount + 1
        elif ac[i] == ect[1]:
            oCount += 1
        elif ac[i] == ect[2]:
            nCount += 1
        i = i + 1
        if nCount == 1:
            if oCount != 3:
                zCount += 1
                nCount = 0

    if pivo == 24:
        return yut[6]
    if zCount == 4:
        ops = 3
        return yut[3]
    elif zCount == 3:
        return yut[2]
    elif zCount == 2:
        return yut[1]
    elif oCount >= 3:
        if nCount == 1:
            return yut[5]
        elif zCount == 1:
            return yut[0]
        else:
            return yut[4]

def yutNol():
    y = [ ["0", "1"],["0", "1"],["0", "1"],
    ["0", "1","0", "1","0", "1","0", "1","0", "1","null"] ]
    result = list()
    y1 = list(rd.choice(y[0]))
    y2 = list(rd.choice(y[1]))
    y3 = list(rd.choice(y[2]))
    y4 = list()
    y4.append(rd.choice(y[3]))
    print("{}, {}, {}, {} ".format(y1, y2, y3, y4))
    result = y1 + y2 + y3 + y4
    cam = reSult(result)
    print(cam)
    return cam

def mainloop(tag):
    cam = ["ui"]
    while tag:
        cam = yutNol()
        if (cam == "윷") or (cam == "모"):
            print(" {}! 한번 더 돌립니다.".format(cam))
            cam = yutNol()
            if (cam == "윷") or (cam == "모"):
                print(" {}! 한번 더 돌립니다.".format(cam))
                cam = yutNol()
        if (cam == "낙"):
            print(" {}! 다음 기회에(벌레 컷)".format(cam))
        tag = 0
        return cam


import sys
sys.stdin = open('b_2660.txt', 'r')

def get_distance(y, x):
    que = [y]
    visit = [0] * N
    visit[y] = 1
    distance = 0
    while que:
        distance += 1
        for _ in range(len(que)):
            nxt = que.pop(0)
            for idx in range(N):
                if point_map[nxt][idx] == 1 and visit[idx] == 0:
                    visit[idx] = 1
                    if idx == x:
                        return distance
                    else:
                        que.append(idx)

N = int(input())
point_map = [[0]*N for _ in range(N)]
relation = []
while True:
    new_info = input()
    if new_info == '-1 -1':
        break
    else:
        a, b = map(int, new_info.split())
        a -= 1
        b -= 1
        point_map[a][b] = 1
        point_map[b][a] = 1

for y in range(N):
    for x in range(N):
        if y != x and point_map[y][x] == 0:
            dis = get_distance(y, x)
            point_map[y][x] = dis
            point_map[x][y] = dis

point_lst = [0] * N
for y in range(N):
    point_lst[y] = max(point_map[y])

res_point = min(point_lst)
res_cnt = 0
res_lst = []

for idx in range(N):
    if point_lst[idx] == res_point:
        res_lst.append(idx+1)
        res_cnt += 1

print(res_point, res_cnt)
for res in res_lst:
    print(res, end=' ')


import pandas as pd
#import json
import datetime
# this piece of code will add the mode artiact had model history into a data frame
try:
    print("no error")
except exception as err:
       print(err)
       print("Error appear in the code")

class ModelVersioning:
    def __init__(self, trained_model):
        self.trained_model = trained_model
        #self.model_name = model_name

    def Model_HyperParameters(self):
        df_param = pd.DataFrame([self.trained_model.get_params()]).T.reset_index().rename(
            columns={'index': 'Hyper_Parameter_name', 0: 'Hyper_Parameter_value'})
        return df_param
# add comment lines to change in the code
# this will add the model artifacts into the model hyper parameters
    def Model_Artifacts(self):
        df_params = self.Model_HyperParameters()
        df_params['run_time'] = datetime.datetime.now()
        df_params['model_name'] = "ML Model"
        df_params['model_type'] = "Classification"
        return df_params


from __future__ import annotations

import importlib
import os
import sys
import typing

import pytest
from _pytest.monkeypatch import MonkeyPatch
from pytest_mock import MockerFixture

from platformdirs.unix import Unix

def test_user_documents_dir(mocker: MockerFixture) -> None:
    example_path = "/home/example/ExampleDocumentsFolder"
    mock = mocker.patch("platformdirs.unix._get_user_dirs_folder")
    mock.return_value = example_path
    assert Unix().user_documents_dir == example_path

def test_user_documents_dir_env_var(mocker: MockerFixture) -> None:
    # Mock documents dir not being in user-dirs.dirs file
    mock = mocker.patch("platformdirs.unix._get_user_dirs_folder")
    mock.return_value = None

    example_path = "/home/example/ExampleDocumentsFolder"
    mocker.patch.dict(os.environ, {"XDG_DOCUMENTS_DIR": example_path})

    assert Unix().user_documents_dir == example_path

def test_user_documents_dir_default(mocker: MockerFixture) -> None:
    # Mock documents dir not being in user-dirs.dirs file
    mock = mocker.patch("platformdirs.unix._get_user_dirs_folder")
    mock.return_value = None

    # Mock no XDG_DOCUMENTS_DIR env variable being set
    mocker.patch.dict(os.environ, {"XDG_DOCUMENTS_DIR": ""})

    # Mock home directory
    mocker.patch.dict(os.environ, {"HOME": "/home/example"})
    # Mock home directory for running the test on Windows
    mocker.patch.dict(os.environ, {"USERPROFILE": "/home/example"})

    assert Unix().user_documents_dir == "/home/example/Documents"

class XDGVariable(typing.NamedTuple):
    name: str
    default_value: str

def _func_to_path(func: str) -> XDGVariable | None:
    mapping = {
        "user_data_dir": XDGVariable("XDG_DATA_HOME", "~/.local/share"),
        "site_data_dir": XDGVariable("XDG_DATA_DIRS", f"/usr/local/share{os.pathsep}/usr/share"),
        "user_config_dir": XDGVariable("XDG_CONFIG_HOME", "~/.config"),
        "site_config_dir": XDGVariable("XDG_CONFIG_DIRS", "/etc/xdg"),
        "user_cache_dir": XDGVariable("XDG_CACHE_HOME", "~/.cache"),
        "user_state_dir": XDGVariable("XDG_STATE_HOME", "~/.local/state"),
        "user_log_dir": XDGVariable("XDG_CACHE_HOME", "~/.cache"),
        "user_runtime_dir": XDGVariable("XDG_RUNTIME_DIR", "/run/user/1234"),
    }
    return mapping.get(func)

@pytest.fixture()
def dirs_instance() -> Unix:
    return Unix(multipath=True, opinion=False)

@pytest.fixture()
def _getuid(mocker: MockerFixture) -> None:
    mocker.patch("platformdirs.unix.getuid", return_value=1234)

@pytest.mark.usefixtures("_getuid")
def test_xdg_variable_not_set(monkeypatch: MonkeyPatch, dirs_instance: Unix, func: str) -> None:
    xdg_variable = _func_to_path(func)
    if xdg_variable is None:
        return

    monkeypatch.delenv(xdg_variable.name, raising=False)
    result = getattr(dirs_instance, func)
    assert result == os.path.expanduser(xdg_variable.default_value)

@pytest.mark.usefixtures("_getuid")
def test_xdg_variable_empty_value(monkeypatch: MonkeyPatch, dirs_instance: Unix, func: str) -> None:
    xdg_variable = _func_to_path(func)
    if xdg_variable is None:
        return

    monkeypatch.setenv(xdg_variable.name, "")
    result = getattr(dirs_instance, func)
    assert result == os.path.expanduser(xdg_variable.default_value)

@pytest.mark.usefixtures("_getuid")
def test_xdg_variable_custom_value(monkeypatch: MonkeyPatch, dirs_instance: Unix, func: str) -> None:
    xdg_variable = _func_to_path(func)
    if xdg_variable is None:
        return

    monkeypatch.setenv(xdg_variable.name, "/tmp/custom-dir")
    result = getattr(dirs_instance, func)
    assert result == "/tmp/custom-dir"

def test_platform_non_linux(monkeypatch: MonkeyPatch) -> None:
    from platformdirs import unix

    try:
        with monkeypatch.context() as context:
            context.setattr(sys, "platform", "magic")
            monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
            importlib.reload(unix)
        with pytest.raises(RuntimeError, match="should only be used on Linux"):
            unix.Unix().user_runtime_dir
    finally:
        importlib.reload(unix)


"""
https://leetcode.com/problems/flower-planting-with-no-adjacent/
1042. Flower Planting With No Adjacent
Easy
-----------------------
You have N gardens, labelled 1 to N.  In each garden, you want to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path,
they have different types of flowers.
Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden.
The flower types are denoted 1, 2, 3, or 4.  It is guaranteed an answer exists.

Example 1:
Input: N = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]

Example 2:
Input: N = 4, paths = [[1,2],[3,4]]
Output: [1,2,1,2]

Example 3:
Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output: [1,2,3,4]

Note:
1 <= N <= 10000
0 <= paths.size <= 20000
No garden has 4 or more paths coming into or leaving it.
It is guaranteed an answer exists.
"""
import collections

class Solution:
    def gardenNoAdj(self, N, paths):
        return self.gardenNoAdj_1(N, paths)

    def gardenNoAdj_1(self, N, paths):
        """
        采用adjacent list保存图数据
        1.从1~N依次遍历每个garden的adjacent list
        2.对于garden i,先排除相邻节点已经种植的flower type,然后选择未被排除最小的type为i的flower type
        -------------
        验证通过,性能不错
        Runtime: 448 ms, faster than 91.40% of Python3 online submissions for Flower Planting With No Adjacent.
        Memory Usage: 19.4 MB, less than 100.00% of Python3 online submissions for Flower Planting With No Adjacent.
        :param N:
        :param paths:
        :return:
        """
        if not N or N <= 0:
            return []

        ret = [0 for i in range(N + 1)]
        adjacent_list = collections.defaultdict(list)
        for p in paths:
            adjacent_list[p[0]].append(p[1])
            adjacent_list[p[1]].append(p[0])

        for i in range(1, N + 1):
            neighbors = adjacent_list[i]
            if neighbors:
                types = [0, 1, 2, 3, 4]
                for n in neighbors:
                    if ret[n] > 0:
                        types[ret[n]] = -1
                for t in types:
                    if t > 0:
                        ret[i] = t
                        break
            else:
                ret[i] = 1

        return ret[1:]

def main():
    N = 3
    paths = [[1, 2], [2, 3], [3, 1]]
    ret = Solution().gardenNoAdj(N, paths)
    print(ret)
    print(ret == [1, 2, 3])
    print("--------------------")

    N = 4
    paths = [[1, 2], [3, 4]]
    ret = Solution().gardenNoAdj(N, paths)
    print(ret)
    print(ret == [1, 2, 1, 2])
    print("--------------------")

    N = 4
    paths = [[1, 2], [2, 3], [3, 4], [4, 1], [1, 3], [2, 4]]
    ret = Solution().gardenNoAdj(N, paths)
    print(ret)
    print(ret == [1, 2, 3, 4])
    print("--------------------")

if __name__ == "__main__":
    main()


from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, IMAGES
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=False, nullable=False)
    email = db.Column(db.String(120), unique=False, nullable=False)
    pic_name = db.Column(db.String(120), unique=True, nullable=False)

photos = UploadSet('photos', IMAGES)

app.config['UPLOADED_PHOTOS_DEST'] = 'static/img'
configure_uploads(app, photos)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        upload = User(username='username',email='example@domain.com',pic_name='static/img/'+filename)
        db.session.add(upload)
        db.session.commit()
        print(filename)
    return render_template('upload.html')

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


# coding: utf-8

# # Get dimension of dataset
#
# Get dimension of feature space for input into
# This information is used by [3_tybalt_2layer_model_generator.py](3_tybalt_2layer_model_generator.ipynb) to train autoencoder

# In[ ]:

import os
import pandas as pd
import pickle

randomState = 123

# In[2]:

get_ipython().run_cell_magic('time', '', '# Load dataset\nsubsample_dataset = "subsample_13K_validation_0.2"\ntrain_file =  "/home/alexandra/Documents/Data/LINCS_tuning/"+subsample_dataset+"/train_model_input.txt.xz"\nval_file =  "/home/alexandra/Documents/Data/LINCS_tuning/"+subsample_dataset+"/validation_model_input.txt.xz"')

# In[3]:

# Read data
rnaseq_train = pd.read_table(train_file, index_col=0, header=0, compression = 'xz')
rnaseq_val = pd.read_table(val_file, index_col=0, header=0, compression = 'xz')

# In[4]:

# Output files
dim_train_file = os.path.join(
    os.path.dirname(
        os.getcwd()), "metadata", subsample_dataset, "train_tune_dim.pickle")
dim_val_file = os.path.join(
    os.path.dirname(
        os.getcwd()), "metadata", subsample_dataset, "validation_tune_dim.pickle")

# In[5]:

rnaseq_train.head()

# In[6]:

rnaseq_val.head()

# In[7]:

# Save shape of input dataset
dim_train= rnaseq_train.shape
dim_val= rnaseq_val.shape

with open(dim_train_file, 'wb') as f:
    pickle.dump(dim_train, f)

del rnaseq_train

with open(dim_val_file, 'wb') as f:
    pickle.dump(dim_val, f)

del rnaseq_val


#Klasa przechwouje wszystkie sloty i sygnały w aplikacji

#Moduły wbudowane
import os
from PyQt5.QtWidgets import *
from PyQt5 import *
import sys
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtCore import QThread

#Moduły aplikacji
from forms import blank_window

#klasa odpowiadająca za główny ekran, czyli za forms/main_window.py
#pierwszy ekran po uruchomieniu aplikacji!
from forms import main_window
class MainWindow(QMainWindow, main_window.Ui_MainWindow):
#ten konstruktor nadpisuje konstruktor z klasy bazowej
#dlatego wywołujemy konstruktor z klasy bazowej z poziomu konstruktora klasy dziedziczącej
	def __init__(self):
		super().__init__()
		#wywołuję główną metodę piku formularza
		self.setupUi(self) # metoda zdefiniowana w pliku *.UI zamienionym na *.py, czyli w formularzu
		#przypisuje konkretną funkcję(slot) do przycisku i sygnał
		self.MP3_Player.clicked.connect(lambda: self.showMP3PlayerForm())
		self.FM_Radio.clicked.connect(lambda: self.showFMForm())
		self.Navigation.clicked.connect(lambda: self.startNavigation())
		self.Camcorder.clicked.connect(lambda: self.showCamcorderForm())
		self.Camera.clicked.connect(lambda: self.showCameraForm())
		self.Multimedia.clicked.connect(lambda: self.showMultimediaForm())
		self.Close.clicked.connect(lambda: self.showCloseForm())
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def showMP3PlayerForm(self):
		#tworzę obiekt klasy MusicWindow
		self.dialog = MusicWindow()
		#wyświetlam formualrz (pierwszy!) odtwarzacza muzyki
		#analogicznie działają funkcję niżej
		self.dialog.show()
	def showFMForm(self):
		self.dialog = FMWindow()
		self.dialog.show()
	def startNavigation(self):
		#uruchamiam nawigację navit
		os.system('navit')
	def showCamcorderForm(self):
		self.dialog = CamcorderWindow()
		self.dialog.show()
	def showCameraForm(self):
		self.dialog = CameraWindow()
		self.dialog.show()
	def showMultimediaForm(self):
		self.dialog = MultimediaWindow()
		self.dialog.show()
	def showCloseForm(self):
		self.dialog = CloseWindow()
		self.dialog.show()

#Klasa odpowiadająca za MP3PlayerWindow czyli za forms/MP3_player_window.py
from forms import MP3_player_window
class MusicWindow(QMainWindow, MP3_player_window.Ui_MP3PlayerWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Pendrive.clicked.connect(lambda: self.playPendrive())
		self.Memory_Card.clicked.connect(lambda: self.playMemoryCard())
		self.Playlist.clicked.connect(lambda: self.showPlaylist())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def playPendrive(self):
		os.system('sudo pkill -9 aplay;sudo pkill -9 rtl_fm;vlc /media/pi/307E-6572 --fullscreen')
	def playMemoryCard(self):
		os.system('sudo pkill -9 aplay;sudo pkill -9 rtl_fm;vlc --no-media-library /home/pi/Music')
	def showPlaylist(self):
		self.dialog = PlaylistsWindow()
		self.dialog.show()

#Klasa odpowiadająca za FMWindow, czyli za forms/FM_window.py
#Wybranie przycisku "Wybierz stację" wywołuje klasę SelectFMWindow
#która najpierw rysuje pusty formularz
#potem rysuje na nim przyciski do uruchamiania stacji radiowych
#przyciski za pomocą klasy ListStations
from forms import FM_window
FMWindowList = 0
class FMWindow(QMainWindow, FM_window.Ui_FMWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self) # gets defined in the UI file

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Select_Station.clicked.connect(lambda: self.showSelectStationForm())
		self.Favourited_Stations.clicked.connect(lambda: self.showSelectFavouritedStationForm())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		#otwieram plik ze stylami CSS
		#które ustalają wygląd elementów, analogicznie jak dla HTML
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def showSelectStationForm(self):
		global FMWindowList
		FMWindowList = SelectFMWindow('normal')
		FMWindowList.show()
	def showSelectFavouritedStationForm(self):
		#zmienna o zagięgu globalnym
		global FMWindowList
		FMWindowList = SelectFMWindow('favourited')
		FMWindowList.show()

#Klasa odpowiadająca za SelectFMWindow
#która najpierw rysuje pusty formularz
#potem rysuje na nim przyciski do uruchamiania stacji radiowych
#za pomocą klasy ListStations
#kind argument przekazany do rozróżnienia widoku na normalny i na widok ulubionych
#później ten argument będzie przekazany do klasy ListStations
#i na tej podstawie zostanie skonstruowane odpowiednie zapytanie do bazy
#zrobić najlepiej bez globalnej zmiennej offset!
from classes.ListStations import ListStations
#globalna zmienna
#offset dla rekordów z bazy
offset=0
#zmienna globala przechowuje nazwę aktualnie odtwarzanej stacji
StationPlayed=0
class SelectFMWindow(QMainWindow, blank_window.Ui_BlankWindow):
#w tym konstruktorze trzeba wywołać instancję klasy ListStations
#i przekazać do niej argument kind, aby wiedziała
#czy ma generować widok normalny czy widok ulubionych
	def __init__(self,kind):
		super(self.__class__, self).__init__()
		self.setupUi(self)
		#tworzę obiekt, który zgodnie z argumentem kind stworzy odpowiedni widok
		self.setStyleSheet(open("resources/style.qss", "r").read())

		#dodaję napis Wszystkie stacje lub Ulubione stację
		if(kind=='normal'):
			self.test=QtWidgets.QLabel("sd",self)
			#parametry: x, y, width, height
			self.test.setGeometry(QtCore.QRect(80, 100, 181, 31))
			_translate = QtCore.QCoreApplication.translate
			self.test.setText(_translate("MainWindow", "
Wszystkie stacje:

"))
			#wyświetlam etykietę
			self.test.show()
		else:
			self.test=QtWidgets.QLabel("sd",self)
			self.test.setGeometry(QtCore.QRect(80, 100, 181, 31))
			_translate = QtCore.QCoreApplication.translate
			self.test.setText(_translate("MainWindow", "
Ulubione stacje:

"))
			self.test.show()

		self.ListStationsObject=ListStations(kind)

		#standardowe rysowanie przycisków
		#rysuje albo normalny widok albo widok ulubionych
		self.drawStationsButtons(kind,offset)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

	#funkcję(sloty) do obsługi przycisków
	def playStation(self,sender,kind):
		global StationPlayed
		#pobieram z bazy częstotliwość stacja o danej nazwie (nazwa zawiera się w sender)
		Frequency=self.ListStationsObject.getStationFrequency(sender)
		FMPlayString="sudo pkill arecord;sudo pkill -9 aplay;sudo pkill -9 rtl_fm;sudo rtl_fm -f "+str(Frequency)+"e6 -s 200000 -r 48000 | aplay -r 48000 -f S16_LE &"
		#jeśli będzie otwierana ta sama stacja to nie zostanie ona ponownie uruchomiona
		#oraz nie zostanie zatrzmane nagrywanie
		#będzie działać w tle
		if(StationPlayed!=sender):
			os.system(FMPlayString)
			#zwiększam liczbę odtworzeń
			#stację wyświetlane są od najczęściej używanych
			CounterPlayed=self.ListStationsObject.increaseStationPlayed(sender)
		#obiekt klasy, która wyświetla końcowy formularz odtwarzania stacji
		#tj. ten z przyciskami: Dodaj do ulubionych/usuń z ulubionych
		#normalne/ulubione
		#nagrywaj/zatrzymaj nagrywanie
		self.dialog = RadioPlayWindow(sender,kind)
		#wyświetlam ten formularz
		self.dialog.show()
		#przypisuje aktualnie odtwarzaną stację do zmiennej globalnej
		StationPlayed=sender

	def showPreviousStations(self,kind,offset):
		#czyszczę poprzednie przyciski do stacji
		#czyszczę przyciski nawigacji (dalej, wstecz)
		self.cleanStationsButtons(kind)
		#rysuję przyciski do poprzednich stacji
		#rysuję przyciski nawigacji
		self.drawStationsButtons(kind,offset=offset-4)
	def showNextStations(self,kind,offset):
		#analogicznie jak w funkcji wyżej
		self.cleanStationsButtons(kind)
		self.drawStationsButtons(kind,offset=offset+4)
		#funkcja, która rysuję przyciski do stacji
		#oraz rysuję przyciski nawigacji
	def drawStationsButtons(self,kind,offset):
		#tworzę listę ze stacjami
		StationsList=self.ListStationsObject.getStationName(kind,offset)
		#rysuje przyciski ze stacjami
		offset_x=84
		self.i=0
		self.StationsListLength=len(StationsList)
		self.StationsListButtons=[]
		self.StationsListLabels=[]

		#tworzę przyciski dopóki są rekordy z bazy
		while self.StationsListLength>0:
			self.StationsListButtons.append(QPushButton(self))
			#parametry: x, y, width, height
			self.StationsListButtons[self.i].setGeometry(QtCore.QRect(offset_x, 150, 150, 150))
			#wygląd przycisku uruchamiającego daną stację
			self.StationsListButtons[self.i].setStyleSheet("QPushButton{background:#26d8fc url(:/images/radio.png)}")
			#ustalam nazwę obiektu (czyli nazwę konkretnego przycisku)
			#ta nazwa będzie później wykorzystana w celu jednoznacznej identyfikacji
			#który konkretny przycisk wcisnął użytkownik
			#ta informacją posłuży do uruchomienia właściwej stacji
			self.StationsListButtons[self.i].setObjectName(StationsList[self.i])

			#dodaje rysowanie etykiet
			#analogicznie jak etykiety wyżej
			self.StationsListLabels.append(QtWidgets.QLabel("sd",self))
			self.StationsListLabels[self.i].setGeometry(QtCore.QRect(offset_x, 310, 181, 31))
			self.StationsListLabels[self.i].setObjectName(StationsList[self.i])
			_translate = QtCore.QCoreApplication.translate
			self.StationsListLabels[self.i].setText(_translate("MainWindow", "
"+StationsList[self.i]+"

"))
			self.StationsListLabels[self.i].show()

			self.StationsListButtons[self.i].show()
			offset_x=offset_x+234
			self.StationsListLength=self.StationsListLength-1
			#połączenie sygnału, czyli wciśnięcia przycisku uruchamiającego daną stację
			#ze slotem, czyli funkcją, który zostanie wykonana po wciśnięciu tego przycisku
			#do funkcji playStation() z obecnej klasy zostanie przekazana nazwa obiektu (opisałem wyżej) oraz kind czyli rodzaj stacji
			#normalna lub ulubiona
			#za nazwę obiektu odpowiada: self.sender().objectName()
			self.StationsListButtons[self.i].clicked.connect(lambda: self.playStation(self.sender().objectName(),kind))
			self.i=self.i+1

		#sprawdzam ile jest wszystkich rekordów
		self.StationsCount=self.ListStationsObject.getCountStations(kind)
		#rysuję przycisk do przodu jeśli jest więcej wyników

		if(self.StationsCount>(offset+4)):
			self.ButtonNext=QPushButton(self)
			self.ButtonNext.setGeometry(QtCore.QRect(600, 350, 150, 150))
			self.ButtonNext.setStyleSheet("QPushButton{background:#168c24 url(:/images/forward.png)}")
			#dodaje rysowanie etykiet
			self.LabelForward=QtWidgets.QLabel("sd",self)
			self.LabelForward.setGeometry(QtCore.QRect(600, 510, 181, 31))
			_translate = QtCore.QCoreApplication.translate
			self.LabelForward.setText(_translate("MainWindow", "
Następne

"))
			self.LabelForward.show()

			self.ButtonNext.show()
			self.ButtonNext.clicked.connect(lambda: self.showNextStations(kind,offset))
		else:
			#wykorzystanie exceptions (wyjątków)
			try:
				self.ButtonNext #sprawdza czy istnieje przycisk "Dalej"
			except:
				pass #jeśli nie ma to zostanie wykonana ta linijka, który właściwie nic nie robi
			else:
				#jeśli istnieję to ukryję przycisk do przodu oraz jego etykietę
				self.ButtonNext.hide()
				self.LabelForward.hide()

		#rysuję przycisk wstecz jeśli jest inna strona niż pierwsza
		#czyli w praktycę jeśli offset jest rózny od zera
		if(offset!=0):
			self.ButtonPrev=QPushButton(self)
			self.ButtonPrev.setGeometry(QtCore.QRect(400, 350, 150, 150))
			self.ButtonPrev.setStyleSheet("QPushButton{background:#168c24 url(:/images/backward.png)}")
			self.ButtonPrev.show()
			self.ButtonPrev.clicked.connect(lambda: self.showPreviousStations(kind,offset))

			#dodaje rysowanie etykiet
			self.LabelBackward=QtWidgets.QLabel("sd",self)
			self.LabelBackward.setGeometry(QtCore.QRect(400, 510, 181, 31))
			_translate = QtCore.QCoreApplication.translate
			self.LabelBackward.setText(_translate("MainWindow", "
Poprzednie

"))
			self.LabelBackward.show()
		else:
			try:
				self.ButtonPrev
			except:
				pass
			else:
				self.ButtonPrev.hide()
				self.LabelBackward.hide()

	#metoda czyszcząca wcześniej wyświetlone stacje
	def cleanStationsButtons(self,kind):
		#czyszczę obecną listę przycisków
		for i in range(len(self.StationsListButtons)):
			self.StationsListButtons[i].hide()
		#czyszczę obecną listę etykiet
		for i in range(len(self.StationsListLabels)):
			self.StationsListLabels[i].hide()
		#czyszczę przyciski nawigacji:
		try:
			self.ButtonPrev
		except:
			pass
		else:
			self.ButtonPrev.hide()
			self.LabelBackward.hide()
		try:
			self.ButtonNext
		except:
			pass
		else:
			self.ButtonNext.hide()
			self.LabelForward.hide()
	#funkcja zamyka okno z listą stacji (z przyciskami do danych stacji)
	def closeFMListForm():
			global FMWindowList
			FMWindowList.close()

#Klasa odpowiadająca za RadioPlayWindow, czyli za forms/radio_play_window.py
#Wyświetla widok odtwarzania konkretnej stacji radiowej
#nagrywanie stacji działa póki co tylko na PC
#nie działa na raspberry
from forms import radio_play_window
#moduł do obsługi czasu
import datetime

from subprocess import check_output
FMName=0
class RadioPlayWindow(QMainWindow, radio_play_window.Ui_RadioPlayWindow):
	def __init__(self,sender,kind):
		super(self.__class__, self).__init__()
		self.setupUi(self)
		#globalna zmienna nazwa stacji, która jest odtwarzana
		global FMName
		FMName=sender
		#wypisuję nazwę stacji
		self.RadioName=QtWidgets.QLabel("sd",self)
		self.RadioName.setGeometry(QtCore.QRect(387, 280, 181, 31))
		_translate = QtCore.QCoreApplication.translate
		self.RadioName.setText(_translate("MainWindow", "
"+sender+"

"))
		self.RadioName.show()

		#obiekt do operacji na bazie danych
		self.ListStationsObject=ListStations(kind)

		#sprawdzam czy nagrywanie jest już aktywne
		#nagrywanie dla konkretnej stacji
		self.PIDarecord=self.get_pid("arecord")
		if(isinstance(self.PIDarecord, int) and FMName==StationPlayed):
			#Rysuję przycisk stop nagrywania
			self.StopButton=self.drawControlFMButton("Stop nagrywania",627,350,"#fe022c","stop.png")
			self.StopButton.show()
			#dodanie slotu
			self.StopButton.clicked.connect(lambda: self.useControlFMButton(self.sender().objectName()))
			#dodaje rysowanie etykiety
			self.StopLabel=self.drawControlButtonLabel(627,510,"Zatrzymaj nagrywanie")
			self.StopLabel.show()
		else:
			#Rysuję przycisk start nagrywania
			self.RecordButton=self.drawControlFMButton("Nagrywaj",627,350,"#016285","record.png")
			self.RecordButton.show()
			#dodanie slotu
			self.RecordButton.clicked.connect(lambda: self.useControlFMButton(self.sender().objectName()))
			#dodaje rysowanie etykiety
			self.RecordLabel=self.drawControlButtonLabel(627,510,"Nagrywaj")
			self.RecordLabel.show()

		#najpierw muszę sprawdzić stacja jest w ulubionych
		#trzeba wysłać zapytanie do bazy i sprawdzić, czy jest w ulubionych
		self.isFavourited=self.ListStationsObject.isStationFavourited(FMName)
		if(self.isFavourited==0):
			#Rysuję przycisk Ulubione
			self.FavouritedButton=self.drawControlFMButton("Ulubione",247,350,"#8214d0","favourited.png")
			self.FavouritedButton.show()
			#Dodanie slotu
			self.FavouritedButton.clicked.connect(lambda: self.useControlFMButton(self.sender().objectName()))
			#Etykieta
			self.FavouritedLabel=self.drawControlButtonLabel(247,510,"Ulubione")
			self.FavouritedLabel.show()
			#Rysuję przycisk usuń/dodaj do ulubionych
			self.AddtoFavouritedButton=self.drawControlFMButton("Dodaj",437,350,"#13de00","add.png")
			self.AddtoFavouritedButton.show()
			#dodaje rysowanie etykiety
			self.AddtoFavouritedLabel=self.drawControlButtonLabel(437,510,"Dodaj do ulubionych")
			self.AddtoFavouritedLabel.show()
		else:
			#Rysuję przycisk Normalne
			self.NormalButton=self.drawControlFMButton("Normalne",247,350,"#26d8fc","radio.png")
			#Dodanie slotu
			self.NormalButton.clicked.connect(lambda: self.useControlFMButton(self.sender().objectName()))
			#dodaje rysowanie etykiety
			self.NormalLabel=self.drawControlButtonLabel(247,510,"Normalne")
			self.NormalLabel.show()
			#usuń z ulubionych
			self.DeleteFromFavouritedButton=self.drawControlFMButton("Usun",437,350,"#fe022c","delete.png")
			self.DeleteFromFavouritedButton.show()
			#Dodanie slotu
			self.DeleteFromFavouritedButton.clicked.connect(lambda: self.useControlFMButton(self.sender().objectName()))
			#dodaje rysowanie etykiety
			self.DeleteFromFavouritedLabel=self.drawControlButtonLabel(437,510,"Usuń z ulubionych")
			self.DeleteFromFavouritedLabel.show()
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#definicja własnego sygnału
	#wcześniej korzystałem z wbudowanych sygnałów
	#np. z kliknięcia przycisku
	trigger = pyqtSignal()
	#trigger został specjalnie stworzony do zamknęcia okna listy stacji

	#funkcję(sloty) do obsługi przycisków
	#obsługa przycisków do przechodzenia z widoku odtwarzania konkretnej np. ulubionej stacji
	#do widoku listy stacji normalnych (czyli wszystkich stacji)
	def useControlFMButton(self,sender):
		global FMWindowList
		#ta linijka łączy sygnał ze slotem closeFMListForm() z klasy SelectFMWindow
		self.trigger.connect(lambda: SelectFMWindow.closeFMListForm())
		if(sender=="Ulubione"):
				#emituje sygnał z obecnej klasy do klasy SelectFMWindow (opisane wyżej)
				#powyższy slot ma zadanie zamknąć okno z listą stacji
				#w tym przypasku zamknie listę wszystkich stacji
				self.trigger.emit()
				#zamykam okno odtwarzania danej stacji normalnej
				self.close()
				#otwieram okno z listą stacji ulubionych
				FMWindowList = SelectFMWindow('favourited')
				#wyświetlam to okno
				FMWindowList.show()
		if(sender=="Normalne"):
				#analogicznie jak wyżej
				self.trigger.emit()
				self.close()
				FMWindowList = SelectFMWindow('normal')
				FMWindowList.show()
		#dodawanie danej stacji do ulubionych
		if(sender=="Dodaj"): #jeśli wciśnięto przycisk "Dodaj do ulubionych"
				#dodaję stację do ulubionych
				#zmieniam parametr Favourited w bazie z "0" na "1"
				self.ListStationsObject.addFMStationToFavourited(FMName)
				#emituje sygnał do zamknięcia listy wszystkich stacji
				self.trigger.emit()
				#zamykam okno odtwarzania konkretnej stacji
				#w tym przpadku stacji należącej do wszystkich stacji (nie należy do ulubionych)
				self.close()
				#otwieram listę stacji ulubionych
				FMWindowList = SelectFMWindow('favourited')
				#wyświetlam okno z listą stacji ulubionych
				FMWindowList.show()
				#odtwarzam stację
				#pobieram z bazy częstotliwość danej stacji
				#a potem ja odtwarzam
				Frequency=self.ListStationsObject.getStationFrequency(FMName)
				FMPlayString="sudo pkill -9 aplay;sudo pkill -9 rtl_fm;sudo rtl_fm -f "+str(Frequency)+"e6 -s 200000 -r 48000 | aplay -r 48000 -f S16_LE &"
				#wykonuje FMPlayString w terminalu linuxa
				os.system(FMPlayString)
				#wyświetla widok odtwarzania stacji, j/w
				self.dialog = RadioPlayWindow(FMName,"favourited")
				self.dialog.show()
		#usuwanie z ulubionych
		#analogicznie jak wyżej
		if(sender=="Usun"): #jeśli wciśnięto przycisk "Usuń z ulubionych"
				self.ListStationsObject.deleteFMStationFromFavourited(FMName)
				self.trigger.emit()
				self.close()
				FMWindowList = SelectFMWindow('normal')
				FMWindowList.show()
				#odtwarzam stację
				Frequency=self.ListStationsObject.getStationFrequency(FMName)
				FMPlayString="sudo pkill -9 aplay;sudo pkill -9 rtl_fm;sudo rtl_fm -f "+str(Frequency)+"e6 -s 200000 -r 48000 | aplay -r 48000 -f S16_LE &"
				os.system(FMPlayString)
				self.dialog = RadioPlayWindow(FMName,"normal")
				self.dialog.show()
		#nagrywanie dźwięku z radia
		#działa póki co tylko na PC
		#nie działa jeszcze na raspberry
		#w nazwie pliku jest nazwa stacji
		#oraz data i godzina nagrywania
		if(sender=="Nagrywaj"):
			#zmieniam wygląd przycisku
			#nagrywam
			i = datetime.datetime.now()
			time=("%s-%s-%s-%s:%s:%s" % (i.day, i.month, i.year, i.hour, i.minute, i.second))
			RecordString="sudo pkill arecord;arecord "+'"'+FMName+"-"+str(time)+".wav\" &"
			os.system(RecordString)
			self.close()
			self.dialog = RadioPlayWindow(FMName,"normal")
			self.dialog.show()
		if(sender=="Stop nagrywania"):
			#zmieniam wygląd przycisku
			#zatrzymuje nagrywanie
			os.system('sudo pkill -9 arecord')
			self.close()
			self.dialog = RadioPlayWindow(FMName,"normal")
			self.dialog.show()

	#rysuję przycisk w widoku stacji
	#Ulubione/Normalne
	#dodaj/usuń z ulubionych
	#nagrywaj/zatrzymaj nagrywanie
	def drawControlFMButton(self,objectname,offset_x,offset_y,background,image):
		self.ControlFMButton=QPushButton(self)
		self.ControlFMButton.setGeometry(QtCore.QRect(offset_x, offset_y, 150, 150))
		self.ControlFMButton.setStyleSheet("QPushButton{background:"+str(background)+" url(:/images/"+str(image)+")}")
		self.ControlFMButton.setObjectName(objectname)
		return self.ControlFMButton

	#to samo tylko, że dla etykiet tych przycisków
	def drawControlButtonLabel(self,offset_x,offset_y,label):
		self.ControlFMButtonLabel=QtWidgets.QLabel("sd",self)
		self.ControlFMButtonLabel.setGeometry(QtCore.QRect(offset_x, offset_y, 181, 31))
		_translate = QtCore.QCoreApplication.translate
		self.ControlFMButtonLabel.setText(_translate("MainWindow", "
"+str(label)+"

"))
		return self.ControlFMButtonLabel
	#funkcję zwraca pid procesu, np pid procesu arecord
	#służy do sprawdzenia czy jakaś stacja jest już nagrywana
	def get_pid(self,name):
		try:
			return int(check_output(["pidof","-s",name]))
		except:
			pass
		else:
			pass

#Klasa odpowiadająca za ListsPlaylistWindow, czyli za forms/playlists_window.py
#tworzy pusty formularz z przyciskiem wstecz, na którym będzie wylistowana lista playlist
#oraz tworzy obiekt klasy ListPlaylist (z pliku ListPlaylists.py), która odpowiada za właściwą obsługę listowania playlist

#importuję kod klasy ListPlaylists
from classes.ListPlaylists import ListPlaylists
class PlaylistsWindow(QMainWindow, blank_window.Ui_BlankWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())
		self.PlaylistsWindowForm=ListPlaylists()
		self.PlaylistsWindowForm.show()
		self.Back.clicked.connect(lambda: self.backToMP3PlayerWindow())

	#przypisanie slotów
	#funkcja, która wraca do widoku odtwarzacza (3 przyciski: pendrive, kara pamięci, playlista)
	def backToMP3PlayerWindow(self):
		self.close()
		self.PlaylistsWindowForm.close()

#Klasa odpowiadająca za CamcorderWindow, czyli za forms/camcorder_window
#wyświetla pierwszy formularz po wciśnieciu przycisku Kamera z głównego ekranu
from forms import camcorder_window
class CamcorderWindow(QMainWindow, camcorder_window.Ui_CamcorderWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Front_Camcorder.clicked.connect(lambda: self.showFrontCamcorderForm())
		self.Back_Camcorder.clicked.connect(lambda: self.showBackCamcorderForm())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	#tworzy obiekt klasy FrontCamcorderWindow
	#która wyświetla formularz przedniej kamery (rejestrator)
	def showFrontCamcorderForm(self):
		self.dialog = FrontCamcorderWindow()
	#analogicznie formularz kamery cofania
	def showBackCamcorderForm(self):
		self.dialog = BackCamcorderWindow()

#Klasa odpowiadająca za FrontCamcorderWindow, czyli za forms/front_camcorder_window.py
#widok formularza przedniej kamery (rejestratora)
from classes.Camera import Camera
class FrontCamcorderWindow(QMainWindow, blank_window.Ui_BlankWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())
		#wyświetlam pusty formularz, na którym się wyświetli stream z kamery
		self.show()

		self.Back.clicked.connect(lambda: self.closeFrontCamcorderStream())

		#tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki
		self.VideoLabel = QLabel(self)
		#ustalam pozycję i wymiary: x, y, szerokość, wysokość
		self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540))

		#tworze nowy wątek
		self.ThreadStream = QThread()
		#tworzę obiekt, który dziedziczy po QObject
		#dzięki niemu będzie możliwość obsługi slotów i sygnałów
		self.WorkerStream = Camera("/dev/FrontCamcorder")

		#jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap
		#to funkcja streamFromFrontWebcam() go obsłuży
		#czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli
		self.WorkerStream.StreamSignal.connect(self.streamFromFrontWebcam)

		#przenoszę obiekt WorkerStream do nowego wątku
		self.WorkerStream.moveToThread(self.ThreadStream)

		#jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy
		self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit)

		#jeśli nowy wątek zostanie uruchomiony to
		#zostanie wykonana funkcja startFrontCamcorderStream() z klasy Camera
		self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream)

		#uruchamiam nowy wątek
		self.ThreadStream.start()

	#funkcja zamykająca stream z kamerki
	def closeFrontCamcorderStream(self):
		os.system("rm temp/stream")
		self.close()
	#slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera
	def streamFromFrontWebcam(self,ResizedFrame):
		self.VideoLabel.setPixmap(ResizedFrame)
		self.VideoLabel.show()

#Klasa odpowiadająca za BackCamcorderWindow, czyli za forms/back_camcorder_window.py
#analogicznie dla kamery cofania
class BackCamcorderWindow(QMainWindow, blank_window.Ui_BlankWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())
		self.show()

		self.Back.clicked.connect(lambda: self.closeBackCamcorderStream())

		#tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki
		self.VideoLabel = QLabel(self)
		#ustalam pozycję i wymiary: x, y, szerokość, wysokość
		self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540))

		#tworze nowy wątek
		self.ThreadStream = QThread()
		#tworzę obiekt, który dziedziczy po QObject
		#dzięki niemu będzie możliwość obsługi slotów i sygnałów
		self.WorkerStream = Camera("/dev/BackCamcorder")

		#jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap
		#to funkcja streamFromBackWebcam() go obsłuży
		#czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli
		self.WorkerStream.StreamSignal.connect(self.streamFromBackWebcam)

		#przenoszę obiekt WorkerStream do nowego wątku
		self.WorkerStream.moveToThread(self.ThreadStream)

		#jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy
		self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit)

		#jeśli nowy wątek zostanie uruchomiony to
		#zostanie wykonana funkcja startCamcorderStream() z klasy Camera
		self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream)

		#uruchamiam nowy wątek
		self.ThreadStream.start()

	#funkcja zamykająca stream z kamerki
	def closeBackCamcorderStream(self):
		os.system("rm temp/stream")
		self.close()
	#slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera
	def streamFromBackWebcam(self,ResizedFrame):
		self.VideoLabel.setPixmap(ResizedFrame)
		self.VideoLabel.show()

#Klasa odpowiadająca za CameraWindow, czyli za forms/camera_window
#analogicznie jak wyżej, tylko klasa do obługi zdjęć
#wszystkie 3 następne klasy do obsługi robienia zdjęć
from forms import camera_window
class CameraWindow(QMainWindow, camera_window.Ui_CameraWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Front_Camera.clicked.connect(lambda: self.showFrontCameraForm())
		self.Back_Camera.clicked.connect(lambda: self.showBackCameraForm())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def showFrontCameraForm(self):
		self.dialog = FrontCameraWindow()
	def showBackCameraForm(self):
		self.dialog = BackCameraWindow()

#Klasa odpowiadająca za FrontCameraWindow, czyli za forms/front_camera_window.py
class FrontCameraWindow(QMainWindow, blank_window.Ui_BlankWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())
		self.show()

		self.Back.clicked.connect(lambda: self.closeFrontCamcorderStream())

		#tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki
		self.VideoLabel = QLabel(self)
		#ustalam pozycję i wymiary: x, y, szerokość, wysokość
		self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540))

		#Rysuję przycisk zrób zdjęcie
		self.TakePhoto=RadioPlayWindow.drawControlFMButton(self,"TakePhoto",860,160,"#26d8fc","camera.png")
		self.TakePhoto.clicked.connect(lambda: self.takePhoto())
		self.TakePhoto.show()
		#dodaje rysowanie etykiety
		self.TakePhotoLabel=RadioPlayWindow.drawControlButtonLabel(self,860,320,"Zrób zdjęcie")
		self.TakePhotoLabel.show()

		#tworze nowy wątek
		self.ThreadStream = QThread()
		#tworzę obiekt, który dziedziczy po QObject
		#dzięki niemu będzie możliwość obsługi slotów i sygnałów
		self.WorkerStream = Camera("/dev/FrontCamcorder")

		#jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap
		#to funkcja streamFromWebcam() go obsłuży
		#czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli
		self.WorkerStream.StreamSignal.connect(self.streamFromFrontWebcam)

		#przenoszę obiekt WorkerStream do nowego wątku
		self.WorkerStream.moveToThread(self.ThreadStream)

		#jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy
		self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit)

		#jeśli nowy wątek zostanie uruchomiony to
		#zostanie wykonana funkcja startCamcorderStream() z klasy Camera
		self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream)

		#uruchamiam nowy wątek
		self.ThreadStream.start()

	#funkcja zamykająca stream z kamerki
	def closeFrontCamcorderStream(self):
		os.system("rm temp/stream")
		self.close()
	#slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera
	def streamFromFrontWebcam(self,ResizedFrame):
		self.VideoLabel.setPixmap(ResizedFrame)
		self.VideoLabel.show()
	def takePhoto(self):
		os.system("touch temp/photo")

#Klasa odpowiadająca za BackCameraWindow, czyli za forms/back_camera_window.py
class BackCameraWindow(QMainWindow, blank_window.Ui_BlankWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())
		self.show()

		self.Back.clicked.connect(lambda: self.closeBackCamcorderStream())

		#tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki
		self.VideoLabel = QLabel(self)
		#ustalam pozycję i wymiary: x, y, szerokość, wysokość
		self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540))

		#Rysuję przycisk zrób zdjęcie
		self.TakePhoto=RadioPlayWindow.drawControlFMButton(self,"TakePhoto",860,160,"#26d8fc","camera.png")
		self.TakePhoto.clicked.connect(lambda: self.takePhoto())
		self.TakePhoto.show()
		#dodaje rysowanie etykiety
		self.TakePhotoLabel=RadioPlayWindow.drawControlButtonLabel(self,860,320,"Zrób zdjęcie")
		self.TakePhotoLabel.show()

		#tworze nowy wątek
		self.ThreadStream = QThread()
		#tworzę obiekt, który dziedziczy po QObject
		#dzięki niemu będzie możliwość obsługi slotów i sygnałów
		self.WorkerStream = Camera("/dev/BackCamcorder")

		#jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap
		#to funkcja streamFromBackWebcam() go obsłuży
		#czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli
		self.WorkerStream.StreamSignal.connect(self.streamFromBackWebcam)

		#przenoszę obiekt WorkerStream do nowego wątku
		self.WorkerStream.moveToThread(self.ThreadStream)

		#jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy
		self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit)

		#jeśli nowy wątek zostanie uruchomiony to
		#zostanie wykonana funkcja startCamcorderStream() z klasy Camera
		self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream)

		#uruchamiam nowy wątek
		self.ThreadStream.start()

	#funkcja zamykająca stream z kamerki
	def closeBackCamcorderStream(self):
		os.system("rm temp/stream")
		self.close()
	#slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera
	def streamFromBackWebcam(self,ResizedFrame):
		self.VideoLabel.setPixmap(ResizedFrame)
		self.VideoLabel.show()
	def takePhoto(self):
		os.system("touch temp/photo")

#Klasa odpowiadająca za MultimediaWindow czyli za forms/multimedia_window.py
#wyświetla listę multimedialnych przycisków (netflix, spotify itd.)
#oraz odpowiada za ich obsługę
from forms import multimedia_window
class MultimediaWindow(QMainWindow, multimedia_window.Ui_MultimediaWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self) # gets defined in the UI file

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Spotify.clicked.connect(lambda: self.playSpotify())
		self.Youtube.clicked.connect(lambda: self.playYoutube())
		self.Internet.clicked.connect(lambda: self.startChromium())
		self.Netflix.clicked.connect(lambda: self.startNetflix())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def playSpotify(self):
		spotifyPath="chromium-browser https://open.spotify.com/browse/featured"
		#spotifyPath="firefox https://open.spotify.com/browse/featured"
		os.system(spotifyPath)
	def playYoutube(self):
		youtubePath="chromium-browser https://www.youtube.com"
		os.system(youtubePath)
	def startChromium(self):
		os.system('chromium-browser')
	def startNetflix(self):
		netflixPath="chromium-browser https://www.netflix.com "
		os.system(netflixPath)

#Klasa odpowiadająca za CloseWindow, czyli za forms/close_window.py
#klasa odpowiada za okno zamykania aplikacji
from forms import close_window
class CloseWindow(QMainWindow, close_window.Ui_CloseWindow):
	def __init__(self):
		super(self.__class__, self).__init__()
		self.setupUi(self)

		#przypisuje konkretną funkcję do przycisku i sygnał
		self.Restart.clicked.connect(lambda: self.restartPI())
		self.Desktop.clicked.connect(lambda: self.showDesktop())
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setStyleSheet(open("resources/style.qss", "r").read())

	#funkcję(sloty) do obsługi przycisków
	def restartPI(self):
		os.system('sudo reboot')
	def showDesktop(self):
		os.system('sudo pkill -9 arecord;sudo pkill -9 aplay;sudo killall python3')


import pygame, sys
from settings import *
from level import Level
import colores
import constantes

#Iniciamos el juego
pygame.init()
#tamaño da ventana
screen =  pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
level = Level(level_map, screen)

#Bucle principal del juego
while True:
 for event in pygame.event.get():
  if event.type == pygame.QUIT:
    pygame.quit()
    sys.exit()
  screen.fill(colores.blanco)
  level.run()

  pygame.display.update()
  clock.tick(constantes.FPS)


from ellipsis import apiManager
from ellipsis import sanitize

def search(username, fuzzySearch= True):

    sanitize.validString('username', username, True)

    sanitize.validBool('fuzzySearch', fuzzySearch, True)

    body = {'username': username, 'fuzzySearch':fuzzySearch}
    r = apiManager.get('/user', body, None)

    return r

def get(userId):
    sanitize.validUuid('userId', userId, True)

    r = apiManager.get('/user/' + userId, None, None)
    return r


import pandas as pd
import numpy as np
import tensorflow.compat.v1 as tf

tf.compat.v1.disable_eager_execution()

# 키, 몸무게, 레이블이 적힌 CSV 파일 읽어 들이기 --- (※1)
csv = pd.read_csv("iris.csv")

# 데이터 정규화 --- (※2)
csv["SepalLength"] = csv["SepalLength"]/10
csv["SepalWidth"] = csv["SepalWidth"]/10
csv["PetalLength"] = csv["PetalLength"]/10
csv["PetalWidth"] = csv["PetalWidth"]/10
# one-hot 레이블

# 레이블을 배열로 변환하기 --- (※3)
# - thin=(1,0,0) / normal=(0,1,0) / fat=(0,0,1)
bclass = {"Iris-setosa": [1,0,0], "Iris-versicolor": [0,1,0], "Iris-virginica": [0,0,1]}
csv["label_name"] = csv["Name"].apply(lambda x : np.array(bclass[x]))

# 테스트를 위한 데이터 분류 --- (※4)
test_csv = csv[50:150]
test_pat = test_csv[["SepalLength","SepalWidth","PetalLength","PetalWidth"]]
test_ans = list(test_csv["label_name"])

# 데이터 플로우 그래프 구축하기 --- (※5)
# 플레이스홀더 선언하기
x  = tf.placeholder(tf.float32, [None, 4]) # 키와 몸무게 데이터 넣기
y_ = tf.placeholder(tf.float32, [None, 3]) # 정답 레이블 넣기

# 변수 선언하기 --- (※6)
W = tf.Variable(tf.zeros([4, 3])) # 가중치
b = tf.Variable(tf.zeros([3])) # 바이어스
# 실제 값과 예측 값의 분산을 계산할 회귀 함수 지정.

# 소프트맥스 회귀 정의하기 --- (※7)
y = tf.nn.softmax(tf.matmul(x, W) + b)

# 모델 훈련하기 --- (※8)
# 손실을 최소화 하기 위한 최적화 코드
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)+(1-y_)*tf.log(1-y))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(cross_entropy)

# 정답률 구하기
predict = tf.equal(tf.argmax(y, 1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(predict, tf.float32))

# 세션 시작하기
sess = tf.Session()
sess.run(tf.global_variables_initializer()) # 변수 초기화하기

# 학습시키기
for step in range(150):
    data = csv[["SepalLength", "SepalWidth", "PetalLength", "PetalWidth"]]
    ans = list(csv["label_name"])
    fd = {x: data, y_: ans}
    sess.run(train, feed_dict=fd)
    if step % 10 == 0:
        cre = sess.run(cross_entropy, feed_dict=fd)
        acc = sess.run(accuracy, feed_dict=fd)
        print("step=", step, "cre=", cre, "acc=", acc)

# 최종적인 정답률 구하기
acc = sess.run(accuracy, feed_dict=fd)
print("정답률 =", acc)
pre = sess.run(tf.argmax(y, 1), feed_dict=fd)
#print(pre)
for idx in pre:
    print(list(bclass.values())[idx])


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

#
 Functionality 3 - Shortest Ordered Route

#import libraries
import pandas as pd
import csv
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra
import collections
import heapq
from collections import defaultdict
from itertools import groupby
from ipywidgets import HTML
from ipyleaflet import Map, basemaps, basemap_to_tiles, Polyline, Marker, Icon, Popup
from IPython.display import Image

#
 Read and clean the data

#create variables to store the path of data containing distance and time distance
path_distance = "USA-road-d.CAL.gr"
path_time_distance = "USA-road-t.CAL.gr"

#function to check the contents of the file containing distance by printing only few lines
def data_view(path):
    line_num = 0
    with open(path, encoding='utf-8') as file:
        for i in file:
            if (line_num < 10):
                print(i)
                line_num += 1

#call the function by passing the path containing file with "distance"
data_view(path_distance)

#call the function by passing the path containing file with "time distance"
data_view(path_time_distance)

#function to consider only the lines after 7th line, split the values and store the necessary data in lists
node1 = []
node2 = []
distance = []
def data_cleaning(path):
    line_num = 0
    with open(path, encoding='utf-8') as file:
        for i in file:
            if (line_num > 6):
                parts = i.split()
                node1.append(parts[1])
                node2.append(parts[2])
                distance.append(parts[3])
            line_num += 1

#call the function by passing the path containing file with "distance"
data_cleaning(path_distance)

#create a dataframe of the lists containing distance with another column (ie. network distance = 1)
df = pd.DataFrame(
    {'source': node1,
     'target': node2,
     'distance': distance,
     'weight' : 1
    })

#check how the dataframe containing distance looks
df

#call the function by passing the path containing file with "time distance"
data_cleaning(path_time_distance)

#create a dataframe of the lists containing time distance with another column (ie. network distance = 1)
df_td = pd.DataFrame(
    {'source': node1,
     'target': node2,
     'time_distance': distance,
     'weight' : 1
    })

#check how the dataframe containing time distance looks
df_td

#
 The shortest route function

#
 I am going to be using a brute force approach in which I will find the shortest distance between the source node to the first node in the list, then first node to second node, then second node to third node and so on, till the destination node and add up the distances

#create a class called Graph where
#self.edges is a dict of all possible next nodes e.g. {'1': ['4', '3', '8', '9'], ...}
#self.weights has all the weights between two nodes, with the two nodes as a tuple as the key e.g. {('1', '2'): 1, ('5', '9'): 1, ...}

class Graph():
    def __init__(self):
        self.edges = defaultdict(list)
        self.weights = {}

    def add_edge(self, from_node, to_node, weight):
        # assuming edges are bi-directional
        self.edges[from_node].append(to_node)
        self.edges[to_node].append(from_node)
        self.weights[(from_node, to_node)] = weight
        self.weights[(to_node, from_node)] = weight

#call the Graph class
graph = Graph()

#take the input in which first node represents the source and the last node represents the destination
list_of_nodes_to_dest = []
def take_input():
    while True:
        inp = input()
        if inp == "":
            break
        else:
            list_of_nodes_to_dest.append(inp)

    #pack the graph, source input and destination input into a tuple ie. (graph,source,destination)
    res = [(graph ,list_of_nodes_to_dest[i], list_of_nodes_to_dest[i + 1])
           for i in range(len(list_of_nodes_to_dest) - 1)]

    #choose which type of distance to consider
    print("Choose 1 for distance, 2 for network distance and 3 for time distance")
    inp = input()
    return inp,res

inp,res = take_input()

#create an edge list with source, target and distance/network distance/time distance
edge_list = []
if inp == '1':
    for i,j in df.iterrows():
        edge_list.append((j[0],j[1],j[2]))
elif inp == '2':
    for i,j in df.iterrows():
        edge_list.append((j[0],j[1],j[3]))
elif inp == '3':
    for i,j in df_td.iterrows():
        edge_list.append((j[0],j[1],j[2]))

#check the length of edge list
len(edge_list)

#add the edge list to the graph
for edge in edge_list:
    graph.add_edge(*edge)

#shortest route function
def dijsktra(graph, initial, end):
    # shortest paths is a dict of nodes
    # whose value is a tuple of (previous node, weight)
    shortest_paths = {initial: (None, 0)}
    current_node = initial
    visited = set()

    while current_node != end:
        visited.add(current_node)
        destinations = graph.edges[current_node]
        weight_to_current_node = shortest_paths[current_node][1]

        for next_node in destinations:
            weight = graph.weights[(current_node, next_node)] + weight_to_current_node
            if next_node not in shortest_paths:
                shortest_paths[next_node] = (current_node, weight)
            else:
                current_shortest_weight = shortest_paths[next_node][1]
                if current_shortest_weight > weight:
                    shortest_paths[next_node] = (current_node, weight)

        next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited}
        if not next_destinations:
            return "Route Not Possible"
        # next node is the destination with the lowest weight
        current_node = min(next_destinations, key=lambda k: next_destinations[k][1])

    # Work back through destinations in shortest path
    path = []
    weights = []
    while current_node is not None:
        path.append(current_node)
        next_node = shortest_paths[current_node][0]
        weights.append(shortest_paths[current_node][1])
        current_node = next_node
    # Reverse path
    path = path[::-1]
    return weights[0],path

#call the shortest route function to find the shortest path and weight between each set of nodes
arr = []
for tripple in res:
    for i in dijsktra(*tripple):
        arr.append(i)
    print(tripple[1] +" -> " +tripple[2], dijsktra(*tripple))

#store the resultant path and weight separately
res_path = [arr[i] for i in range(len(arr)) if i % 2 != 0]
res_weight = [arr[i] for i in range(len(arr)) if i % 2 == 0]

#flatten the list of lists of path
flattened_list = []
for x in res_path:
    for y in x:
        flattened_list.append(y)

#clean up the path and add up the weights of the set of nodes
res_path = [x[0] for x in groupby(flattened_list)]
res_weight  = sum(res_weight)
print("The shortest route from " + list_of_nodes_to_dest[0] +" to " + list_of_nodes_to_dest[-1] +" is:\n" +str(res_path))
print("The total weight is " +str(res_weight))

#
 Validate the result

#use networkx to create an edgelist (for validating the results)
G = nx.from_pandas_edgelist(df,'source','target', edge_attr='weight')

#run the below function to find the shortest path for a set of nodes(for validating the results)
single_source_dijkstra(G,'21','22')

#
 Visualization of the graph

#read the node informtion data
df_data = pd.read_csv('node_information_file.csv')

#convert the latitudes and logitudes in proper format by dividing them by 1000000
#store the latitude and logitude of the source, must-pass and destination nodes in a list
location_latlongs = []
for x in list_of_nodes_to_dest:
    location_latlong = []
    location_latlong.append(float(df_data["Longitude"].iloc[int(x)-1])/1000000)
    location_latlong.append(float(df_data["Latitude"].iloc[int(x)-1])/1000000)
    location_latlong.append(x)
    location_latlongs.append(location_latlong)

#store the latitude and longitude of all the nodes in the shortest route from sourse to destination
path_latlongs = []
for x in res_path:
    path_latlong = []
    path_latlong.append(float(df_data["Longitude"].iloc[int(x)-1])/1000000)
    path_latlong.append(float(df_data["Latitude"].iloc[int(x)-1])/1000000)
    path_latlongs.append(path_latlong)

#create a visulaization for graph
def visualize():
    center = location_latlongs[1]

    m = Map(center=center, zoom=8)
    icon1 = Icon(icon_url='https://img.icons8.com/ultraviolet/40/000000/map-pin.png', icon_size=[40, 40], icon_anchor=[20,40])
    icon2 = Icon(icon_url='https://img.icons8.com/officel/40/000000/map-pin.png', icon_size=[40, 40], icon_anchor=[20,40])
    icon3 = Icon(icon_url='http://icons.iconarchive.com/icons/custom-icon-design/flatastic-6/256/Circle-icon.png', icon_size=[10, 10], icon_anchor=[5,5], shadow_size=[5,5])

    line = Polyline(
        locations = [[
        path_latlongs,]],
        color = "#669df6" ,
        fill= False,
        weight = 2,
        stroke = True
    )

    m.add_layer(line)

    style = {'text-align': 'left','description_width': '150px'}
    i = 0
    while i < len(location_latlongs):
        if i == 0:
            message = HTML()
            message.placeholder = "Source"
            message.description = "Source"+"
Node ID: "+location_latlongs[i][2]+"
Lat:   "+ str(location_latlongs[i][1])+ "
Long:  "+ str(location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False, title="Source",
                            icon=icon1,
                            rise_on_hover=True,
                            z_index_offset = 100)
            m.add_layer(marker);
            marker.popup = message

        elif (len(location_latlongs)-i) == 1:
            message = HTML()
            message.placeholder = "Destination"
            message.description = "Destination"+"
Node ID: "+location_latlongs[i][2]+"
Lat:   "+ str(location_latlongs[i][1])+ "
Long:  "+ str(location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False,
                            title="Destination",
                            icon=icon2,
                            rise_on_hover=True)
            m.add_layer(marker);
            marker.popup = message

        else:
            message = HTML()
            message.placeholder = "Waypoint"
            message.description = "Waypoint: "+str(i)+""+"
Node ID: "+location_latlongs[i][2]+"
Lat:   "+ str(location_latlongs[i][1])+ "
Long:  "+ str(location_latlongs[i][0])
            message.style = style
            marker = Marker(location=location_latlongs[i],
                            draggable=False,
                            icon=icon3,
                            title="Waypoint",
                            rise_on_hover=True)
            m.add_layer(marker);
            marker.popup = message
        i += 1

    return(m)

#call the visulaization function
m = visualize()

#print the map of visulalization
m

#
 I am attaching the png images of the route as the map visualization is dynamic and it will not show up on github.

Image(filename = 'nodes_route.png')
Image(filename = 'source_node.png')
Image(filename = 'destination_node.png')
Image(filename = 'waypoint_node_1.png')
Image(filename = 'waypoint_node_2.png')


from ml_scheduler.ml_pipeline.shift_predictor import predict_week_shifts
from ml_scheduler.ml_pipeline.user_predictor import predict_week_users

from firesdk.util.utils import org_names_filter

def test(path_to_csv, path_to_json_dir, company, department, needs_type='avg', remove_ratios=False,
         remove_needs=False, classifier_id=None, include_manager=False):
    """

    :param path_to_csv: String. Path to csv file of all the shifts.
    :param path_to_json_dir: String. Path to a directory containing all json schedules.
    :param company: String. Name of the company.
    :param department: String. Name of the department in the company.
    :param needs_type: String. Specifies type of needs to use. 'manual', 'avg', or 'median'.
    :param remove_ratios: Bool. Whether or not the remove the ratios from the features.
    :param remove_needs: Bool. Whether or not the remove the needs from the features.
    :param classifier_id: String. The classifier to use for training and prediction of the user predictor.
     'random_forest', 'k_neighbors', 'radius_neighbors' or None. If None, use a neural net from Tensorflow.
    :param include_manager: Bool. Whether or not to include the scheduling manager of the department in the schedule.
    :return:
    """
    company = org_names_filter(company)
    department = org_names_filter(department)

    shifts_predictions, shifts_shifts_key = predict_week_shifts(
        path_to_csv,
        path_to_json_dir,
        company,
        department,
        needs_type=needs_type,
        remove_ratios=remove_ratios,
        remove_needs=remove_needs
    )

    user_predictions, users, shifts_key = predict_week_users(
        path_to_csv,
        company,
        department,
        shifts_shifts_key,
        classifier_id=classifier_id
    )

    print(shifts_predictions)
    print(user_predictions)

    for a, b in zip(shifts_shifts_key, shifts_key):
        if a != b:
            raise ValueError('shifts_keys not aligned')

    for day_of_week, shift_pred in shifts_predictions.items():
        needed_shift_indexes = {}
        for index, shift in enumerate(shift_pred):
            if shift == 1:
                needed_shift_indexes[index] = ''

        # what if a user wins two in one day???
        for shift_index in needed_shift_indexes.keys():
            current_highest = 0
            for email, user_pred in user_predictions[day_of_week].items():
                if user_pred[0][shift_index] > current_highest:
                    current_highest = user_pred[0][shift_index]
                    needed_shift_indexes[shift_index] = email

        print(needed_shift_indexes)

    print(users[0])


from django.shortcuts import render,redirect
from .models import Vendors, Vouchers , Suggest_Reward,Redemption_Request , budget
from Users.models import User , announcements
from activities.models import Points
from django.core.mail import send_mail
import pytz
from datetime import datetime,date,timedelta
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
import matplotlib.pyplot as plt
from io import StringIO
import numpy as np

# Create your views here.
def is_expired(end_date):
    utc=pytz.UTC
    now = utc.localize(datetime.now())
    if now >= end_date:
        return True
    else:
        return False

def create_vendor(request):
    if request.user.role == "Role.A":
        if request.method == "POST":
            name = request.POST["name"]
            start_date = request.POST["start_date"]

            end_date = request.POST["end_date"]
            Logo = request.FILES["Logo"]
            if Vendors.objects.filter(name=request.POST["name"]).exists():
                return render(request,"rewards/create_vendor.html",{
                "warning_message":"Vendor Already Exists try adding vouchers to that Vendor"
            })
            else:
                if end_date:
                    Vendors.objects.create(name = name , end_date = end_date , img = Logo , start_date = start_date , creator = request.user)
                else:
                    Vendors.objects.create(name = name  , img = Logo , start_date = start_date , creator = request.user)

                announcements.objects.create(creator = request.user , PostText = f"A new vendor {name} is added!!",EndDate = datetime.now() + timedelta(days=30))
                return render(request,"rewards/create_vendor.html",{
                "message":"Vendor successfuly added"
                })
        else:
            return render(request,"rewards/create_vendor.html")
    else:
        return redirect("login")

def view_vendors(request):
    if request.user.is_authenticated:
        all_vendors = Vendors.objects.filter().all()
        vendors = []
        utc=pytz.UTC
        now = utc.localize(datetime.now())
        for vendor in all_vendors:
            if vendor.start_date <= now:
                vendors.append(vendor)
        return render(request,"rewards/vendors.html",{
            "vendors": vendors
})
def vendor_view(request,vendor_id):
    vendor = Vendors.objects.get(pk = vendor_id)
    vouchers = Vouchers.objects.filter(vendor = vendor).all()
    return render(request,"rewards/vendor.html",{
        "vendor":vendor,
        "vouchers":vouchers
})

def add_new_reward(request):
    if request.user.role == "Role.A":
        if request.method == "POST":
            vendor = request.POST["name"]
            getvendor = Vendors.objects.get(name = vendor)
            start_date = request.POST["start_date"]

            end_date = request.POST["end_date"]
            points = request.POST["points_equivalent"]
            if end_date:
                Vouchers.objects.create(vendor = getvendor, end_date = end_date, points_equivalent=points , start_date = start_date , creator = request.user)
            else:
                Vouchers.objects.create(vendor = getvendor, points_equivalent=points , start_date = start_date , creator = request.user)
            announcements.objects.create(creator = request.user , PostText = f"A new Reward from {vendor} is added!!",EndDate = end_date)
            return render(request,"rewards/create_reward.html",{
                "message":"Reward Successfuly Added"
                })

        else:
            return render(request,"rewards/create_reward.html")
    else:
        return redirect("login")
def suggest_rewards(request):
    if request.method== "POST":
        if request.user.role == "Role.M" or request.user.role == "Role.E" :
            getvendorname= request.POST['vendor']
            getwebsite= request.POST['website']
            getreason= request.POST['reason']
            Suggest_Reward.objects.create(vendor = getvendorname , website=getwebsite, reason=getreason)

            return render(request,"rewards/suggest_rewards.html", {
                'message': "Vendor suggestion has been successfully submitted"
            })

    else:

        return render(request,"rewards/suggest_rewards.html")

def redemption_request(request,voucher_id):
    if not request.user.role == "Role.A":
        voucher = Vouchers.objects.get(pk = voucher_id)
        if request.method == "POST":
            points_equivalent = voucher.points_equivalent
            if request.user.points >= voucher.points_equivalent:
                points_needed = []
                points = Points.objects.filter(employee = request.user,is_used = False).order_by('end_date')
                for point in points:
                    if is_expired(point.end_date) == False:
                        points_needed.append(point)
                for point in points_needed:
                    acquired = 0
                    if acquired < points_equivalent:
                        acquired = acquired + point.points
                        if acquired > points_equivalent:

                            Points.objects.filter(pk = point.id).update(points = acquired - points_equivalent)
                            break
                        else:
                            Points.objects.filter(pk = point.id).update(is_used = True)

                User.objects.filter(username = request.user.username).update(points = request.user.points - points_equivalent)
                Redemption_Request.objects.create(voucher = voucher,employee = request.user)
                return redirect("users-home")
            else:
                return HttpResponseRedirect(reverse("vendor", args = (voucher_id,)))

def admin_view_redemption_requests(request):
    if request.user.is_authenticated and request.user.role == "Role.A":
        redemption_requests = Redemption_Request.objects.filter(status='Status.P')
        return render(request,"rewards/admin_view_redemption_requests.html",{
            "redemption_requests":redemption_requests})
    else:
        return redirect("login")

def redemption_request_view(request,redemption_request_id):
    redemption_request = Redemption_Request.objects.get(pk = redemption_request_id)
    return render(request,"rewards/admin_redemption_request_view.html",{"redemption_request":redemption_request})

def decline_redemption(request,request_id):
    if request.user.role == "Role.A":
        redemption_request = Redemption_Request.objects.get(pk = request_id)
        user = redemption_request.employee
        if request.method == "POST":

            Redemption_Request.objects.filter(pk = request_id).update(status='Status.D')
            User.objects.filter(username = user.username).update(points = user.points + redemption_request.voucher.points_equivalent)
            send_mail(
                    'Redemption Request',
                    'Your redemption request has been rejected',
                    'muhammad.mazen4@gmail.com.com',
                    [f'{Redemption_Request.objects.get(pk = request_id).employee.email}'],
                    fail_silently=False,)
            return redirect("admin_view_redemption_requests")
        else:
            return redirect("users-home")
    else:
        return(redirect("login"))
def accept_redemption(request , request_id):
    if request.user.role == "Role.A":

        if request.method == "POST":
            redemption_request = Redemption_Request.objects.get(pk = request_id)

            Redemption_Request.objects.filter(pk = request_id).update(status='Status.A',
                                                                                approved_by = request.user ,
                                                                                approved_date = datetime.now())

            return render(request,"rewards/admin_redemption_request_view.html",{
                    "redemption_request":redemption_request,
                    "message": "Accpeted"
                    })

def admin_accept_decline_reward (request):
     if (request.user.is_authenticated and request.user.role == "Role.A"):
        suggestion_requests= Suggest_Reward.objects.all()
        return render(request,'rewards/edit_reward.html',{
            'suggestion_requests': suggestion_requests,
        })

def delete_reward_suggestion (request, reward_id):
    if (request.user.is_authenticated):
        if request.user.role == "Role.A":
            reward = Suggest_Reward.objects.get(pk = reward_id)
            Suggest_Reward.objects.filter(pk = reward_id).delete()

            return render(request,'rewards/edit_reward.html',{
                "Message": f"suggest {reward} has been declined",
            })

def edit_approve_reward_suggestion(request, reward_id):
    if (request.user.is_authenticated and request.user.role == "Role.A"):
        if(request.method == "POST"):
            try:
                Vendors.objects.create(
                name=request.POST["vendor_name"],
            #  start_date= request.POST["start_date"],
                end_date= request.POST["end_date"],
                img= request.FILES["Image"])
                Suggest_Reward.objects.get(pk = reward_id).delete()
                return redirect('edit_reward')
            except:
                return render(request,'rewards/approve_reward.html',{
                "Message":"Vendor already exists"})
        else:
            reward_suggestion= Suggest_Reward.objects.filter(pk = reward_id)[0]
            return render(request,'rewards/approve_reward.html',{
                'reward_suggestion':reward_suggestion
            })

def delete_vendor(request,vendor_id):
    if request.user.role == "Role.A":
        vendor = Vendors.objects.get(pk = vendor_id)
        Vendors.objects.filter(pk = vendor_id).delete()
        vendors = Vendors.objects.filter().all()

        return render(request , "rewards/vendors.html",{
            "message":f"Vendor {vendor.name} is Deleted",
             "vendors": vendors
        })
    else:
        return redirect("login")

def put_budget(request):
    if request.user.role == "Role.A":
        now = datetime.now()

        if budget.objects.filter(year = int(now.year),is_active = True):
            #creating a piechart

            labels = ["Remaining Budget" , "Used Budget"]
            this_year_budget = budget.objects.filter(year = int(now.year),is_active = True)[0].budget
            budget_compare = budget.objects.filter(year = int(now.year),is_active = True)[0].budget_compare
            percentage = (this_year_budget/budget_compare)*100
            data = [percentage,100-percentage]
            print(4)

            if request.method == "POST":
                current_budget = budget.objects.filter(year = int(now.year),is_active = True)[0]
                # graph = return_graph(current_budget.budget , current_budget.budget_compare)
                budget_used_percentage = (current_budget.budget/current_budget.budget_compare)*100
                Budget = request.POST["budget"]

                points = budget.objects.filter(year = int(now.year))[0].point
                money = budget.objects.filter(year = int(now.year))[0].EGP
                budget.objects.filter(year = int(now.year)).update(is_active = False)
                budget.objects.create(budget = Budget , point = points , EGP = money , budget_compare = Budget)

                return redirect("make_budget")
            else:
                current_budget = budget.objects.filter(year = int(now.year),is_active = True)[0]
                budget_used_percentage = (current_budget.budget/current_budget.budget_compare)*100
                return render(request,"rewards/budget.html",{
                "newyear": (now.month == 1 and now.day == 1) or not budget.objects.filter(year = int(now.year),
                                                                                is_active = True),
                "current_budget":current_budget,
                "budget_used_percentage":budget_used_percentage,
                'labels': labels,
                'data': data,

            })

        else:
            current_budget = 0
            budget_used_percentage = 0
            labels = ["Remaining Budget" , "Used Budget" ]
            this_year_budget = 0
            budget_compare = 0
            percentage = 0
            data = [percentage,100-percentage]

            if request.method == "POST":

                Budget = request.POST["budget"]
                points = request.POST["points"]
                money = request.POST["EGP"]
                budget.objects.create(budget = Budget , point = points , EGP = money , budget_compare = Budget, admin = request.user)

                return redirect("make_budget")
            else:
                return render(request,"rewards/budget.html",{
                    "newyear": (now.month == 1 and now.day == 1) or not budget.objects.filter(year = int(now.year),
                                                                                is_active = True),
                    "current_budget":current_budget,
                    "budget_used_percentage":budget_used_percentage,
                    'labels': labels,
                    'data': data,

                })


import unittest

class MyTestCase(unittest.TestCase):
    def test_something(self):
        filename = "./data/day1.txt"

        elfCalories = []

        with open(filename) as f:
            elf = []
            for line in f:
                strippedLine = line.strip()
                if strippedLine:
                    elf.append(int(strippedLine))
                else:
                    elfsTotalCalories = 0
                    for i in elf:
                        elfsTotalCalories += i
                    elfCalories.append(elfsTotalCalories)
                    elf=[]

        self.assertEqual(258, len(elfCalories))
        self.assertEqual(44427, elfCalories[0])
        self.assertEqual(33711 + 6672, elfCalories[1])
        elfCalories.sort(reverse=True)
        self.assertEqual(71124, elfCalories[0])
        top3 = elfCalories[0] + elfCalories[1] + elfCalories[2]
        self.assertEqual(204639, top3)

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


import tensorflow as tf

class GradientAccumulator:

    def __init__(self):
        """Initializes the accumulator."""
        self._gradients = []
        self._accum_steps = None

    @property
    def step(self):
        """Number of accumulated steps."""
        if self._accum_steps is None:
            self._accum_steps = tf.Variable(
                tf.constant(0, dtype=tf.int64),
                trainable=False
            )

        return self._accum_steps.value()

    @property
    def gradients(self):
        """The accumulated gradients on the current replica."""
        if not self._gradients:
            raise ValueError("The accumulator should be called first to initialize the gradients")
        return list(gradient.value() if gradient is not None else gradient for gradient in self._gradients)

    def __call__(self, gradients):
        """Accumulates :obj:`gradients` on the current replica."""
        if not self._gradients:
            _ = self.step  # Create the step variable.
            self._gradients.extend(
                [
                    tf.Variable(
                        tf.zeros_like(gradient),
                        trainable=False
                    )
                    if gradient is not None
                    else gradient
                    for gradient in gradients
                ]
            )
        if len(gradients) != len(self._gradients):
            raise ValueError(f"Expected {len(self._gradients)} gradients, but got {len(gradients)}")

        for accum_gradient, gradient in zip(self._gradients, gradients):
            if accum_gradient is not None and gradient is not None:
                accum_gradient.assign_add(gradient)

        self._accum_steps.assign_add(1)

    def reset(self):
        """Resets the accumulated gradients on the current replica."""
        if not self._gradients:
            return
        self._accum_steps.assign(0)
        for gradient in self._gradients:
            if gradient is not None:
                gradient.assign(tf.zeros_like(gradient))


#!/usr/bin/env python3

import os
import numpy
import argparse

here = os.path.dirname(os.path.realpath(__file__))

def gen_board(size_x, size_y, height, num_towers, seed):
    numpy.random.seed(seed)

    board = [[0 for x in range(size_x)] for y in range(size_y)]

    cells = [(x, y) for x in range(size_x) for y in range(size_y)]

    first = True
    for i in numpy.random.choice (range(len(cells)), num_towers, replace=False):
        (x, y) = cells[i]
        col_height = height if first else numpy.random.choice(range(2, height + 1))
        first = False
        board[y][x] = col_height

    board_name = 'random_towers_{}x{}_{}_{}_{}.txt'.format(size_x, size_y, height, num_towers, seed)
    f = open(os.path.join(here, 'boards', board_name), 'w')
    for row in board:
        f.write(" ".join(map(str, row)) + '\n')
    f.close()

    return board_name

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("--size_x", type=int, default=4)
    parser.add_argument("--size_y", type=int, default=4)
    parser.add_argument("--height", type=int, default=4)
    parser.add_argument("--num_towers", type=int, default=4)
    parser.add_argument("--seed", type=int, default=0)

    args = parser.parse_args()

    gen_board(args.size_x, args.size_y, args.height, args.num_towers, args.seed)

if __name__ == "__main__":
    main()


from molecule_class import *

Elements = {
 'H':
     {'Mass':1.0079, 'PeriodicTableNum':1 },
 'C':
     {'Mass':12.011, 'PeriodicTableNum':6 },
 'O':
     {'Mass':15.999, 'PeriodicTableNum':8 },
 'N':
     {'Mass':14.007, 'PeriodicTableNum':7 },
 'P':
     {'Mass':30.973762, 'PeriodicTableNum':15 },
 'S':
     {'Mass':32.07, 'PeriodicTableNum':16 },
 'F':
     {'Mass':18.9984032, 'PeriodicTableNum':9 },
 'CL':
     {'Mass':35.453, 'PeriodicTableNum':17 },
 'BR':
     {'Mass':79.904, 'PeriodicTableNum':35 },
 'I':
     {'Mass':126.90447, 'PeriodicTableNum':53 },
 'AL':
     {'Mass':26.9815386, 'PeriodicTableNum':13 }
}

def TrimElementName(s):
    El = s[:2].upper()
    if El in Elements.keys():
        return El
    else:
        if El[:1] in Elements.keys():
            return El[:1]
        else:
            sys.stderr.write("--- !Warning in "+inspect.stack()[0][3]+": could not get an element name from the string ["+str(s)+"]. Maybe extend the elements list? Known elements: ["+str(Elements)+"]. Returning none. \n")
            return 'none'


class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        curr, res, letter = 0, 0, set()
        for i, ch in enumerate(s):
            while ch in letter:
                letter.remove(s[curr])
                curr += 1
            letter.add(ch)
            res = max(res, i - curr + 1)
        return res

leetcode_3_Longest Substring Without Repeating Characters.py