import pytest
from mock import Mock
from pyramid.security import ALL_PERMISSIONS, Allow, Everyone, Authenticated

from nefertari import acl

class TestACLsUnit(object):

    def test_baseacl_init(self):
        acl_obj = acl.BaseACL(request='foo')
        assert acl_obj.request == 'foo'
        assert acl_obj.__acl__ == [(Allow, 'g:admin', ALL_PERMISSIONS)]
        assert acl_obj.__context_acl__ == [
            (Allow, 'g:admin', ALL_PERMISSIONS)]

    def test_baseacl_acl_getter(self):
        acl_obj = acl.BaseACL(request='foo')
        assert acl_obj.acl is acl_obj.__acl__
        assert acl_obj.acl == [(Allow, 'g:admin', ALL_PERMISSIONS)]

    def test_baseacl_acl_setter(self):
        acl_obj = acl.BaseACL(request='foo')
        assert acl_obj.acl == [(Allow, 'g:admin', ALL_PERMISSIONS)]
        ace = (Allow, Everyone, ['index', 'show'])
        with pytest.raises(AssertionError):
            acl_obj.acl = [ace]
        acl_obj.acl = ace
        assert acl_obj.acl == [(Allow, 'g:admin', ALL_PERMISSIONS), ace]

    def test_baseacl_context_acl(self):
        acl_obj = acl.BaseACL(request='foo')
        assert acl_obj.context_acl(None) is acl_obj.__context_acl__

    def test_baseacl_getitem_no_context_cls(self):
        acl_obj = acl.BaseACL(request='foo')
        assert acl_obj.__context_class__ is None
        with pytest.raises(AssertionError):
            acl_obj.__getitem__('foo')

    def test_baseacl_getitem(self):
        acl_obj = acl.BaseACL(request='foo')
        clx_cls = Mock()
        clx_cls.pk_field.return_value = 'storyname'
        acl_obj.__context_class__ = clx_cls
        obj = acl_obj.__getitem__('foo')
        clx_cls.pk_field.assert_called_once_with()
        clx_cls.get.assert_called_once_with(
            __raise=True, storyname='foo')
        assert obj.__acl__ == acl_obj.__context_acl__
        assert obj.__parent__ == acl_obj
        assert obj.__name__ == 'foo'

    def test_rootacl(self):
        acl_obj = acl.RootACL(request='foo')
        assert acl_obj.__acl__ == [(Allow, 'g:admin', ALL_PERMISSIONS)]
        assert acl_obj.request == 'foo'

    def test_adminacl(self):
        acl_obj = acl.AdminACL(request='foo')
        assert isinstance(acl_obj, acl.BaseACL)
        assert acl_obj['foo'] == 1
        assert acl_obj['qweoo'] == 1

    def test_guestacl_acl(self):
        acl_obj = acl.GuestACL(request='foo')
        assert acl_obj.acl == [
            (Allow, 'g:admin', ALL_PERMISSIONS),
            (Allow, Everyone, ['index', 'show'])
        ]

    def test_guestacl_context_acl(self):
        acl_obj = acl.GuestACL(request='foo')
        assert acl_obj.context_acl('asdasd') == [
            (Allow, 'g:admin', ALL_PERMISSIONS),
            (Allow, Everyone, ['index', 'show']),
        ]

    def test_authenticatedreadacl_acl(self):
        acl_obj = acl.AuthenticatedReadACL(request='foo')
        assert acl_obj.acl == [
            (Allow, 'g:admin', ALL_PERMISSIONS),
            (Allow, Authenticated, 'index')
        ]

    def test_authenticatedreadacl_context_acl(self):
        acl_obj = acl.AuthenticatedReadACL(request='foo')
        assert acl_obj.context_acl('asdasd') == [
            (Allow, 'g:admin', ALL_PERMISSIONS),
            (Allow, Authenticated, 'show'),
        ]

class TestSelfParamMixin(object):

    def test_resolve_self_key_wrong_key(self):
        obj = acl.SelfParamMixin()
        assert obj.param_value == 'self'
        assert obj.resolve_self_key('') == ''
        assert obj.resolve_self_key('foo') == 'foo'

    def test_resolve_self_key_user_not_logged_in(self):
        obj = acl.SelfParamMixin()
        obj.request = Mock(user=None)
        assert obj.resolve_self_key('self') == 'self'

    def test_resolve_self_key_no_model_Cls(self):
        obj = acl.SelfParamMixin()
        obj.__context_class__ = None
        obj.request = Mock(user=1)
        assert obj.resolve_self_key('self') == 'self'

    def test_resolve_self_key_user_wrong_class(self):
        obj = acl.SelfParamMixin()
        obj.__context_class__ = dict
        obj.request = Mock(user='a')
        assert obj.resolve_self_key('self') == 'self'

    def test_resolve_self_key(self):
        obj = acl.SelfParamMixin()
        obj.__context_class__ = Mock
        user = Mock(username='user12')
        user.pk_field.return_value = 'username'
        obj.request = Mock(user=user)
        assert obj.resolve_self_key('self') == 'user12'


import time
import threading
import logging
import struct

from events.events import *

class JoystickEventProducer(object):

    started = False
    file = None
    index = 0

    def __init__(self, file, index):
        self.file = file
        self.index = index

    def _loop(self):

        js = open(self.file, 'rb')

        while self.started:
            evbuf = js.read(8)
            if evbuf:
                time, value, type, number = struct.unpack('IhBB', evbuf)
                if not (type & 0x80) and (type & 0x01):
                    if value == 1:
                        e = Event('joystick_button_pressed', {'joystick_num': self.index, 'button_num': number})
                        notify_event_receivers(e)

    def start(self):
        self.started = True
        t = threading.Thread(target=self._loop)
        t.daemon = True
        t.start()

    def stop(self):
        self.started = False

class JoystickService(object):

    started = False

    event_producers = [JoystickEventProducer('/dev/input/js0', 0), JoystickEventProducer('/dev/input/js1', 1)]

    def __init__(self):
        pass

    def _loop(self):

        for producer in self.event_producers:
            producer.start()

    def start(self):
        logging.info('Starting Joystick service...')
        self.started = True
        t = threading.Thread(target=self._loop)
        t.daemon = True
        t.start()

    def stop(self):
        for producer in self.event_producers:
            producer.stop()
        self.started = False


#!/usr/bin/env python
from __future__ import print_function, absolute_import
import os
import sys
import subprocess
import numpy as np
import astropy.io.fits as fits
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from desc.twinkles import PostageStampMaker, render_fits_image, \
    convert_image_to_hdu
from desc.twinkles.Display import image_norm
from desc.twinkles.db_table_access import LsstDatabaseTable

try:
    objectId = int(sys.argv[1])
    tempdir = sys.argv[2]
except:
    print("usage: %s <objectId> <tempdir>" % sys.argv[0])
    sys.exit(0)

def output_dir(filename):
    return os.path.join(tempdir, filename)

level2_repo = '/nfs/farm/g/desc/u1/users/jchiang/desc_projects/twinkles/Run1.1/output'

band = 'u'
size = 10.
scaling_factor = 50.

db_info = dict(db='jc_desc', read_default_file='~/.my.cnf')
jc_desc = LsstDatabaseTable(**db_info)

# Find all of the visits for the specified band.
visits = jc_desc.apply('''select visitId from CcdVisit
                          where filterName='%(band)s'
                          order by visitId''' % locals(),
                       lambda curs : [x[0] for x in curs])

# Find the coordinates of the object.
ra, dec = jc_desc.apply('''select psRA, psDecl from Object
                           where objectId=%(objectId)i''' % locals(),
                        lambda curs : tuple([x for x in curs][0]))

# Create the coadd postage stamp to get the normalization for the
# individual stamp images.
coadd = PostageStampMaker(os.path.join(level2_repo, 'deepCoadd', band,
                                       '0/0,0.fits'))
stamp = coadd.create(ra, dec, size)
hdu = convert_image_to_hdu(stamp)
norm = image_norm(hdu.data*scaling_factor)

fig, axes, norm = render_fits_image(hdu)
plt.savefig('coadd_%(objectId)i.png' % locals())
plt.close(fig)

# Generate the png files for each visit.
for visit in visits:
    print("working on", visit)
    sys.stdout.flush()
    maker = PostageStampMaker(os.path.join(level2_repo, 'deepCoadd', band,
                                           '0/0,0tempExp',
                                           'v%i-fu.fits' % visit))
    stamp = maker.create(ra, dec, size)
    hdu = convert_image_to_hdu(stamp)
    title = 'objectId: %(objectId)i; visit: %(visit)7i' % locals()
    fig, axes, norm = render_fits_image(hdu, title=title, norm=norm)
    plt.savefig(output_dir('stamp_%07i.png' % visit))
    plt.close(fig)

# Create the gif movie.
command = 'convert -delay 20 -loop 0 %(tempdir)s/stamp*.png objectId_%(objectId)i.gif' % locals()
print(command)
subprocess.call(command, shell=True)


from DispositivoEntrada import DispositivoEntrada

class Raton(DispositivoEntrada):
    contadorRatones = 0

    def __init__(self, tipoEntrada, marca):
        super().__init__(tipoEntrada, marca)
        self._idRaton = Raton.aumentarId()

    @classmethod
    def aumentarId(cls):
        cls.contadorRatones += 1
        return cls.contadorRatones

    def __str__(self):
        return f'Ratón: Id: {self._idRaton}, {super().__str__()}'

# Para testear
if __name__ == '__main__':
    raton1 = Raton('USB', 'Razer')
    raton2 = Raton('PS2', 'Genius')
    raton3 = Raton('Bluetooth', 'Sarasa')

    print(raton1)
    print(raton2)
    print(raton3)


""" Produce ensemble Sm 2 abundances from the Gaia-ESO Survey iDR4 WG11 data """

__author__ = 'Andy Casey <arc@ast.cam.ac.uk>'

import release

database, element, ion = ("arc", "Sm", 2)
ges = release.DataRelease(database)

# 9 lines available from two nodes (MyGIsFOS and ULB)
# No lines in common.
# Solar abundances available are reasonable for both nodes.

# 4836.7 line (ULB) should not be used.
# 4929.6 line should not be used.
# Lines greater than 3 should be removed.

flag_id = ges.flags.retrieve_or_create("Abundance is non-physical")
num_rows = ges.flags.update([flag_id],
    """SELECT id FROM line_abundances WHERE element = '{0}' AND ion = '{1}' AND
        (abundance > 3)""".format(element, ion))

flag_id = ges.flags.retrieve_or_create(
    "Not an ideal line for analysis")
num_rows = ges.flags.update([flag_id],
    """SELECT id FROM line_abundances WHERE element = '{0}' AND ion = '{1}'
    AND wavelength > 4836 AND wavelength < 4837""".format(element, ion))

num_rows = ges.flags.update([flag_id],
    """SELECT id FROM line_abundances WHERE element = '{0}' AND ion = '{1}'
    AND wavelength > 4929 AND wavelength < 4930""".format(element, ion))

# No differential biases available. Solar biases are available for some lines.
"""
# Calculate biases and apply them.
species_biases = ges.biases.differential(element, ion)
for node in species_biases:
    for wavelength, (bias, sigma, N) in species_biases[node].items():
        rows = ges.biases.apply_offset(element, ion, node, wavelength, -bias)
"""

# Perform the homogenisation.
ges.homogenise.species(element, ion)


import urllib
import sys
import time
import csv
import re
import os

LOCATION_URL="http://nok.fxexchangerate.com/"

regex2="(\S*\d+\s\w+\s\=\s[^\s]*.*[NOK])<br/>"
m2 = re.compile(regex2)
foundfirst=False
foundsecond=False
fromto=["USD","GBP","EUR","SGD","JPY"]
now = time.strftime("%c")
for currency in fromto:
        response = urllib.urlopen(LOCATION_URL+ currency + ".xml")
        lines = response.readlines()
        output_string=""

        # Build the output from the web query as a string
        for line in lines:
                #print("Current line: "+line)
                mymatch2 = m2.search(line)
                if mymatch2:
                        value=mymatch2.group(1)
                        if not foundfirst:
                                foundfirst=True
                                output_string=output_string + " " + "Convert:"  + value + "\n"
                                continue
                        else:
                                foundsecond=True
                                output_string=output_string + " " + "Convert:" + value + "\n"
                                break

        sys.stdout.write(now)
        sys.stdout.write(output_string)
        time.sleep(1)


import datetime

from protorpc import message_types
from protorpc import remote

from multitest_transport.api import base
from multitest_transport.models import config_encoder
from multitest_transport.models import messages
from multitest_transport.models import ndb_models
from multitest_transport.util import env

@base.MTT_API.api_class(resource_name='node_config', path='node_config')
class NodeConfigApi(remote.Service):
  """A handler for Node Config API."""

  @base.ApiMethod(message_types.VoidMessage, messages.NodeConfig,
                  http_method='GET', path='/node_config', name='get')
  def Get(self, request):
    """Fetches the server's node configuration."""
    node_config = ndb_models.GetNodeConfig()
    return messages.Convert(node_config, messages.NodeConfig)

  @base.ApiMethod(messages.NodeConfig, messages.NodeConfig,
                  http_method='PUT', path='/node_config', name='update')
  def Update(self, request):
    """Updates the server's node configuration.

    Body:
      Node configuration data
    """
    node_config = messages.Convert(
        request, ndb_models.NodeConfig, messages.NodeConfig)
    node_config.put()
    return messages.Convert(node_config, messages.NodeConfig)

  @base.ApiMethod(message_types.VoidMessage, messages.SimpleMessage,
                  http_method='GET', path='export', name='export')
  def ExportConfigData(self, request):
    """Exports the server's node configuration."""
    config_set = config_encoder.ConfigSet(
        node_config=ndb_models.GetNodeConfig(),
        build_channels=ndb_models.BuildChannelConfig.query().fetch(),
        device_actions=ndb_models.DeviceAction.query().fetch(),
        test_run_actions=ndb_models.TestRunAction.query().fetch(),
        tests=ndb_models.Test.query().fetch(),
        file_cleaner=ndb_models.GetFileCleanerSettings())
    header = '# MTT Configuration - %s - %s\n' % (
        env.HOSTNAME, datetime.datetime.now())
    data = config_encoder.Encode(config_set)
    return messages.SimpleMessage(value=header + data)

  @base.ApiMethod(messages.SimpleMessage, message_types.VoidMessage,
                  http_method='POST', path='import', name='import')
  def ImportConfigData(self, request):
    """Imports another server's node configuration.

    Body:
      Exported node configuration data
    """
    config_set = config_encoder.Decode(request.value)
    config_encoder.Load(config_set)
    return message_types.VoidMessage()


from Tests.all_tests import run_tests
from Logic.sales_manager import SalesManager
from UserInterface.menu import Menu
from UserInterface.command_line import CommandLine

def main():
    run_tests()

    a = '\033[96m'
    n = '\033[0m'

    interface_type = input(f"Ce fel de interfata vrei sa folosesti?\nCommand line {a}(c){n} sau Meniu {a}(m){n}?")

    sales_manager = SalesManager()

    if interface_type == "c":
        command_line = CommandLine(sales_manager)
        command_line.run()
    elif interface_type == "m":
        menu = Menu(sales_manager)
        menu.run()

if __name__ == "__main__":
    main()


import re
import subprocess
from types import ModuleType

import reusables
import wx
from wx.adv import TaskBarIcon
import logging
import argparse

class AudioController:
    def __init__(self):
        # Recover configs
        config = reusables.config_dict("config.ini")
        self.name_device_a = config["device_a"]["name"]
        self.name_device_b = config["device_b"]["name"]
        self.icon_device_a = config["device_a"]["icon"]
        self.icon_device_b = config["device_b"]["icon"]

    @staticmethod
    def _force_portaudio_reload(sounddevice: ModuleType) -> None:
        """Cause the PortAudio library inside the given sounddevice module to be reloaded.

        Without doing this the default device is not refreshed after changing it."""
        sounddevice._ffi.dlclose(sounddevice._lib)
        sounddevice._lib = sounddevice._ffi.dlopen(sounddevice._libname)
        sounddevice._lib.Pa_Initialize()

    def get_default_device_name(self) -> str:
        import sounddevice

        # force sounddevice to reload the default device from the PortAudio dll
        # noinspection PyTypeChecker
        self._force_portaudio_reload(sounddevice)
        # now get the raw name of the device
        idd = sounddevice.default.device[1]
        raw_name = sounddevice.query_devices(idd)["name"]
        # extract the name and return it
        matches = re.finditer(r".*(?= \()", raw_name, re.MULTILINE)
        return next(matches).group()

    def set_default_device(self, device_name: str) -> None:
        subprocess.run(
            ["nircmd.exe", "setdefaultsounddevice", "{}".format(device_name)]
        )

    def toggle_between_devices(self) -> None:
        default_device_name = self.get_default_device_name()
        if default_device_name == self.name_device_a:
            self.set_default_device(self.name_device_b)
        else:
            self.set_default_device(self.name_device_a)

    def open_sound_panel(self, event):
        subprocess.run(["control", "mmsys.cpl", "sounds"])

def create_menu_item(menu, label, func):
    item = wx.MenuItem(menu, -1, label)
    menu.Bind(wx.EVT_MENU, func, id=item.GetId())
    menu.Append(item)
    return item

class MyTaskBarIcon(TaskBarIcon):
    def __init__(self, frame):
        self.AC = AudioController()
        self.frame = frame
        super(TaskBarIcon, self).__init__()
        self.set_icon()
        self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        create_menu_item(menu, "Open Sound Panel", self.AC.open_sound_panel)
        menu.AppendSeparator()
        create_menu_item(menu, "Exit", self.on_exit)
        return menu

    def set_icon(self):
        default_device_name = self.AC.get_default_device_name()
        logging.debug(f"Current default device name: {default_device_name}")
        if default_device_name == self.AC.name_device_a:
            path = self.AC.icon_device_a
            tooltip = self.AC.name_device_a
        else:
            path = self.AC.icon_device_b
            tooltip = self.AC.name_device_b
        logging.debug(f"Setting icon to: {path}")
        icon = wx.Icon(wx.Bitmap(path))
        self.SetIcon(icon, tooltip)
        logging.debug(f"Icon set")

    def on_left_down(self, event):
        self.AC.toggle_between_devices()
        # Wait a bit to make sure nircmd finish toggling the sound device before updating the icon
        wx.CallLater(int(500), self.set_icon)

    def on_exit(self, event):
        wx.CallAfter(self.Destroy)
        self.frame.Close()

class App(wx.App):
    def OnInit(self):
        frame = wx.Frame(None)
        self.SetTopWindow(frame)
        MyTaskBarIcon(frame)
        return True

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
                        prog = 'ToggleAudioTrayIcon',
                        description = 'A tray icon to quickly toggle default audio device.')
    parser.add_argument('-d', '--debug', action='store_true', help="print debug message to a log file")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            filename="ToggleAudioTrayIcon_debug_logs.txt",
            filemode="a",
            format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
            datefmt="%H:%M:%S",
            level=logging.DEBUG,
        )
        logging.debug("START")

    app = App(False)
    app.MainLoop()


import sys

class ShortestPath:
    def floyd(self, V, edges):
        dist = [[sys.maxsize for _ in range(V)] for _ in range(V)]

        for u in range(V):
            for w in range(V):
                if edges[u][w]:
                    dist[u][w] = edges[u][w]
        for u in range(V):
            dist[u][u] = 0

        for k in range(V):
            for i in range(V):
                for j in range(V):
                    if dist[i][k] != sys.maxsize and dist[k][j] != sys.maxsize and dist[i][k] + dist[k][j] < dist[i][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        print(dist)

def main():
    V = 4
    edges = [[None for _ in range(4)] for _ in range(4)]
    edges[0][2] = -2
    edges[1][0] = 4
    edges[1][2] = 3
    edges[2][3] = 2
    edges[3][1] = -1

    shortest = ShortestPath()
    shortest.floyd(V, edges)

if __name__ == '__main__':
    main()


import subprocess
import time
import whois
from ip2geotools.databases.noncommercial import DbIpCity
import dns.resolver
import urllib.request
import requests
import re
import time
import platform
import socket
from bs4 import BeautifulSoup as bs
from Wappalyzer import Wappalyzer, WebPage
import warnings
import sys
import os
import phonenumbers
from phonenumbers import geocoder, carrier
from colorama import Fore, Style, init
init()

def banner():
    print(Fore.RED + """
  ____        _     _         __        __   _             _
 / ___| _ __ (_) __| | ___ _ _\ \      / /__| |__   __   _/ |
 \___ \| '_ \| |/ _` |/ _ \ '__\ \ /\ / / _ \ '_ \  \ \ / / |
  ___) | |_) | | (_| |  __/ |   \ V  V /  __/ |_) |  \ V /| |
 |____/| .__/|_|\__,_|\___|_|    \_/\_/ \___|_.__/    \_/ |_|
       |_|
    \t\t[Coded By: BlackSheep4]
    """)
    print(Style.RESET_ALL)

def main():
    print('\n' + "Welcome to SpiderWeb v1 - Information Gathering Tool" + '\n')

    print(Fore.RED + "\t[" + Fore.GREEN + "01" + Fore.RED + "] " + Fore.WHITE + "Operative System Detection")
    print(Fore.RED + "\t[" + Fore.GREEN + "02" + Fore.RED + "] " + Fore.WHITE + "WHOIS Information")
    print(Fore.RED + "\t[" + Fore.GREEN + "03" + Fore.RED + "] " + Fore.WHITE + "Target Geolocation")
    print(Fore.RED + "\t[" + Fore.GREEN + "04" + Fore.RED + "] " + Fore.WHITE + "DNS Dumping")
    print(Fore.RED + "\t[" + Fore.GREEN + "05" + Fore.RED + "] " + Fore.WHITE + "Robots.txt Extraction")
    print(Fore.RED + "\t[" + Fore.GREEN + "06" + Fore.RED + "] " + Fore.WHITE + "Get all the links from the target")
    print(Fore.RED + "\t[" + Fore.GREEN + "07" + Fore.RED + "] " + Fore.WHITE + "Server Detection")
    print(Fore.RED + "\t[" + Fore.GREEN + "08" + Fore.RED + "] " + Fore.WHITE + "Server Technologies Detection")
    print(Fore.RED + "\t[" + Fore.GREEN + "09" + Fore.RED + "] " + Fore.WHITE + "Phone Information Extractor")
    print(Fore.RED + "\n\t[" + Fore.GREEN + "10" + Fore.RED + "] " + Fore.WHITE + "Exit")
    print('\n')
    option = int(input("[+] Choose an option >> "))
    print(Style.RESET_ALL)

    int(option)

    if option == 1:
        target = str(input("[+] Target Domain >> "))
        url = f'http://www.{target}/'
        system = platform.system()
        target2 = socket.gethostbyname(target)

        if system == 'Linux':
            try:
                print('[!] GETTING OPERATIVE SYSTEM')
                time.sleep(1)
                ping = subprocess.Popen(f"ping -c 1 {target2}",shell=True,  stdout=subprocess.PIPE)
                out = ping.communicate()[0] #access stdoutdata
                out = out.split() #split by spaces
                out = str(out)

                ttl = re.search(r'ttl=(\d+)', out).group(1)
                ttl= int(ttl)

                if ttl >= 0 and ttl <= 64:
                    print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Server Operative System: " + Fore.GREEN + "LINUX")
                    print(Style.RESET_ALL)
                elif ttl >= 65 and ttl <= 128:
                    print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Server Operative System: " + Fore.GREEN + "WINDOWS")
                    print(Style.RESET_ALL)
                else:
                    print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Server Operative System:" + Fore.GREEN + "UNKOWN")
                    print(Style.RESET_ALL)

                input('\n' + "Press any key to continue...")
                os.system('clear')

            except (AttributeError):
                print('\n')
                print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + 'An error occurred. It is possible that the server is down or that you have misspelled the IP or domain.')

        else:
            print('Please use this script in Linux OS')
            input('\n' + "Press any key to continue...")
            os.system('clear')

    elif option == 2:

        target = str(input("[+] Target Domain >> "))

        w = whois.whois(target)
        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + f"Getting WHOIS Information from {target}")
        time.sleep(0.5)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Domain Names: " + str(w.get("domain_name")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Domain Name Servers: " + str(w.get("name_servers"))[2:-2])
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Organization: " + str(w.get("org")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Registration: " + str(w.get("registrar")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Emails: " + str(w.get("emails")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "DNSSec: " + str(w.get("dnssec")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Country: " + str(w.get("country")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "State: " + str(w.get("state")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "City: " + str(w.get("city")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Zipcode: " + str(w.get("zipcode")))
        time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Address: " + str(w.get("address")))

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 3:

        target = str(input("[+] Target Domain >> "))
        target2 = socket.gethostbyname(target)

        response = DbIpCity.get(target2, api_key="free")
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Tracking IP Location")
        time.sleep(0.5)
        latitude = response.latitude
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Latitude: " + str(response.latitude))
        time.sleep(0.3)
        longitude = response.longitude
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Longitude: " + str(response.longitude))
        time.sleep(0.3)
        print("[+] Google Maps Track: " + f"https://google.es/maps/@{latitude},{longitude},15z?hl=en")

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 4:

        target = str(input("[+] Target Domain >> "))

        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Starting DNS Dumping")
        mx = dns.resolver.resolve(target, 'MX')
        soa = dns.resolver.resolve(target, 'SOA')
        ns = dns.resolver.resolve(target, 'NS')
        time.sleep(0.5)

        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "DUMPING MX SERVERS")
        for data in mx:
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "MX Servers: " + str(data.exchange) + "\t" + " PREFERENCE: " + str(data.preference))
            time.sleep(0.3)
        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "DUMPING DOMAIN NAME SERVERS")
        for data in ns:
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Domain Name Servers: " + str(data.target))
            time.sleep(0.3)

        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "DUMPING PRIMARY ZONE DOMAIN")
        for data in soa:
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "DNS Primary Zone: " + str(data.mname))
            time.sleep(0.3)

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 5:

        target = str(input("[+] Target Domain >> "))

        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "Trying to get robots.txt")

        robots = f'http://www.{target}/robots.txt'
        file = "robots.txt"

        request = requests.get(robots)
        if request.status_code == 200:
            r = urllib.request.urlopen(robots)
            f = open(file, 'wb')
            f.write(r.read())
            f.close
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "File Successfully Downloaded!")
        else:
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + f"Seems that {target} doesn´t have any robots.txt")

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 6:

        target = str(input("[+] Target Domain >> "))
        url = f'http://www.{target}/'

        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + f"Getting all links from {target} ")

        req = requests.get(url)
        soup = bs(req.text, 'html.parser') #transform request to unicode and parse to HTML

        for link in soup.find_all('a'):
            time.sleep(0.2)
            print(link.get('href'))

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 7:

        target = str(input("[+] Target Domain >> "))
        url = f'http://www.{target}/'

        r = requests.get(url)
        server = r.headers['Server']
        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "Getting the Type of Server... ")
        time.sleep(0.5)
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Server: " + str(server))

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 8:

        target = str(input("[+] Target Domain >> "))
        url = f'http://www.{target}/'

        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "Detecting Technologies...")
        #STUPID WARNING XD
        warnings.filterwarnings("ignore", message="""Caught 'unbalanced parenthesis at position 119' compiling regex""", category=UserWarning )

        wappalyzer = Wappalyzer.latest()
        webpage = WebPage.new_from_url(url)
        technologies = wappalyzer.analyze(webpage)
        for t in technologies:
            time.sleep(0.5)
            print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Technology Detected: {}".format(t))

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 9:
        target = str(input("[+] Phone Target (+12345678901) >> "))
        phone = phonenumbers.parse(target)
        carrier2 = carrier.name_for_number(phone, 'en')
        region = geocoder.description_for_number(phone, 'en')
        possible = phonenumbers.is_possible_number(phone)

        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Phone Number Validation: " + str(possible))
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "General Information: "+ str(phone))
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Carrier: " + str(carrier2))
        print(Fore.RED + "[" + Fore.GREEN + "+" + Fore.RED + "] " + Fore.WHITE + "Country: " + str(region))

        input('\n' + "Press any key to continue...")
        os.system('clear')

    elif option == 10:
        print(Fore.RED + "[" + Fore.GREEN + "!" + Fore.RED + "] " + Fore.WHITE + "Exiting")
        sys.exit()

    else:
        print("WTF are you trying dude? Select a number of the menu!")

if __name__ == '__main__':
    try:
        while True:
            banner()
            main()
    except:
        print('[!] Stopping the scanner...')
        sys.exit(1)


import numpy as np
import pandas as pd

from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import confusion_matrix

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
from keras.layers import Conv1D, MaxPooling1D,GlobalAveragePooling1D
from sklearn.feature_extraction.text import CountVectorizer
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM
from sklearn.model_selection import train_test_split
from keras.utils.np_utils import to_categorical
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.models import model_from_json
import re
import warnings
warnings.filterwarnings('ignore')
from subprocess import check_output
print(check_output(["ls", "\path"]).decode("utf8"))

import nltk
import os
import gc
from keras.preprocessing import sequence,text
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense,Dropout,Embedding,LSTM,Conv1D,GlobalMaxPooling1D,Flatten,MaxPooling1D,GRU,SpatialDropout1D,Bidirectional,Conv2D
from keras.callbacks import EarlyStopping
from tensorflow.keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,confusion_matrix,classification_report,f1_score
import matplotlib.pyplot as plt
import warnings
# Preprocessing
from sklearn import preprocessing
from sklearn.utils import class_weight as cw
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from bs4 import BeautifulSoup
# Time
import time
import datetime
from tensorflow.keras.optimizers import RMSprop,Adam
from tensorflow.keras.optimizers import Adam
###########################
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, ReduceLROnPlateau
# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
###########################
import string
import re
from nltk.corpus import stopwords
#########################
from tensorflow.keras import layers
from tensorflow.keras import regularizers
from tensorflow.keras.layers import BatchNormalization
from keras.regularizers import l2
from tensorflow.keras.utils import to_categorical

# Date and time
def date_time(x):
    if x==1:
        return 'Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
    if x==2:
        return 'Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now())
    if x==3:
        return 'Date now: %s' % datetime.datetime.now()
    if x==4:
        return 'Date today: %s' % datetime.date.today()

input_directory = r"../input/"
output_directory = r"../output/"

if not os.path.exists(output_directory):
    os.mkdir(output_directory)

figure_directory = "../output/figures"
if not os.path.exists(figure_directory):
    os.mkdir(figure_directory)

file_name_pred_batch = figure_directory+r"/result"
file_name_pred_sample = figure_directory+r"/sample"

data = pd.read_csv('\path\dataset')
data.columns

data = data[['text', 'sentiment']]
data.head()

import nltk
nltk.download('punkt')

import nltk
nltk.download('stopwords')

import nltk
nltk.download('wordnet')

##The_stopword
all_stopwords = stopwords.words('arabic')
sw_list = [
'إذ', 'إذا','إذما', 'اذن', 'إذن', 'أف', 'أقل', 'كتر', 'اجو', 'اتلم', 'كثر', 'اكثروا', 'اكثرة',
'اكثرا', 'أكثر', 'الا', 'ألا', 'إلا', 'التي', 'الذي', 'الذين', 'اللاتي', 'اللائي', 'اللتان', 'اللتيا', 'اللتين', 'اللذان', 'اللذين', 'اللواتي', 'إلى', 'إليك', 'إليكم', 'إليكما', 'إليكم', 'إليكن', 'أم', 'أما', 'أما', 'إما', 'آما', 'ان', 'أن',
 'إن', 'إنا', 'أنا', 'انا', 'انتي', 'أنتي', 'أنت', 'أنتت', 'أنتما', 'أنتم', 'أنتما', 'أنتن', 'أنما', 'إنما', 'إنه', 'أنني', 'آه', 'آها', 'أو', 'آوو', 'اوو ', 'او', 'أولاء', 'أولئك ', 'أوه', 'آي', 'أي', 'أيهم', 'أيتها', 'أيها', 'ايي',
'إي', 'أين', 'أين', 'أينما', 'إيه', 'بخ', 'برا روح', 'بتاع', 'بب', 'بابا', 'بعدين', 'بر', 'بلاي', 'بح', 'بس', 'بعد', 'بعض', 'بك', 'بكي', 'بيكم', 'بكم', 'بكما', 'بكن', 'بل', 'بلى', 'بما', 'بماذا', 'بمن', 'بنا', 'به', 'بها',
 'بهم', 'بهما', 'بهن', 'بي', 'بين', 'بيد', 'تلك', 'تلكم', 'تلكما', 'ته', 'تي', 'تين', 'ثم', 'ثمة', 'جاب', 'جة', 'حط', 'خد', 'رابعه', 'راح', 'رح', 'شال', 'صح', 'طخ', 'عااا', 'كدا', 'ليل', 'حاشا', 'حبذا', 'حتى', 'حيث',
' حيثما', 'حين', 'خلا', 'دون', 'ذا', 'ذات', 'ذاك', 'ذان', 'ذانك',
 'ذلك','ذلكم', 'ذلكما', 'ذلكن', 'ذه', 'ذو', 'ذوا', 'ذواتا', 'ذواتي', 'ذي', 'ذين', 'ذينك', 'ريثما', 'ريث', 'سوف', 'سوو', 'سواء', 'سوا', 'سوى ', 'شتان', 'عدا', 'عسى', 'عل', 'على', 'عبر', 'عنا', 'عليك', 'عليكي', 'عليكما',
 'عليكم', 'عليه', 'علا', ' عما', 'عن', 'عند', 'فإذا', 'فإن', 'فلا', 'فمن', 'في', 'فيم', ' فيما', 'فينكم', ' فينم', 'فين', 'فيهما', 'فيهم', 'فيه', 'فيها', ' قد', ' كأنهم', ' كأن', ' كأنما', ' كأي', ' كأين', ' وكدا', ' كذا', 'كذلك', ' كل',
 ' كلا', ' كلاهما', ' كلتا', ' كلما', ' كليكما', ' كليهما', ' كم', ' كما', ' كي', ' كيت', ' كيف', ' كيفما', ' لا', ' ليالي', ' لا لا لا', ' لسا', 'لاسيما', ' لدى', ' لسه', ' لستي', ' لست', ' لستما', ' لستم', ' لستما', 'لستن', ' لسن'
 ' لسنا', ' لعل', ' لك', ' لكم', ' لكما', ' لكن', ' لكنما', 'لكي', ' لكيلا', ' لم', ' لما', ' لن', ' لنا', ' له', ' لها', ' لهم', ' لهما', 'لهن', ' لو', ' لولا', ' لوما', ' لي', ' لئن', ' ليت', ' ليس', ' ليسا', ' ليست', ' ليستا',
 ' هع', ' هم', ' هاتان', ' هاته', ' هاتي', ' هاتين', ' هاك', ' هاهنا' , 'هذه', ' هذي', ' هذين', ' هكذا', ' هل', ' هلا', ' هم', ' هما', ' هن', ' هنا', 'هناك', ' هنالك', ' هو', ' هؤلاء', 'هي', ' هيا', ' هيت', 'هيهات',
' والذين', ' وإذ', ' وإذا', ' وإن', ' ولا', ' ولكن', ' ولو', ' وما', 'ومن', ' وهو', ' وله', ' واد', ' وه', ' يا', ' ااا', ' أبريل', ' أبو', ' أبٌ ', ' أجل ', ' جمع ', ' أحد ', ' أخبر', ' أخذ', ' أخو ', ' أخٌ ', ' أربع ', 'أحمر',
' أرح ', ' أربعا', ' أبكي', ' أرى', ' أسكن', ' أصبح', ' أصلا', ' أضحى', ' أطعم', ' أكتوبر', ' أعطى', ' أعلم', ' أغسطس', ' أفريل', ' أفعل به', ' أفٍّ ', ' ألف', ' ألفى', ' ألوف', ' أم', ' أما', 'أمام', ' أمامك', ' أمامكي', ' أمامكما',
' أمامكم', ' أمامكَ', ' أمد', ' أمس', ' أمسى', ' مسا', ' امسا', ' تج', ' تحوّل', ' تحط', ' تخذ', ' ترك', ' تاني', ' تسع', ' تسعة', ' تسعين', ' تشرين', ' تعسا', ' تعلَّم', ' تفعلان', ' تفعلا', ' تفعلين', ' تفعلوا', ' تفعلون', ' تفعلين',
' جانفي', ' جعل', ' جلل', ' جمعة', ' جميع', ' جنيه', ' جوان', ' جويلية',
 ' جير', ' ء', ' سابع', ' سادس', ' سبت', ' سبتمبر', ' سبحان', ' سبع', ' سبح', ' سير ', ' ست', ' ستة', ' ستكون', ' ستمئة', ' ستمائة', ' ستون', ' ستين', ' سحقا', ' سرا', ' سرعان', ' سقى ', ' سمعا', ' سنة', ' سنتيم', ' سنين',
' سنوات', ' سوف', ' سوى', ' سين', ' صارِ', ' صباح', ' صبر', ' صبرا', ' صبرو', ' صدقا', ' صراحة', ' صفر', ' صهٍ', ' صهْ', ' ض', ' ضاد', ' ضحوة', ' ضد', ' ضامن', ' ضمن', ' ط', ' طاء', 'طاق', 'ّ طالما', ' طرا', ' طفق', 'ّ طَق', ' عشرة',
' عشرات', 'عشرون', ' عشرين', ' عل', ' علق', ' علم', ' ه ', ' ما انفك', ' ما برح', ' مادام', ' مادامو'
, ' مادمنا', ' ماذا', ' ماما', ' متر', ' مرة',' مرات', ' مارس', ' مازال', ' مازالو', ' مازالنا', ' ماي', ' مايزال', ' مايزل', ' مايو', ' مافتئ', ' متىِ', ' مثل', ' مذ', ' مرات', ' مرّة', ' مساء', ' يفعلون', ' يكون', ' يلي', ' يمكن', ' يمين', ' ين', ' يناير',
' يورو', ' يوليو', ' يومان', ' يونيو', ' يوان'
]
all_stopwords.extend(sw_list)

## pre-processing steps
'''
'''
    # Punctiations

punctuations = '''`÷×؛<>_()*&^%][ـ،/:"؟.,'{}~¦+|!”…“–ـ''' + string.punctuation

stop_words = stopwords.words()

    #diacritics
arabic_diacritics = re.compile("""
                             ّ    | # Shadda
                             َ    | # Fatha
                             ً    | # Tanwin Fath
                             ُ    | # Damma
                             ٌ    | # Tanwin Damm
                             ِ    | # Kasra
                             ٍ    | # Tanwin Kasr
                             ْ    | # Sukun
                             ـ     # Tatwil/Kashida
                         """, re.VERBOSE)

def preprocess(text ):

    '''
    Arabic text is entered as a string, and the preprocessed text is output.
    '''

    #remove punctuations
    translator = str.maketrans('', '', punctuations)
    text = text.translate(translator)

    # remove Tashkeel
    text = re.sub(arabic_diacritics, '', text )

    #words and corresponding emoticon
    text = re.sub("مرتبك", "o.o", text)
    text = re.sub("سعيد ", "(:", text)
    text = re.sub("وجهة سعيد جدا", "^_^", text)
    text = re.sub("غاضب", "):<", text)
    text = re.sub("بكاء", ")'：", text)
    text = re.sub("شيطاني", "(:3", text)
    text = re.sub("مللائكي", "o :) ", text)
    text = re.sub("سعيد", "8^) ", text)

    #remove normalization
    text = re.sub("[إأآا]", "ا", text)
    text = re.sub("ى", "ي", text)
    text = re.sub("ؤ", "ء", text)
    text = re.sub("ئ", "ء", text)
    text = re.sub("ة", "ه", text)
    text = re.sub("گ", "ك", text)

    text = ' '.join(word for word in text.split() if word not in stop_words)

    return text

data['text'] = data['text'].apply(preprocess)
print(data.head(5))

#spilt and encode our data
X = data.text
Y = data.sentiment

label_encoder = LabelEncoder()

Y = label_encoder.fit_transform(Y)

Y = to_categorical(Y)

#split data & calculate maxword and max lenx
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.20, random_state = 123)

max_words = len(set(" ".join(X_train).split()))
#max_len = X_train.apply(lambda x: len(x)).max()

#max_words = 2000
max_len = 100
#, 150, 120, 100
max_words, max_len

num_unique_word=max_words
MAX_REVIEW_LEN=max_len

#Hyperparameter value
max_features = num_unique_word
max_words = MAX_REVIEW_LEN
batch_size = 128
#batch_size = 500
epochs = 10
num_classes=2
embedding_size =128
# Convolution
kernel_size = 5
filters = 64
pool_size = 4

#Tokenize Text
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(X_train))
X_train = tokenizer.texts_to_sequences(X_train)
X_test = tokenizer.texts_to_sequences(X_test)

#sequence padding
X_train = sequence.pad_sequences(X_train, maxlen=max_words)
X_test = sequence.pad_sequences(X_test, maxlen=max_words)
print(X_train.shape,X_test.shape)

maxlen=max_words

#Output Configuration
main_model_dir = output_directory + r"models/"
main_log_dir = output_directory + r"logs/"

try:
    os.mkdir(main_model_dir)
except:
    print("Could not create main model directory")

try:
    os.mkdir(main_log_dir)
except:
    print("Could not create main log directory")

model_dir = main_model_dir + time.strftime('%Y-%m-%d %H-%M-%S') + "/"
log_dir = main_log_dir + time.strftime('%Y-%m-%d %H-%M-%S')

try:
    os.mkdir(model_dir)
except:
    print("Could not create model directory")

try:
    os.mkdir(log_dir)
except:
    print("Could not create log directory")

model_file = model_dir + "{epoch:02d}-val_acc-{val_acc:.2f}-val_loss-{val_loss:.2f}.hdf5"

print("Settting Callbacks")

checkpoint = ModelCheckpoint(
    model_file,
    monitor='val_acc',
    save_best_only=True)

early_stopping = EarlyStopping(
    monitor='val_loss',
    patience=3,
    verbose=1,
    restore_best_weights=True)

reduce_lr = ReduceLROnPlateau(
    monitor='val_loss',
    factor=0.5,
    patience=1,
    verbose=1)

callbacks = [checkpoint, reduce_lr, early_stopping]

callbacks = [early_stopping]

print("Set Callbacks at ", date_time(5))

def plot_performance(history=None, figure_directory=None, ylim_pad=[0, 0]):
    xlabel = 'Epoch'
    legends = ['Training', 'Validation']

    plt.figure(figsize=(20, 5))

    y1 = history.history['accuracy']
    y2 = history.history['val_accuracy']

    min_y = min(min(y1), min(y2))-ylim_pad[0]
    max_y = max(max(y1), max(y2))+ylim_pad[0]

    plt.subplot(121)

    plt.plot(y1)
    plt.plot(y2)

    plt.title('Model Accuracy\n'+date_time(1), fontsize=17)
    plt.xlabel(xlabel, fontsize=15)
    plt.ylabel('Accuracy', fontsize=15)
    plt.ylim(min_y, max_y)
    plt.legend(legends, loc='upper left')
    plt.grid()

    y1 = history.history['loss']
    y2 = history.history['val_loss']

    min_y = min(min(y1), min(y2))-ylim_pad[1]
    max_y = max(max(y1), max(y2))+ylim_pad[1]

    plt.subplot(122)

    plt.plot(y1)
    plt.plot(y2)

    plt.title('Model Loss\n'+date_time(1), fontsize=17)
    plt.xlabel(xlabel, fontsize=15)
    plt.ylabel('Loss', fontsize=15)
    plt.ylim(min_y, max_y)
    plt.legend(legends, loc='upper left')
    plt.grid()
    if figure_directory:
        plt.savefig(figure_directory+"/history")

    plt.show()

# word embedding
def get_coefs(word, *arr):
    return word, np.asarray(arr, dtype='float32')

def get_embed_mat(EMBEDDING_FILE, max_features,embed_dim):
    # word vectors
    embeddings_index = dict(get_coefs(*o.rstrip().rsplit(' ')) for o in open(EMBEDDING_FILE, encoding='utf8'))
    print('Found %s word vectors.' % len(embeddings_index))

    # embedding matrix
    word_index = tokenizer.word_index
    num_words = min(max_features, len(word_index) + 1)
    all_embs = np.stack(embeddings_index.values()) #for random init
    embedding_matrix = np.random.normal(all_embs.mean(), all_embs.std(),
                                        (num_words, embed_dim))
    for word, i in word_index.items():
        if i >= max_features:
            continue
        embedding_vector = embeddings_index.get(word)
        if embedding_vector is not None:
            embedding_matrix[i] = embedding_vector
    max_features = embedding_matrix.shape[0]

    return embedding_matrix

#MC1 Model
model20= Sequential()
model20.add(Embedding(max_features, embedding_size, input_length=maxlen))
model20.add(Dropout(0.5))
model20.add(Conv1D(512, kernel_size=3,padding='same',activation='relu',strides=1))
model20.add(GlobalAveragePooling1D())
model20.add(Dropout(0.5))
model20.add(Dense(
    units=256,
    kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4),
    bias_regularizer=regularizers.l2(1e-4),
    activity_regularizer=regularizers.l2(1e-5)
))
model20.add(BatchNormalization())
model20.add(Dropout(0.5))
model20.add(Dense(2,activation='softmax'))
model20.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
model20.summary()

loss = 'categorical_crossentropy'
# loss = 'binary_crossentropy'
metrics = ['accuracy']

start_time = time.time()
print(date_time(1))
history3=model20.fit(X_train, Y_train, validation_data=(X_test, Y_test),epochs=20, batch_size=batch_size, verbose=1)
elapsed_time = time.time() - start_time
elapsed_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
print("\nElapsed Time: " + elapsed_time)
print("Completed Model Trainning", date_time(1))
#epochs=50,100,200,500

#Visualization
plot_performance(history=history3)

#MC2 Model
model4= Sequential()
model4.add(Embedding(max_features, embedding_size, input_length=maxlen))
model4.add(Conv1D(128,kernel_size=3,padding='same',activation='relu'))
model4.add(MaxPooling1D(pool_size=2))
model4.add(Conv1D(64,kernel_size=3,padding='same',activation='relu'))
model4.add(MaxPooling1D(pool_size=2))
model4.add(Dropout(0.25))
model4.add(SpatialDropout1D(0.25))
model4.add(Bidirectional(GRU(128)))
model4.add(Dropout(0.5))
model4.add(Flatten())
model4.add(Dense(128,activation='relu'))
model4.add(Dropout(0.5))
model4.add(Dense(2,activation='softmax'))
model4.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.001),metrics=['accuracy'])
model4.summary()

loss = 'categorical_crossentropy'
# loss = 'binary_crossentropy'
metrics = ['accuracy']

start_time = time.time()
print(date_time(1))
history3=model4.fit(X_train, Y_train, validation_data=(X_test, Y_test),epochs=20, batch_size=batch_size, verbose=1)
elapsed_time = time.time() - start_time
elapsed_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
print("\nElapsed Time: " + elapsed_time)
print("Completed Model Trainning", date_time(1))

#Visualization
plot_performance(history=history3)


"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
"""

def find_missing_number(nums):
    n = len(nums)
    sum = n * (n+1) // 2
    diff = 0

    for i in nums:
        if i > 0:
            diff += i

    return sum - diff

def find_missing_number_maxmin(nums):
    max_num = max(nums)
    min_num = 2**32

    # find min number greater than 0
    for i in nums:
        if i < min_num and i >= 0:
            min_num = i

    for i in range(min_num, max_num + 1):
        if i not in nums:
            return i

def find_missing_number_kaz(nums):
   nums.sort(reverse=True)
   print(nums)
   for i in nums:
       mn = min(nums)
       if mn < 0:
           nums.pop()
   print(mn)
   if mn == 1 or mn == 0:
       x = mn + 1
       if x in nums:
           x = x + 1
   else:
       x = mn - 1
   return x

nums = [3, 5]
print(find_missing_number(nums))

nums = [3, 4, -1, 1]
print(find_missing_number_kaz(nums))


import tensorflow as tf

class ContentAddressing():

	@staticmethod
	def address(key, intensity, memory, epsilon=1e-6):

		# Cosine similitude
		key_mem = tf.matmul(key, tf.transpose(memory)) # (KXW) (NXW)T = (KXW)(WXN) = KXN
		norm_memory_row = tf.sqrt( tf.reduce_sum( tf.multiply(memory, memory) , 1, keep_dims=True) ) # Nx1
		norm_key = tf.sqrt( tf.reduce_sum( tf.multiply(key, key) , 1, keep_dims=True) ) # KX1

		norms_sum = tf.multiply ( norm_key , tf.transpose(norm_memory_row)) + epsilon # KXN

		similitude = tf.divide(key_mem, norms_sum) # KXN

		return tf.nn.softmax(tf.multiply(tf.transpose(intensity), similitude)) #KXN


from django.urls import path
from . import views
from .views import *

urlpatterns = [
    path('', views.home, name='school-home'),
    path('profile/', views.profile, name='school-profile'),
    path('teacher/', views.teachers, name='school-teachers'),
    path('resource/', views.resources, name='school-resources'),
    path('set_profile/', SetProfileCreateView.as_view(), name='set-school-profile'),
    path('add_profile/', SchoolCreateView.as_view(), name='add-school-profile'),
    path('add_teacher/', SchoolTeacherCreateView.as_view(), name='add-school-teacher'),
    path('register_teacher/', TeacherCreateView.as_view(), name='register-teacher'),
    path('view_teachers/', SchoolTeacherListView.as_view(), name='view-school-teachers'),
    path('profile/<int:pk>/update/', SchoolProfileUpdateView.as_view(), name='update-school-profile'),
    path('teacher/<int:pk>/update/', SchoolTeacherUpdateView.as_view(), name='update-school-teacher'),
    path('teacher/<int:pk>/', SchoolTeacherDetailView.as_view(), name='school-teacher-details'),
    path('add_resource/', SchoolResourceCreateView.as_view(), name='add-school-resource'),
    path('resource/<int:pk>/update/', SchoolResourceUpdateView.as_view(), name='update-school-resource'),
    path('view_resources/', SchoolResourceListView.as_view(), name='view-school-resources'),
    path('resource/<int:pk>/', SchoolResourceDetailView.as_view(), name='school-resource-details'),
    path('student/', views.students, name='students'),
    path('add_students/enrolments/', views.add_students, name='add-students'),
    path('add_students/repeaters/', views.add_repeaters, name='add-repeaters'),
    path('view_students/repeaters/', views.view_repeaters, name='view-repeaters'),
    path('add_students/nationality/', views.add_nationality, name='add-nationality'),
    path('view_students/nationality/', views.view_nationality, name='view-nationality'),
    path('add_students/physical_streams/', views.add_physical_streams, name='add-physical-streams'),
    path('view_students/physical_streams/', views.view_physical_streams, name='view-physical-streams'),
    path('add_students/orphans/', views.add_orphans, name='add-orphans'),
    path('view_students/orphans/', views.view_orphans, name='view-orphans'),
    path('add_students/special_needs/', views.add_special_needs, name='add-special-needs'),
    path('view_students/special_needs/', views.view_special_needs, name='view-special-needs'),
    path('add_students/seating_and_writing_space/', views.add_seating_and_writing_space, name='add-seating-and-writing-space'),
    path('view_students/seating_and_writing_space/', views.view_seating_and_writing_space, name='view-seating-and-writing-space'),
    path('add_students/transfered_students/', views.add_transfered_students, name='add-transfered-students'),
    path('view_students/transfered_students/', views.view_transfered_students, name='view-transfered-students'),
    path('add_students/examinations/', views.add_examinations, name='add-examinations'),
    path('view_students/examinations/', views.view_examinations, name='view-examinations'),
    path('add_students/proposed_intake/', views.add_proposed_intake, name='add-proposed-intake'),
    path('view_students/proposed_intake/', views.view_proposed_intake, name='view-proposed-intake'),
    path('add_students/new_entrants/', views.add_new_entrants, name='add-new-entrants'),
    path('view_students/new_entrants/', views.view_new_entrants, name='view-new-entrants'),
    path('student/<int:pk>/update/', StudentUpdateView.as_view(), name='update-student'),
    path('view_students/enrolments/', views.view_students, name='view-students'),
    path('left_teachers/', views.add_left_teachers, name='add-left-teachers'),
    path('non_teaching_staff/', views.add_non_teaching_staff, name='add-non-teaching-staff'),
    path('teacher_allocation/', views.teacher_allocation, name='teacher-allocation'),
    path('add_buildings/', views.add_buildings, name='add-buildings'),
    path('add_buildings_under_construction/', views.add_buildings_under_construction,
        name='add-buildings-under-construction'),
    path('add_buildings_needed/', views.add_rooms_needed, name='add-buildings-needed'),
    path('add_latrines/', views.add_latrines, name='add-latrines'),
    path('add_water_and_energy/', views.add_water_and_energy_sources, name='add-water-and-energy-sources'),
    path('request_teacher/', RequestTeacherCreateView.as_view(), name='request-teacher'),
    path('request_teacher/<int:pk>/update/', RequestTeacherUpdateView.as_view(), name='update-teacher-request'),
    path('request_teacher/view/', RequestTeacherListView.as_view(), name='teacher-requests'),
]


from django.contrib import admin
from . import models
# Register your models here.

@admin.register(models.Purchase)
class PurchaseAdmin(admin.ModelAdmin):
    fieldsets = (("Custom Profile", {"fields": ("title","host", "closed")}),)

    list_display = (
       "title",
       "host",
       "closed",
    )


from datetime import datetime

current_date_and_time = datetime.now()
day_of_week = current_date_and_time.weekday()

total_price = float()
sales_tax = float()
subtotal = float(input("Please enter the subtotal: "))
buy_more = float()
discount = float()

def price_math():
    global total_price
    global sales_tax
    global subtotal
    global buy_more
    global discount
    if day_of_week == 1 or 2:
        if subtotal >= 50:
            discount = subtotal * .1
            subtotal = subtotal * .9
            print(f"Your discount: {discount:.2f}$")
        else:
            buy_more = 50 - subtotal #stretch (get the amount remainder the user needs to buy to get the discount)
            print(f'You will need to purchase ${buy_more} to get the 10% discount')
    sales_tax = subtotal * .06
    total_price = sales_tax + subtotal

price_math()
print(f'Subtotal: {subtotal}')
print(f'Sales tax amount: {sales_tax:.2f}')
print(f'Total: {total_price:.2f}$')


try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import argparse

def ocr_core(filename):
    """
    This function will handle the core OCR processing of images.
    """
    text = pytesseract.image_to_string(Image.open(filename))  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
    return text

# print(ocr_core('images/ocr_example_1.png'))

def ArgChecker():
    parser = argparse.ArgumentParser()
    parser.add_argument("filename", nargs='?')
    args = parser.parse_args()
    if args.filename is None:
        parser.error("This python program requires a full filepath to run")
    else:
        print(ocr_core(args.filename))

if __name__ == '__main__':
    ArgChecker()


num = int(input())
size = input()
delivery = input()
delivery_price = 0

price = 0

if num <= 10:
    print("Invalid order")

if num > 10:
    if delivery == "With delivery":
        delivery_price = 60
    elif delivery == "Without delivery":
        delivery_price = 0

    if size == '90X130':
        price = 110
        if num > 60:
            price *= 0.92
        if 30 < num <= 60:
            price *= 0.95

    if size == '100X150':
        price = 140
        if num > 80:
            price *= 0.90
        if 40 < num <= 80:
            price *= 0.94

    if size == '130X180':
        price = 190
        if num > 50:
            price *= 0.88
        if 20 < num <=50:
            price *= 0.93

    if size == '200X300':
        price = 250
        if num > 50:
            price *= 0.86
        if 25 < num <= 50:
            price *= 0.91

    total = price * num + delivery_price

    if num > 99:
        total *= 0.96

    print(f"{total:.2f} BGN")

python_basics_2023/more_exercises_python_basics/Exam - 18 and 19 July 2020/03. Aluminum Joinery.py


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import tensorflow as tf
from scipy.misc import imread, imsave, imshow, imresize
import numpy as np
import sys; sys.path.insert(0, ".")
from utility import draw_toolbox
from ssdface_freeze import anchor_manipulator_np
from preprocessing import ssd_preprocessing

slim = tf.contrib.slim

def save_image_with_bbox(image, labels_, scores_, bboxes_):
    if not hasattr(save_image_with_bbox, "counter"):
        save_image_with_bbox.counter = 0  # it doesn't exist yet, so initialize it
    save_image_with_bbox.counter += 1

    img_to_draw = np.copy(image)

    img_to_draw = draw_toolbox.bboxes_draw_on_img(img_to_draw, labels_, scores_, bboxes_, thickness=2)
    imsave(os.path.join('./debug/{}.jpg').format(save_image_with_bbox.counter), img_to_draw)
    return save_image_with_bbox.counter

def slim_get_split(file_pattern='{}_????'):
    # Features in Pascal VOC TFRecords.
    keys_to_features = {
        'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
        'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'),
        'image/height': tf.FixedLenFeature([1], tf.int64),
        'image/width': tf.FixedLenFeature([1], tf.int64),
        'image/channels': tf.FixedLenFeature([1], tf.int64),
        'image/shape': tf.FixedLenFeature([3], tf.int64),
        'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32),
        'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),
        'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32),
        'image/object/bbox/ymax': tf.VarLenFeature(dtype=tf.float32),
        'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64),
        'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64),
        'image/object/bbox/truncated': tf.VarLenFeature(dtype=tf.int64),
    }
    items_to_handlers = {
        'image': slim.tfexample_decoder.Image('image/encoded', 'image/format'),
        'shape': slim.tfexample_decoder.Tensor('image/shape'),
        'object/bbox': slim.tfexample_decoder.BoundingBox(
                ['ymin', 'xmin', 'ymax', 'xmax'], 'image/object/bbox/'),
        'object/label': slim.tfexample_decoder.Tensor('image/object/bbox/label'),
        'object/difficult': slim.tfexample_decoder.Tensor('image/object/bbox/difficult'),
        'object/truncated': slim.tfexample_decoder.Tensor('image/object/bbox/truncated'),
    }
    decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers)

    dataset = slim.dataset.Dataset(
                data_sources=file_pattern,
                reader=tf.TFRecordReader,
                decoder=decoder,
                num_samples=100,
                items_to_descriptions=None,
                num_classes=21,
                labels_to_names=None)

    with tf.name_scope('dataset_data_provider'):
        provider = slim.dataset_data_provider.DatasetDataProvider(
                    dataset,
                    num_readers=2,
                    common_queue_capacity=32,
                    common_queue_min=8,
                    shuffle=True,
                    num_epochs=1)

    [org_image, shape, glabels_raw, gbboxes_raw, isdifficult] = provider.get(['image', 'shape',
                                                                         'object/label',
                                                                         'object/bbox',
                                                                         'object/difficult'])
    image, glabels, gbboxes = ssd_preprocessing.preprocess_image(org_image, glabels_raw, gbboxes_raw, [128., 128., 128.], [96, 96], is_training=True, data_format='channels_last', output_rgb=True)

    '''anchor_creator = anchor_manipulator.AnchorCreator([300] * 2,
            layers_shapes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)],
            anchor_scales = [(0.1,), (0.2,), (0.375,), (0.55,), (0.725,), (0.9,)],
            extra_anchor_scales = [(0.1414,), (0.2739,), (0.4541,), (0.6315,), (0.8078,), (0.9836,)],
            anchor_ratios = [(2., .5), (2., 3., .5, 0.3333), (2., 3., .5, 0.3333), (2., 3., .5, 0.3333), (2., .5), (2., .5)],
            layer_steps = [8, 16, 32, 64, 100, 300])'''
    anchor_creator = anchor_manipulator_np.AnchorCreator([96] * 2,
            layers_shapes = [(12, 12), (6, 6), (3, 3), (1, 1)],
            anchor_scales = [(0.15,), (0.3,), (0.45,), (0.6,)],
            extra_anchor_scales = [(0.2,), (0.4,), (0.5,), (0.8,)],
            anchor_ratios = [(1.,), (1.,),(1.,),(1.,)],
            layer_steps = [4, 8, 16, 48])
    all_anchors, all_num_anchors_depth, all_num_anchors_spatial = anchor_creator.get_all_anchors()

    num_anchors_per_layer = []
    for ind in range(len(all_anchors)):
        num_anchors_per_layer.append(all_num_anchors_depth[ind] * all_num_anchors_spatial[ind])

    anchor_encoder_decoder = anchor_manipulator_np.AnchorEncoder(allowed_borders=[1.0] * 4,
                                                        positive_threshold = 0.5,
                                                        ignore_threshold = 0.5,
                                                        prior_scaling=[0.1, 0.1, 0.2, 0.2])

    gt_targets, gt_labels, gt_scores = anchor_encoder_decoder.encode_all_anchors(glabels, gbboxes, all_anchors, all_num_anchors_depth, all_num_anchors_spatial, True)

    anchors = anchor_encoder_decoder._all_anchors
    # split by layers
    gt_targets, gt_labels, gt_scores, anchors = tf.split(gt_targets, num_anchors_per_layer, axis=0),\
                                                tf.split(gt_labels, num_anchors_per_layer, axis=0),\
                                                tf.split(gt_scores, num_anchors_per_layer, axis=0),\
                                                [tf.split(anchor, num_anchors_per_layer, axis=0) for anchor in anchors]

    save_image_op = tf.py_func(save_image_with_bbox,
                            [ssd_preprocessing.unwhiten_image(image),
                            tf.clip_by_value(tf.concat(gt_labels, axis=0), 0, tf.int64.max),
                            tf.concat(gt_scores, axis=0),
                            tf.concat(gt_targets, axis=0)],
                            tf.int64, stateful=True)
    return save_image_op

if __name__ == '__main__':
    #save_image_op = slim_get_split('/home/scchiu/Workspace/Workspace/SSD.TensorFlow/dataset/tfrecords/train*')
    # Create the graph, etc.
    #init_op = tf.group([tf.local_variables_initializer(), tf.local_variables_initializer(), tf.tables_initializer()])

    anchor_creator = anchor_manipulator_np.AnchorCreator([300] * 2,
        layers_shapes = [(30, 30), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)],
        anchor_scales = [(0.1,), (0.2,), (0.375,), (0.55,), (0.725,), (0.9,)],
        extra_anchor_scales = [(0.1414,), (0.2739,), (0.4541,), (0.6315,), (0.8078,), (0.9836,)],
        anchor_ratios = [(2., ), (2., 3., .5, 0.3333), (2., 3., .5, 0.3333), (2., 3., .5, 0.3333), (2., .5), (2., .5)],
        layer_steps = [10, 16, 32, 64, 100, 300])
    '''anchor_creator = anchor_manipulator_np.AnchorCreator([48] * 2,
            layers_shapes = [(12, 12), (6, 6), (3, 3), (1, 1)],
            anchor_scales = [(0.15,), (0.3,), (0.45,), (0.6,)],
            extra_anchor_scales = [(0.2,), (0.4,), (0.5,), (0.8,)],
            anchor_ratios = [(1.,), (1.,),(1.,),(1.,)],
            layer_steps = [4, 8, 16, 48])'''

    all_anchors, all_num_anchors_depth, all_num_anchors_spatial = anchor_creator.get_all_anchors()

    print("\n\n== all_anchors")
    for layer, anchors in enumerate(all_anchors):
        print('\nlayer = {}, size = {}'.format(layer, len(anchors)))
        for n, anchor in enumerate(anchors):
            print('anchor {} = {}'.format(n, anchor.shape))
            if layer > 3:
                print(anchor)

    print("\n\n== all_num_anchors_depth")
    for layer, anchors in enumerate(all_num_anchors_depth):
        print('\nlayer = {}, value = {}'.format(layer, anchors))

    print("\n\n== all_num_anchors_spatial")
    for layer, anchors in enumerate(all_num_anchors_spatial):
        print('\nlayer = {}, value = {}'.format(layer, anchors))

    '''for l1, anchors in enumerate(all_anchors):
        print('layer = {}'.format(l1))
        for l2, anchor in enumerate(anchors):
            print('\tanchor {}'.format(l2))
            print('\t\tshape = {}'.format(anchor.shape))
            print('\t\tanchor = {}'.format(anchor))
    '''
    anchor_encoder_decoder = anchor_manipulator_np.AnchorEncoder(allowed_borders = [1.0] * 4,
                                                            positive_threshold = None,
                                                            ignore_threshold = None,
                                                            prior_scaling=[0.1, 0.1, 0.2, 0.2])

    anchor_encoder_decoder.ext_decode_all_anchors(pred, all_anchors, all_num_anchors_depth, all_num_anchors_spatial)


norden = ["Danmark","Finland","Island","Norge","Sverige"]
storbritannien = ["England", "Nordirland", "Skottland", "Wales"]   #2 arrays med länderna i norden och storbrittanien
print("Ange ett land: ")
land = str(input())  #skapar en input och gör svaret till en string
if land.title() in norden:   #använder oss av .title() metoden för att göra vår string med stor bokstav först, och tittar om inputen matchar någon av länderna
    print(land.title() + " finns i Norden.")
elif land.title() in storbritannien : #om den ej matchar någon av länderna i norden tittar vi i den andra arrayen
    print(land.title() + " ligger i Storbritannien.")
else:
    print(land.title() + " ligger ej i Norden eller Strobritannien.") #om den ej matchar någonstans skriver vi ut detta meddelande

Python Kompendium Uppgifter/Kapitel 5/5.3.py


# -*- coding: utf-8 -*-
"""This module provide method to return stolen bikes by distance"""
import logging

from django.views.decorators.csrf import csrf_exempt
from django.db.models import Func, F
from django.http import JsonResponse, HttpResponse
from django.core import serializers

from APP.models import StolenBike, Bicycle, Image
from ..utils.need_token import need_token

logger = logging.getLogger(__name__)

class Sin(Func):
    function = 'SIN'

class Cos(Func):
    function = 'COS'

class Acos(Func):
    function = 'ACOS'

class Radians(Func):
    function = 'RADIANS'

@csrf_exempt
def get(request):
    """Return stolen bikes sorted by distance.

    Take get params:
    lat - center latitude
    long - center longitude
    distance - radius of data
    distancemin - minimum distance

    Author: Olexii
    """
    if request.method != "GET":
        logger.info("Unsupported method returned")
        return HttpResponse(status=405)

    lat = float(request.GET.get('lat'))
    lng = float(request.GET.get('lng'))
    distance = request.GET.get('distance')
    distance_min = request.GET.get('distance_min', 0)
    radlat = Radians(lat)
    radlong = Radians(lng)
    radflat = Radians(F('lat'))
    radflong = Radians(F('lng'))

    expression = 6371.0 * Acos(Cos(radlat) * Cos(radflat) *
                               Cos(radflong - radlong) +
                               Sin(radlat) * Sin(radflat))

    query = StolenBike.objects.annotate(
        distance=expression)
    query = query.filter(distance__range=(distance_min, distance))
    query = query.order_by('distance')

    result = []
    for stolen in query:
        bike = Bicycle.objects.get(pk=stolen.pk)
        image = Image.objects.get(bike=bike.pk)
        result.append({
            "description": stolen.description,
            "lat": stolen.lat,
            "lng": stolen.lng,
            "id": stolen.id,
            "bike": {
                "id": bike.id,
                "name": bike.name,
                "image": image.url
            }
        })

    return JsonResponse({
        "data": result,
        "count": len(result),
        "count_all": StolenBike.objects.count()
    })


'''
Author: Kristopher Buote

Neural Network that trains on philosophy text sequences to predict the most likely next word.
Embeddings are learned.
'''
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras import Sequential
from keras.layers import Embedding, LSTM, Dense
import pickle

filename = 'republic_clean'
print('Loading data...')
data = open('./philosophy_data/' + filename + '.txt', 'r').read()  # should be simple plain text file
lines = data.split('\n')
lines = lines[0:5]
print('Done.')

# Integer encoding sequences of words
tokenizer = Tokenizer()
print('Tokenizing...')
tokenizer.fit_on_texts(lines)
sequences = tokenizer.texts_to_sequences(lines)
vocab_size = len(tokenizer.word_index) + 1
print('Done.')

# Separate into input (X) and output (Y)
print("Splitting into X and Y...")
sequences = np.array(sequences)
X, Y = sequences[:,0:-1], sequences[:,-1]
# Y = to_categorical(Y, num_classes=vocab_size)
seq_length = X.shape[1]
print('Done.')

# Create Model
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=100, input_length=seq_length)) # Consider input_length = None
model.add(LSTM(100, return_sequences=True))
model.add(LSTM(100))
model.add(Dense(100, activation='relu'))
model.add(Dense(vocab_size, activation='softmax'))
model.summary()

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

# Fit model
epochs = 1
for e in range(epochs):
    model.fit(X, Y, batch_size=512, epochs=1)
    # if e % 10 == 0:
    model.save('./models/philosopher-king-epoch' + str(e) +'.h5')
    # save the tokenizer
    pickle.dump(tokenizer, open('./models/tokenizer.pkl', 'wb'))


#!/usr/bin/env python3
"""
Takes all your GitHub pages repos and builds their static sites.
"""

import os
import os.path
import shutil
from subprocess import check_call, check_output, DEVNULL

PATH = 'https://github.com/{username}/{reponame}'
HELPTEXT = """usage: {} [SUBCOMMAND]
Build and rebuild GitHub pages sites.  Typical usage is to run with no
arguments, which runs the "dwim" sub-command.

dwim - Automatically guess the operations necessary to completely build your
       site.  Will tell you what it's doing as it goes. (this is default)
init - Initialize the site by pulling and running the first build.
pull - Pull every repository (but do not build anything).
rebuild - Rebuild the entire site (without pulling first).
build - Pull each repository and rebuild if it updated.
deploy - Push to S3 (this will never be done by dwim)
help - Display this help text.
"""

def run(args, **kwargs):
    check_call(args, stdout=DEVNULL, stderr=DEVNULL, **kwargs)

class GhpRepo(object):
    """A class representing a git repository with GitHub pages enabled.

    Has a remote URL, a local directory, and a "build" directory, where the
    actual generated site will be placed. Also, most repositories are on branch
    gh-pages, but some (like *.github.io) are on master, so this accepts a
    branch argument.

    This class allows you to clone, build, update, and rebuild a repo fairly
    easily.  Of course, it just shells out to git and jekyll.

    """

    def __init__(self, name, url, local, output, branch='gh-pages'):
        """Create the class instance.

        This doesn't necessarily clone the repo or build it - in fact, the repo
        may already exist locally.

        """
        self.name = name
        self.url = url
        self.local = local
        self.output = output
        self.branch = branch

    def should_build(self):
        return not os.path.exists(os.path.join(self.local, '.nojekyll'))

    def checkout(self):
        """Check out the repository."""
        print("Cloning {}".format(self.name))
        run(['git', 'clone', '-b', self.branch, self.url, self.local])

    def current_commit(self):
        """Return the SHA of the current commit."""
        os.chdir(self.local)
        return check_output(['git', 'rev-parse', 'HEAD'])

    def pull(self):
        """Pull from the default remote tracking branch, hopefully.

        Return True if updated, false otherwise.
        """
        os.chdir(self.local)
        old_revision = self.current_commit()
        run(['git', 'pull'])
        return self.current_commit() != old_revision

    def build(self):
        """Run the build command (jekyll) or just copy files if .nojekyll exists."""
        os.chdir(self.local)
        if self.should_build():
            print('=> {}: build via Jekyll'.format(self.name))
            run(['jekyll', 'build', '-d', self.output])
        else:
            print('=> {}: build via copy'.format(self.name))
            if os.path.exists(self.output):
                shutil.rmtree(self.output)
            ignore = shutil.ignore_patterns(
                # may have to include lots of stuff in here
                '.git',
                '.gitignore',
                '.nojekyll'
            )
            shutil.copytree(self.local, self.output, ignore=ignore)
        print('   DONE'.format(self.name))

    def update_and_build(self):
        """Pull, and if the repo has changed, rebuild.

        Return True if the repo updated.  Return False otherwise.
        """
        if self.pull():
            print('=> {}: was out of date'.format(self.name))
            self.build()
            return True
        return False

class GhpBuilder(object):
    """This class represents a collection of GitHub pages repositories to deploy.

    Construct an instance of this object to build your complete GitHub pages
    website for later deployment.

    """

    def __init__(self, username, repos, directory=os.getcwd()):
        directory = os.path.abspath(directory)
        self.username = username
        self.directory = directory
        self.work = os.path.join(directory, 'work')
        self.site = os.path.join(directory, 'site')
        self.repos = []
        self.main = None
        for name, branch, path in repos:
            url = PATH.format(username=username, reponame=name)
            localwork = os.path.join(self.work, name)
            localbuild = os.path.join(self.site, path)
            if path == '':  # this is the "main site"
                self.main = GhpRepo(name, url, localwork, localbuild, branch)
            else:
                self.repos.append(GhpRepo(name, url, localwork, localbuild, branch))

    def _initial_checkout(self):
        """Create workdir and clone repos for the first time."""
        os.makedirs(self.work, exist_ok=True)
        if self.main:
            self.main.checkout()
        for repo in self.repos:
            repo.checkout()

    def rebuild(self):
        """Build all repos, assuming they are already cloned."""
        os.makedirs(self.site, exist_ok=True)
        if self.main:
            self.main.build()
        for repo in self.repos:
            repo.build()

    def init(self):
        """Check out and build for the first time."""
        print("Initializing the site!")
        self._initial_checkout()
        self.rebuild()

    def pull(self):
        """Pull all repositories without updating."""
        updated = False
        if self.main and self.main.pull():
            print('=> {}: updated'.format(self.main.name))
            updated = True
        for repo in self.repos:
            if repo.pull():
                print('=> {}: updated'.format(repo.name))
                updated = True
        if updated:
            print('You have pulled but not built.  Your site/ directory will')
            print('only be up-to-date when you run "rebuild".')

    def _update_main(self):
        """Update the main repository, and possibly subdirectories.

        Since the main site resides in the root, when it is regenerated, the
        subdirectories are clobbered! To address this, whenever the main repo
        is rebuilt, all other repos are forced to rebuild.

        """
        if self.main and self.main.update_and_build():
            print('Rebuilding other repos since they may have been clobbered.')
            for repo in self.repos:
                repo.build()
            print('Continuing to update other repos...')

    def build(self):
        """Normal build."""
        self._update_main()
        for repo in self.repos:
            repo.update_and_build()

    def dwim(self):
        """Do what I mean mode!

        This tries to infer what operation should be done based on the state of
        the directories.  The goal here is always a completely built site.

        """
        if not os.path.exists(self.work):
            print('Detected that the work directory does not exist.')
            print('Initializing ...')
            self.init()
        elif not os.path.exists(self.site):
            print('Detected that the site directory does not exist, but your repos are cloned.')
            print('Rebuilding ...')
            self.rebuild()
        else:
            print('Updating your existing site.')
            self.build()

    def deploy(self):
        check_call(["s3_website", "push"])

def help():
    print(HELPTEXT.format(sys.argv[0]))

if __name__ == '__main__':
    import sys
    sys.path.insert(0, os.getcwd())
    from config import USERNAME, REPOS
    builder = GhpBuilder(USERNAME, REPOS)
    commands = {
        'init': builder.init,
        'build': builder.build,
        'rebuild': builder.rebuild,
        'dwim': builder.dwim,
        'pull': builder.pull,
        'deploy': builder.deploy,
        'push': builder.deploy,
        'help': help,
    }
    if len(sys.argv) <= 1:
        cmd = 'dwim'
    else:
        cmd = sys.argv[1]
    func = commands.get(cmd)
    if func:
        func()
    else:
        help()


from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalMaxPooling1D
from keras_preprocessing.text import Tokenizer

# set parameters:
num_words = 10
embedded_dims = 5
maxlen = 5
batch_size = 100
filters = 10
kernel_size = 2
hidden_dims = 2
epochs = 20

# create data that represents it taking longer to travel home from work, than to travel to
docs = ['home daycare work', 'home daycare work', 'work daycare home', 'work daycare home', 'home work', 'work home', 'home work', 'work home']
docs_eos = list(map(lambda x: '<go> ' + x, docs))
docs_eos = list(map(lambda x: x + ' <eos>', docs_eos))
y = [35, 34, 47, 46, 18,  23, 19, 26]

# set up the word tokenizer
# TO DO adda a stemmer some home
t = Tokenizer(num_words=10,  oov_token='<oov>')
t.fit_on_texts(docs_eos)

# extract a work sequence
x_seqs = t.texts_to_sequences(docs_eos)

# padding seqs
x_padded = sequence.pad_sequences(x_seqs, maxlen=maxlen)

# initialized the model
model = Sequential()

# our vocab indices into embedding_dims dimensions
model.add(Embedding(num_words,
                    embedded_dims,
                    input_length=maxlen))

# word group filters of size filter_length:
model.add(Conv1D(filters,
                 kernel_size,
                 padding='valid',
                 activation='relu',
                 strides=1))
# we use max pooling:
model.add(GlobalMaxPooling1D())

# We project onto a single unit output layer, and squash it with a sigmoid:
model.add(Dense(1))
model.add(Activation('linear'))

model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['mae'])
model.fit(x_padded, y,
          epochs=epochs)
print('completed')

def predict(docs, maxlen=maxlen):
    docs_eos = list(map(lambda x: '<go> ' + x, docs))
    docs_eos = list(map(lambda x: x + ' <eos>', docs_eos))
    docs_seq = t.texts_to_sequences(docs_eos)
    x_padded = sequence.pad_sequences(docs_seq, maxlen=maxlen)
    return model.predict(x_padded)

test_data = ['home daycare work', 'work daycare home']

print(predict(test_data))


from flask import Flask, request, Markup, render_template, flash
import json

app = Flask(__name__)

@app.route('/')
def render_home():
    return render_template('home.html')

@app.route('/about')
def render_about():
    return render_template('about.html')

@app.route('/Likes')
def render_Likes():
    return render_template('likes.html')

@app.route('/popularity')
def render_popularity():
    return render_template('mvp.html', options = options())

def options():
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
#the drop down menu and also gets year
    year = []
    for y in Ads_data:
        if y['Year'] not in year:
           year.append(y['Year'])

    a = ""
    for y in year:
        a = a + Markup('<option value = "'+ str(y) + '">'+ str(y) + '</option>')
    return a

@app.route('/popularity_response')
def render_popularity_response():
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
#gets year for html drop down menu
    Year = ""
    if 'year' in request.args:
        Year = request.args['year']
        brand = {}
        for a in Ads_data:
            if str(a['Year']) == Year:
                if a['Brand'] in brand:
                    brand[a['Brand']] = brand[a['Brand']] + a['Data']['Viewership']['Views']
                else:
                    brand[a['Brand']] = a['Data']['Viewership']['Views']
#Gets the most viewed brand
    print(brand)
    MostViewed = "Budweiser"
    for r in brand:
        if brand[r] > brand[MostViewed]:
            MostViewed = r
    return render_template('mvp_display.html', Year = Year, mostViewed = MostViewed, Views=brand[MostViewed], options = options())

@app.route('/category')
def render_category():
#Gets the year
    year = []
    with open('super_bowl_ads.json') as Ads:
        Ads_data = json.load(Ads)
    for y in Ads_data:
        if y['Year'] not in year:
           year.append(y['Year'])
    a = ""
    for y in year:
        a = a + Markup('<option value = "'+ str(y) + '">'+ str(y) + '</option>')
    return render_template('category.html', options = a)

@app.route('/category_response')
def render_category_response():
    with open('advertisements.json') as Ads:
        Ads_data = json.load(Ads)

    category = most_pop_cat(request.args['year'],Ads_data)
    return render_template('category_display.html', Year = request.args['year'], mostUsed = category[0], used = category[1], options = options())

def most_pop_cat(year, data):
#Finds the most populay category based on the users choice of year
    cat = {"funny":0, "show_product_quickly":0, "patriotic":0, "celebrity":0,"danger":0,"animals":0,"use_sex":0}
    for ad in data:
        if str(ad['year']) == year:

            if ad["funny"] == "TRUE":
                cat['funny'] = cat['funny'] + 1

            if ad["show_product_quickly"] == "TRUE":
                cat['show_product_quickly'] = cat['show_product_quickly'] + 1

            if ad["patriotic"] == "TRUE":
                cat['patriotic'] = cat['patriotic'] + 1

            if ad["celebrity"] == "TRUE":
                cat['celebrity'] = cat['celebrity'] + 1

            if ad["danger"] == "TRUE":
                cat['danger'] = cat['danger'] + 1

            if ad["animals"] == "TRUE":
                cat['animals'] = cat['animals'] + 1

            if ad["use_sex"] == "TRUE":
                cat['use_sex'] = cat['use_sex'] + 1

    MyCat={'funny': "Comedy",
    'show_product_quickly': "Showing the Product",
    'patriotic': "Patriotic",
    'celebrity':"Celebrity",
    'danger': "Danger",
    'animals': "Animals",
    'use_sex': "Sexual appeal"}

#finds the highest nuber for category used
    print(cat)
    category = []
    highest = 0
    for c in cat:
        if cat[c] == highest:
            category.append(c)

        if cat[c] > highest:
            highest = cat[c]
            category = []
            category.append(c)

    print(highest)
    print(category)
    CT = ""
    for c in category:
       CT = CT + Markup(MyCat[c] + ",")
    return [CT[:-1], highest]

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

  # for c in ad['Data']['Content']:
                #if ad['Data']['Content'][c] == True:
                   # if c in cat:
                      #  cat[c] = cat[c] + 1
                  #  else:
                      #  cat[c] = 1


from train_network import create_one_hot_encoding, encode_labels, create_labels
from keras.models import load_model, Sequential
import os
import pickle
import numpy as np
import tensorflow as tf

input_width = 128
input_height = 128

if __name__ == "__main__":
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25)
    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

    label_dict, emotions_list = create_labels()
    one_hot_encoding = create_one_hot_encoding(emotions_list)
    encoded_labels = encode_labels(label_dict, one_hot_encoding, emotions_list)

    with open('./image_data_dict/images_test.dictionary', 'rb') as image_dict_file:
        validate_image_dict = pickle.load(image_dict_file)
        amount_images = len(validate_image_dict.keys())
        x_train = np.empty(shape=(amount_images, input_width, input_height, 1), dtype=int)
        y_train = np.empty(shape=(amount_images, 8), dtype=int)
        index = 0
        for image_name, image_data in validate_image_dict.items():
            if image_name in encoded_labels.keys() and image_data.shape[0] == input_width:
                x_train[index] = image_data
                y_train[index] = (encoded_labels[image_name])
                index += 1

    model_path = "model"
    model_name = "facial_model.h5"
    path = os.path.join(model_path, model_name)
    model = load_model(path)
    model.fit(x_train, y_train, batch_size=32, epochs=1, validation_split=.1, verbose=2)


import pathlib
from setuptools import setup, find_packages

PACKAGE_ROOT = pathlib.Path(__file__).resolve().parent

def list_reqs(fname='requirements.txt'):
    with open(fname) as f:
        return f.read().splitlines()

with open('README.md') as f:
    readme = f.read().strip()

with open(PACKAGE_ROOT / 'funding_model' / 'VERSION') as f:
    _version = f.read().strip()

setup(name='funding-model',
      version=_version,
      packages=find_packages(exclude=('tests', 'docs')),
      install_requires=list_reqs(),
      python_requires='>=3.7.0',
      author='Ali Naji',
      url="https://github.com/ali-naji",
      license='MIT',
      author_email='anaji7@gatech.edu',
      description="Classification model to predict whether a kickstarter project will be successfully funded",
      long_description=readme,
      package_data={'funding_model': ['VERSION']},
      classifiers=['License :: OSI Approved :: MIT License',
                   'Programming Language :: Python',
                   'Programming Language:: Python:: 3.7',
                   'Programming Language:: Python:: 3.8',
                   'Programming Language:: Python:: 3.9']
      )


## write an example agent and show that it does stuff
import numpy as np
import torch
import matplotlib.pyplot as plt

def get_action(agent, s):
    action, logprob, value = agent.get_action(s)
    return action

def agent_test(env, agent):
    maxsteps = 100
    for step in range(maxsteps):
        s = torch.Tensor(np.expand_dims(env.get_observation(), axis=0))

        action = get_action(agent, s)

        s_prime, r, done, __ = env.step(action)

        env.render()

        if step == maxsteps - 1 or done:
            plt.pause(2)
            plt.close()

        if done:
            break


"""Command line functions for training dictionaries with pronunciation probabilities"""
from __future__ import annotations

from pathlib import Path

import rich_click as click

from montreal_forced_aligner import config
from montreal_forced_aligner.alignment.pretrained import DictionaryTrainer
from montreal_forced_aligner.command_line.utils import (
    common_options,
    validate_acoustic_model,
    validate_dictionary,
)

__all__ = ["train_dictionary_cli"]

@click.command(
    name="train_dictionary",
    context_settings=dict(
        ignore_unknown_options=True,
        allow_extra_args=True,
        allow_interspersed_args=True,
    ),
    short_help="Calculate pronunciation probabilities",
)
@click.argument(
    "corpus_directory",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
)
@click.argument("dictionary_path", type=click.UNPROCESSED, callback=validate_dictionary)
@click.argument("acoustic_model_path", type=click.UNPROCESSED, callback=validate_acoustic_model)
@click.argument(
    "output_directory", type=click.Path(file_okay=False, dir_okay=True, path_type=Path)
)
@click.option(
    "--config_path",
    "-c",
    help="Path to config file to use for training.",
    type=click.Path(exists=True, file_okay=True, dir_okay=False, path_type=Path),
)
@click.option(
    "--silence_probabilities",
    is_flag=True,
    help="Flag for saving silence information for pronunciations.",
    default=False,
)
@click.option(
    "--speaker_characters",
    "-s",
    help="Number of characters of file names to use for determining speaker, "
    "default is to use directory names.",
    type=str,
    default="0",
)
@click.option(
    "--audio_directory",
    "-a",
    help="Audio directory root to use for finding audio files.",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
)
@common_options
@click.help_option("-h", "--help")
@click.pass_context
def train_dictionary_cli(context, **kwargs) -> None:
    """
    Calculate pronunciation probabilities for a dictionary based on alignment results in a corpus.
    """
    if kwargs.get("profile", None) is not None:
        config.profile = kwargs.pop("profile")
    config.update_configuration(kwargs)
    config_path = kwargs.get("config_path", None)
    acoustic_model_path = kwargs["acoustic_model_path"]
    corpus_directory = kwargs["corpus_directory"].absolute()
    dictionary_path = kwargs["dictionary_path"]
    output_directory = kwargs["output_directory"]
    trainer = DictionaryTrainer(
        acoustic_model_path=acoustic_model_path,
        corpus_directory=corpus_directory,
        dictionary_path=dictionary_path,
        **DictionaryTrainer.parse_parameters(config_path, context.params, context.args),
    )

    try:
        trainer.align()
        trainer.export_lexicons(output_directory)
    except Exception:
        trainer.dirty = True
        raise
    finally:
        trainer.cleanup()


import time
import _thread
race_length = 100
winner = False

class Animal:

    def __init__(self, name, speed, rest_time):
        self.name = name
        self.speed = speed
        self.rest_time = rest_time
        self.distance = 0

    def get_name(self):
        return self.name

    def get_rest_time(self):
        return self.rest_time

    def get_speed(self):
        return self.speed

    def get_distance(self):
        return self.distance

    def run(self):
        global race_length
        global winner

        while self.get_distance() < race_length and not winner:
            self.distance = self.get_distance() + self.get_speed()
            print("{} ran {} meters. Is now at {} meters.".format(self.get_name(), self.get_speed(), self.get_distance()))

            if self.get_distance() >= race_length:
                winner = True
                print_winner(self)

            else:
                self.rest()

    def rest(self):
        # print("{} is now resting for {} seconds.".format(self.get_name(), self.get_rest_time()))
        time.sleep(self.get_rest_time())

    def __str__(self):
        return "[Name: {}, Speed: {}, Rest Time: {}]".format(self.get_name(), self.get_speed(), self.get_rest_time())

def print_winner(race_winner):
    print()
    print("{} has won the race!!".format(race_winner.get_name()))
    print()

def race_start():
    print("On your mark...")
    time.sleep(1)
    print("Get set...")
    time.sleep(1)
    print("GO!!!")
    print()

def print_racers(racers):

    for racer in racers:
        print(racer)

    print()

def print_final_distances(racers):
    for racer in racers:
        print("{} finshed at {}.".format(racer.get_name(), racer.get_distance()))
    print()

def main():
    rabbit = Animal("Peter", 25, 3)
    turtle = Animal("Myrtle", 15, 1)
    penguin = Animal("Tux", 20, 2)

    print_racers([rabbit, turtle, penguin])

    race_start()

    _thread.start_new_thread(rabbit.run, (), )
    _thread.start_new_thread(turtle.run, (), )
    _thread.start_new_thread(penguin.run, (), )

    while not winner:
        pass

    print_final_distances([rabbit, turtle, penguin])

if __name__ == "__main__":
    main()


def main():
    ans = input("What time is it? ")

    time = convert(ans)

    if time >= 7.0 and time < 8.0:
        print("breakfast time")
    elif time > 12.0 and time <= 13.0:
        print("lunch time")
    elif time > 18.0 and time < 19.0:
        print("dinner time")

def convert(time):
    hour = int(time.split(":")[0])
    min = int(time.split(":")[1])

    min = float(int(min) * 10 / 60) / 10

    return hour + min

if __name__ == "__main__":
    main()