import pygame

WIDTH = 7
HEIGHT = 6
TILE_SIZE = 100

COLOURS = [None, (200, 200, 100), (200, 100, 100)]

class Board:
    def __init__(self, copy_from = None):
        """ No arguments: initialise a new empty board
            With argument: initialise a clone of the given board """
        if copy_from is None:
            self.squares = [0] * (WIDTH * HEIGHT)
            self.current_player = 1
            self.winning_line = None
        else:
            self.squares = copy_from.squares[:]
            self.current_player = copy_from.current_player
            self.winning_line = copy_from.winning_line

    def get_square(self, x, y):
        """ Return 0 for an empty square, 1 or 2 for a player's counter """
        return self.squares[y * WIDTH + x]

    def get_available_moves(self):
        """ Return a list of available moves (column numbers) """
        moves = []
        for x in xrange(WIDTH):
            if self.get_square(x, 0) == 0:
                moves.append(x)
        return moves

    def play_move(self, x):
        """ Given a move (a column number), play that move for the current player.
            If the move is legal, flip the current player and return True.
            If not, return False. """
        for y in xrange(HEIGHT-1, -1, -1): # bottom to top, to find the first available space
            i = y * WIDTH + x
            if self.squares[i] == 0:
                self.squares[i] = self.current_player
                self.current_player = 3 - self.current_player # Flip current player
                return True
        return False

    def unplay_move(self, x):
        """ Remove the top counter from column x, and flip the current player. """
        for y in xrange(HEIGHT): # top to bottom, to find the first occupied space
            i = y * WIDTH + x
            if self.squares[i] != 0:
                self.squares[i] = 0
                self.current_player = 3 - self.current_player # Flip current player
                return True
        return False

    def is_board_full(self):
        """ Return True if the board is completely full, False otherwise """
        return len(self.get_available_moves()) == 0

    def check_line(self, x, y, dx, dy):
        """ Check if a player has a line starting at x,y in the direction dx,dy.
            Return 1 or 2 for which player has a line, or None if there is no line. """
        if x + 3*dx >= WIDTH or y + 3*dy >= HEIGHT:
            return None

        owner = self.get_square(x, y)
        if owner == 0:
            return None

        for i in xrange(1, 4):
            if self.get_square(x + i*dx, y + i*dy) != owner:
                return None
        return owner

    def get_game_result(self, player):
        """ If this is a terminal state, return its value for the given player:
            +1 for a win, -1 for a loss, 0 for a draw.
            If this is a nonterminal state, return None. """
        if self.is_board_full():
            return 0

        for y in xrange(HEIGHT):
            for x in xrange(WIDTH):
                for dx, dy in [(1, 0), (0, 1), (1, 1), (1, -1)]:
                    winner = self.check_line(x, y, dx, dy)
                    if winner is not None:
                        self.winning_line = (x, y, dx, dy)
                        if winner == player:
                            return 1
                        else:
                            return -1

        return None

    def draw(self, screen):
        """ Draw the board """
        for x in xrange(WIDTH):
            if x % 2 == 1:
                rect = pygame.Rect(x * TILE_SIZE, 0, TILE_SIZE, HEIGHT * TILE_SIZE)
                pygame.draw.rect(screen, (245, 245, 245), rect)

            for y in xrange(HEIGHT):
                c = self.get_square(x, y)
                colour = COLOURS[c]
                if colour is not None:
                    rect = pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                    pygame.draw.ellipse(screen, colour, rect)
                    pygame.draw.ellipse(screen, (0,0,0), rect, 2)


#!/usr/bin/env python3
"""
Copyright (c) 2010, Patrick Salecker
All rights reserved.

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

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

try:
	from .client import Client, decode_cryptset
	from .windows import *
except SystemError:
	from client import Client, decode_cryptset
	from windows import *

import time
import os
import sys

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import GLib

class KismonWindows:
	def __init__(self):
		self.gtkwin = Gtk.Window()
		self.gtkwin.set_position(Gtk.WindowPosition.CENTER)
		self.gtkwin.connect("destroy", self.on_destroy)
		self.gtkwin.connect('key-press-event', self.on_key_press)
		self.is_fullscreen = False

	def fullscreen(self):
		if self.is_fullscreen is True:
			self.gtkwin.unfullscreen()
			self.is_fullscreen = False
		else:
			self.gtkwin.fullscreen()
			self.is_fullscreen = True

	def on_key_press(self, widget, event):
		keyval = event.keyval
		name = Gdk.keyval_name(keyval)
		if name == "F11":
			self.fullscreen()
		elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:
			if self.map is not None:
				if name == "i":
					self.map.zoom_in()
				elif name == "o":
					self.map.zoom_out()

class MainWindow(KismonWindows):
	def __init__(self, config, client_start, client_stop, map, networks, sources, client):
		KismonWindows.__init__(self)
		self.config = config
		self.config_window = None
		self.progress_bar_win = None
		self.client_start = client_start
		self.client_stop = client_stop
		self.networks = networks
		self.map = map

		if map is not None:
			locate_marker = map.locate_marker
		else:
			locate_marker = None

		self.export_networks = {}
		self.networks.notify_add_list["export"] = self.export_add_network
		self.networks.notify_remove_list["export"] = self.export_remove_network

		self.network_list = NetworkList(self.networks, locate_marker, self.on_signal_graph)

		self.gtkwin.set_title("Kismon")
		self.gtkwin.connect("window-state-event", self.on_window_state)
		self.gtkwin.connect('configure-event', self.on_configure_event)

		self.gtkwin.set_default_size(self.config["window"]["width"],
			self.config["window"]["height"])

		if self.config["window"]["maximized"] is True:
			self.gtkwin.maximize()

		self.network_filter = {}
		self.signal_graphs = {}
		self.sources = sources
		self.client = client

		self.notebook = Gtk.Notebook()

		vbox = Gtk.VBox()
		self.gtkwin.add(vbox)
		vbox.pack_start(self.init_menu(), False, False, 0)

		vpaned_main = Gtk.VPaned()
		vpaned_main.set_position(320)
		vbox.add(vpaned_main)
		hbox = Gtk.HBox()
		vpaned_main.add1(hbox)
		hbox.pack_start(self.network_list.widget, expand=True, fill=True, padding=0)

		right_table = Gtk.Table(n_rows=3, n_columns=1)
		right_scrolled = Gtk.ScrolledWindow()
		right_scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
		right_scrolled.add(right_table)
		right_scrolled.set_size_request(160, -1)
		right_scrolled.get_children()[0].set_shadow_type(Gtk.ShadowType.NONE)
		hbox.pack_end(right_scrolled, expand=False, fill=False, padding=2)

		self.info_expander = Gtk.Expander()
		self.info_expander.set_label("Infos")
		self.info_expander.set_expanded(True)
		right_table.attach(self.info_expander, 0, 1, 0, 1, yoptions=Gtk.AttachOptions.SHRINK)
		self.init_info_table()

		self.gps_expander = Gtk.Expander()
		self.gps_expander.set_label("GPS Data")
		self.gps_expander.set_expanded(True)
		right_table.attach(self.gps_expander, 0, 1, 1, 2, yoptions=Gtk.AttachOptions.SHRINK)
		self.init_gps_table()

		self.sources_expander = Gtk.Expander()
		self.sources_expander.set_label("Sources")
		self.sources_expander.set_expanded(True)
		right_table.attach(self.sources_expander, 0, 1, 2, 3, yoptions=Gtk.AttachOptions.SHRINK)
		self.sources_table = None
		self.sources_table_sources = {}

		battery_expander = Gtk.Expander()
		battery_expander.set_label("Battery")
		right_table.attach(battery_expander, 0, 1, 3, 4, yoptions=Gtk.AttachOptions.SHRINK)
		self.battery_bar = Gtk.ProgressBar()
		battery_expander.add(self.battery_bar)
		self.set_battery_bar(100.0)

		self.log_list = LogList(self.config["window"])
		vpaned_main.add2(self.notebook)
		self.notebook.append_page(self.log_list.widget)
		self.notebook.set_tab_label_text(self.log_list.widget, "Log")

		self.statusbar = Gtk.Statusbar()
		self.statusbar_context = self.statusbar.get_context_id("Starting...")
		vbox.pack_end(self.statusbar, expand=False, fill=False, padding=0)

		self.gtkwin.show_all()
		self.apply_config()

	def apply_config(self):
		if self.map is None:
			return
		if self.config["window"]["map_position"] == "widget":
			self.on_map_widget(None, True)
		elif self.config["window"]["map_position"] == "window":
			self.on_map_window(None, True)
		else:
			self.on_map_hide(None)

	def on_destroy(self, widget):
		print("Window destroyed")
		self.gtkwin = None
		Gtk.main_quit()

	def init_menu(self):
		menubar = Gtk.MenuBar()

		file_menu = Gtk.Menu()
		file_menuitem = Gtk.MenuItem.new_with_label("File")
		file_menuitem.set_submenu(file_menu)

		connect = Gtk.MenuItem.new_with_label('Connect')
		connect.connect("activate", self.on_client_connect)
		file_menu.append(connect)

		disconnect = Gtk.MenuItem.new_with_label('Disconnect')
		disconnect.connect("activate", self.on_client_disconnect)
		file_menu.append(disconnect)

		channel_config = Gtk.MenuItem.new_with_mnemonic('_Preferences')
		channel_config.set_label("Configure Channels")
		channel_config.connect("activate", self.on_channel_config)
		file_menu.append(channel_config)

		sep = Gtk.SeparatorMenuItem()
		file_menu.append(sep)

		file_import = Gtk.MenuItem.new_with_mnemonic('_Open')
		file_import.set_label("Import Networks")
		file_import.connect("activate", self.on_file_import)
		file_menu.append(file_import)

		export_menu = Gtk.Menu()
		export_menuitem = Gtk.MenuItem.new_with_mnemonic('Save _As')
		export_menuitem.set_label("Export Networks")
		export_menuitem.set_submenu(export_menu)
		file_menu.append(export_menuitem)

		for export_format, extension in (("Kismon", "json"),("Kismet netxml", "netxml"),
				("Google Earth KMZ", "kmz"), ("MapPoint csv", "csv")):

			menu = Gtk.Menu()
			menuitem = Gtk.MenuItem.new_with_mnemonic('Save _As')
			menuitem.set_label(export_format)
			menuitem.set_submenu(menu)
			export_menu.append(menuitem)

			for amount in ("All", "Filtered"):
				item = Gtk.MenuItem.new_with_label(amount)
				item.connect("activate", self.on_file_export, export_format.lower(), extension, amount)
				menu.append(item)

		sep = Gtk.SeparatorMenuItem()
		file_menu.append(sep)

		exit = Gtk.MenuItem.new_with_mnemonic('_Quit')
		exit.connect("activate", self.on_destroy)
		file_menu.append(exit)

		menubar.append(file_menuitem)

		view_menu = Gtk.Menu()
		view_menuitem = Gtk.MenuItem.new_with_label("View")
		view_menuitem.set_submenu(view_menu)
		menubar.append(view_menuitem)

		networks_menu = Gtk.Menu()
		networks_menuitem = Gtk.MenuItem.new_with_label("Amount of networks")
		networks_menuitem.set_submenu(networks_menu)
		view_menu.append(networks_menuitem)

		for name, key in (("Network List", "network_list"), ("Map", "map"), ("Export", "export")):
			menu = Gtk.Menu()
			menuitem = Gtk.MenuItem.new_with_label(name)
			menuitem.set_submenu(menu)
			networks_menu.append(menuitem)

			show_none = Gtk.RadioMenuItem(label='Disable')
			if key != "export":
				menu.append(show_none)
			show_current = Gtk.RadioMenuItem(group=show_none, label='Networks from the current session')
			menu.append(show_current)
			show_all = Gtk.RadioMenuItem(group=show_none, label='All Networks')
			menu.append(show_all)

			if self.config["filter_networks"][key] == "none":
				show_none.set_active(True)
			if self.config["filter_networks"][key] == "current":
				show_current.set_active(True)
			if self.config["filter_networks"][key] == "all":
				show_all.set_active(True)

			show_none.connect("activate", self.on_network_filter_networks, key, "none")
			show_current.connect("activate", self.on_network_filter_networks, key, "current")
			show_all.connect("activate", self.on_network_filter_networks, key, "all")

		network_type_menu = Gtk.Menu()
		network_menuitem = Gtk.MenuItem.new_with_label("Network Type")
		network_menuitem.set_submenu(network_type_menu)
		view_menu.append(network_menuitem)

		for network_type, key in (("Infrastructure", "infrastructure"),("Data", "data"), ("Probe", "probe"), ("Ad-Hoc", "ad-hoc")):
			item = Gtk.CheckMenuItem.new_with_label('%s Networks' % network_type)
			if self.config["filter_type"][key]:
				item.set_active(True)
			item.connect("activate", self.on_network_filter_type)
			network_type_menu.append(item)

		crypt_menu = Gtk.Menu()
		crypt_menuitem = Gtk.MenuItem.new_with_label("Encryption")
		crypt_menuitem.set_submenu(crypt_menu)
		view_menu.append(crypt_menuitem)

		for crypt in ("None", "WEP", "WPA", "Other"):
			crypt_item = Gtk.CheckMenuItem.new_with_label(crypt)
			if self.config["filter_crypt"][crypt.lower()]:
				crypt_item.set_active(True)
			crypt_item.connect("activate", self.on_network_filter_crypt)
			crypt_menu.append(crypt_item)

		for key in ("ssid", "bssid"):
			regexpr_menuitem = Gtk.MenuItem.new_with_label("%s (regular expression)" % key.upper())
			regexpr_menuitem.connect("activate", self.on_network_filter_regexpr, key)
			view_menu.append(regexpr_menuitem)

		sep = Gtk.SeparatorMenuItem()
		view_menu.append(sep)

		config_menuitem = Gtk.MenuItem.new_with_mnemonic('_Preferences')
		config_menuitem.connect("activate", self.on_config_window)
		view_menu.append(config_menuitem)

		help_menu = Gtk.Menu()
		help_menuitem = Gtk.MenuItem.new_with_label("Help")
		help_menuitem.set_submenu(help_menu)
		menubar.append(help_menuitem)

		about = Gtk.MenuItem.new_with_mnemonic('_About')
		about.connect("activate", self.on_about_dialog)
		help_menu.append(about)

		return menubar

	def on_network_filter_type(self, widget):
		types = ("infrastructure", "ad-hoc", "probe", "data")
		label = widget.get_label().lower()

		for network_type in types:
			if network_type in label:
				self.config["filter_type"][network_type] = widget.get_active()
				break
		self.networks.apply_filters()
		self.networks_queue_progress()

	def on_network_filter_networks(self, widget, target, show):
		if not widget.get_active():
			return

		self.config["filter_networks"][target] = show
		self.networks.apply_filters()
		self.networks_queue_progress()

	def on_network_filter_crypt(self, widget):
		crypt = widget.get_label().lower()
		self.config["filter_crypt"][crypt] = widget.get_active()
		self.networks.apply_filters()
		self.networks_queue_progress()

	def on_network_filter_regexpr(self, widget, key):
		dialog = Gtk.Dialog("%s (regular expression)" % key.upper(), parent=self.gtkwin)
		entry = Gtk.Entry()
		entry.set_width_chars(100)
		entry.set_text(self.config["filter_regexpr"][key])
		hbox = Gtk.HBox()
		hbox.pack_start(Gtk.Label("Regular expression:", True, True, 0), False, 5, 5)
		hbox.pack_end(entry, True, True, 0)
		dialog.vbox.pack_end(hbox, True, True, 0)
		dialog.add_button("Apply", 1)
		dialog.show_all()
		dialog.run()
		regexpr = entry.get_text()
		dialog.destroy()
		self.config["filter_regexpr"][key] = regexpr
		self.networks.apply_filters()
		self.networks_queue_progress()

	def networks_queue_progress(self):
		if self.progress_bar_win is not None:
			return

		self.progress_bar_max = float(len(self.networks.notify_add_queue))
		if self.networks.queue_task:
			self.progress_bar = Gtk.ProgressBar()
			self.progress_bar.set_text("0.0%%, %s networks left" % len(self.networks.notify_add_queue))
			self.progress_bar.set_fraction(0)

			self.progress_bar_win = Gtk.Window()
			self.progress_bar_win.set_title("Adding networks")
			self.progress_bar_win.set_position(Gtk.WindowPosition.CENTER)
			self.progress_bar_win.set_default_size(300, 30)
			self.progress_bar_win.set_modal(True)
			self.progress_bar_win.set_transient_for(self.gtkwin)
			self.progress_bar_win.add(self.progress_bar)
			self.progress_bar_win.show_all()
			def on_delete_event(widget, event):
				return True
			self.progress_bar_win.connect("delete-event",on_delete_event)
			self.progress_bar_win.connect("destroy", self.on_destroy_progress_bar_win)

			GLib.idle_add(self.networks_queue_progress_update)

	def networks_queue_progress_update(self):
		if self.networks.queue_task is None:
			self.progress_bar_win.destroy()
			return False
		progress = 100 / self.progress_bar_max * (self.progress_bar_max - len(self.networks.notify_add_queue))
		self.progress_bar.set_text("%s%%, %s networks left" % (round(progress, 1), len(self.networks.notify_add_queue)))
		self.progress_bar.set_fraction(progress/100)
		return True

	def on_destroy_progress_bar_win(self, window):
		self.progress_bar_win = None

	def init_info_table(self):
		table = Gtk.Table(n_rows=2, n_columns=2)

		networks_label = Gtk.Label(label="Networks: ")
		networks_label.set_alignment(xalign=0, yalign=0)
		table.attach(networks_label, 0, 1, 0, 1)

		networks_value_label = Gtk.Label()
		networks_value_label.set_alignment(xalign=0, yalign=0)
		table.attach(networks_value_label, 1, 2, 0, 1)
		self.info_table_networks = networks_value_label

		packets_label = Gtk.Label(label="Packets: ")
		packets_label.set_alignment(xalign=0, yalign=0)
		table.attach(packets_label, 0, 1, 1, 2)

		packets_value_label = Gtk.Label()
		packets_value_label.set_alignment(xalign=0, yalign=0)
		table.attach(packets_value_label, 1, 2, 1, 2)
		self.info_table_packets = packets_value_label

		table.show_all()
		self.info_table = table
		self.info_expander.add(self.info_table)

	def update_info_table(self, data):
		self.info_table_networks.set_text("%s" % data["networks"])
		self.info_table_packets.set_text("%s" % data["packets"])

	def init_gps_table(self):
		table = Gtk.Table(n_rows=3, n_columns=2)

		fix_label = Gtk.Label(label="Fix: ")
		fix_label.set_alignment(xalign=0, yalign=0)
		table.attach(fix_label, 0, 1, 0, 1)

		fix_value_label = Gtk.Label()
		fix_value_label.set_alignment(xalign=0, yalign=0)
		table.attach(fix_value_label, 1, 2, 0, 1)
		self.gps_table_fix = fix_value_label

		lat_label = Gtk.Label(label="Latitude: ")
		lat_label.set_alignment(xalign=0, yalign=0)
		table.attach(lat_label, 0, 1, 1, 2)

		lat_value_label = Gtk.Label()
		lat_value_label.set_alignment(xalign=0, yalign=0)
		table.attach(lat_value_label, 1, 2, 1, 2)
		self.gps_table_lat = lat_value_label

		lon_label = Gtk.Label(label="Longitude: ")
		lon_label.set_alignment(xalign=0, yalign=0)
		table.attach(lon_label, 0, 1, 2, 3)

		lon_value_label = Gtk.Label()
		lon_value_label.set_alignment(xalign=0, yalign=0)
		table.attach(lon_value_label, 1, 2, 2, 3)
		self.gps_table_lon = lon_value_label

		table.show_all()
		self.gps_table = table
		self.gps_expander.add(self.gps_table)

	def update_gps_table(self, data):
		if data["fix"] == -1:
			data["fix"] = "None"
		elif data["fix"] == 2:
			data["fix"] = "2D"
		elif data["fix"] == 3:
			data["fix"] = "3D"

		self.gps_table_fix.set_text("%s" % data["fix"])
		self.gps_table_lat.set_text("%s" % data["lat"])
		self.gps_table_lon.set_text("%s" % data["lon"])

	def init_sources_table(self, sources):
		self.sources_table_sources = {}
		if self.sources_table is not None:
			self.sources_expander.remove(self.sources_table)

		table = Gtk.Table(n_rows=(len(sources)*5-1), n_columns=2)
		for uuid in sources:
			self.init_sources_table_source(sources[uuid], table)

		table.show_all()
		self.sources_table = table
		self.sources_expander.add(self.sources_table)

	def init_sources_table_source(self, source, table):
		self.sources_table_sources[source["uuid"]] = {}

		rows = []
		if len(self.sources_table_sources) != 1:
			rows.append((None, None))
		rows.append((source["username"], ""))
		rows.append(("Type", source["type"]))
		rows.append(("Channel", source["channel"]))
		rows.append(("Packets", source["packets"]))

		row = len(self.sources_table_sources) * 5
		for title, value in rows:
			if title is not None:
				label = Gtk.Label(label="%s: "%title)
				label.set_alignment(xalign=0, yalign=0)
				table.attach(label, 0, 1, row, row+1)

			label = Gtk.Label(label=value)
			label.set_alignment(xalign=0, yalign=0)
			table.attach(label, 1, 2, row, row+1)
			self.sources_table_sources[source["uuid"]][title] = label
			row += 1

	def update_sources_table(self, sources):
		for source in sources:
			if source not in self.sources_table_sources:
				self.init_sources_table(sources)
				break

		for uuid in sources:
			source = sources[uuid]
			sources_table_source = self.sources_table_sources[uuid]
			sources_table_source["Type"].set_text("%s" % source["type"])
			sources_table_source["Channel"].set_text("%s" % source["channel"])
			sources_table_source["Packets"].set_text("%s" % source["packets"])

	def on_client_connect(self, widget):
		dialog = Gtk.Dialog("Connect", parent=self.gtkwin)
		entry = Gtk.Entry()
		entry.set_text(self.config["kismet"]["server"])
		dialog.add_action_widget(entry, 1)
		dialog.add_button(Gtk.STOCK_CONNECT, 1)
		dialog.show_all()
		dialog.run()
		server = entry.get_text()
		dialog.destroy()
		self.config["kismet"]["server"] = server
		self.client_start()

	def on_client_disconnect(self, widget):
		self.client_stop()

	def on_map_hide(self, widget):
		self.config["window"]["map_position"] = "hide"

	def on_map_window(self, widget, override=False):
		if (widget is not None and widget.get_active()) or override is True:
			try:
				self.map_window.gtkwin.hide()
				self.map_window.gtkwin.show()
				return
			except:
				pass
			self.config["window"]["map_position"] = "window"
			self.map_window = MapWindow(self.map)
			self.map_window.gtkwin.show_all()
		else:
			try:
				self.map_window.gtkwin.destroy()
			except AttributeError:
				pass

	def on_map_widget(self, widget, override=False):
		map_widget = self.map.widget
		if (widget is not None and widget.get_active()) or override is True:
			self.config["window"]["map_position"] = "widget"
			self.notebook.append_page(map_widget)
			self.notebook.set_tab_label_text(map_widget, "Map")
			map_widget.show_all()
		else:
			page = self.notebook.page_num(map_widget)
			if page >= 0:
				self.notebook.remove_page(page)

	def on_about_dialog(self, widget):
		dialog = Gtk.AboutDialog()
		dialog.set_program_name("Kismon")
		dialog.set_version("0.7")
		dialog.set_comments('PyGTK based kismet client')
		dialog.set_website('http://www.salecker.org/software/kismon/en')
		dialog.set_copyright("(c) 2010-2015 Patrick Salecker")
		dialog.run()
		dialog.destroy()

	def on_window_state(self,window, event):
		if event.new_window_state == Gdk.WindowState.MAXIMIZED:
			self.config["window"]["maximized"] = True
		else:
			self.config["window"]["maximized"] = False

	def on_configure_event(self, widget, event):
		width, height = self.gtkwin.get_size()
		self.config["window"]["width"] = width
		self.config["window"]["height"] = height

	def on_config_window(self, widget):
		if self.config_window is not None:
			try:
				self.config_window.gtkwin.hide()
				self.config_window.gtkwin.show()
				return
			except:
				pass

		self.config_window = ConfigWindow(self)

	def on_signal_graph(self, widget):
		mac = self.network_list.network_selected
		signal_window = SignalWindow(mac, self.on_signal_graph_destroy)
		self.signal_graphs[mac] = signal_window

	def on_signal_graph_destroy(self, window, mac):
		del self.signal_graphs[mac]

	def set_battery_bar(self, percent):
		if percent is not False:
			self.battery_bar.set_text("%s%%" % percent)
			self.battery_bar.set_fraction(percent / 100)
		else:
			self.battery_bar.set_text("-")
			self.battery_bar.set_fraction(0)

	def on_file_import(self, widget):
		file_import_window = FileImportWindow(self.networks, self.networks_queue_progress)
		file_import_window.gtkwin.set_transient_for(self.gtkwin)
		file_import_window.gtkwin.set_modal(True)

	def on_file_export(self, widget, export_format, extension, amount):
		dialog = Gtk.FileChooserDialog(title="Export as %s" % (export_format),
			parent=self.gtkwin, action=Gtk.FileChooserAction.SAVE)
		dialog.add_button(Gtk.STOCK_SAVE, Gtk.ResponseType.OK)
		dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
		dialog.set_do_overwrite_confirmation(True)
		dialog.set_current_name("kismon.%s" % extension)

		filename = False
		if dialog.run() == Gtk.ResponseType.OK:
			filename = dialog.get_filename()
		dialog.destroy()
		if filename == False:
			return

		if amount == "Filtered":
			networks = []
			for mac in self.export_networks:
				if self.export_networks[mac] is True:
					networks.append(mac)
		else:
			networks = None

		self.networks.export_networks(export_format, filename, networks)

	def export_add_network(self, mac):
		self.export_networks[mac] = True

	def export_remove_network(self, mac):
		self.export_networks[mac] = False

	def update_statusbar(self):
		if self.map is not None:
			on_map = len(self.map.markers)
		else:
			on_map = 0

		text = "Networks: %s in the current session, %s total, %s in the network list, %s on the map" % \
			(len(self.networks.recent_networks), len(self.networks.networks), len(self.network_list.network_iter), on_map)
		self.statusbar.push(self.statusbar_context, text)

	def on_channel_config(self, widget):
		win = ChannelWindow(self.sources, self.client)

class LogList:
	def __init__(self, config):
		self.rows = []
		self.config = config
		self.treeview = Gtk.TreeView()
		num=0
		for column in ("Time", "Message"):
			tvcolumn = Gtk.TreeViewColumn(column)
			self.treeview.append_column(tvcolumn)
			cell = Gtk.CellRendererText()
			tvcolumn.pack_start(cell, True)
			tvcolumn.add_attribute(cell, 'text', num)
			tvcolumn.set_sort_column_id(num)
			tvcolumn.set_clickable(True)
			num += 1

		self.store = Gtk.ListStore(
			GObject.TYPE_STRING, #time
			GObject.TYPE_STRING, #message
			)
		self.treeview.set_model(self.store)

		log_scrolled = Gtk.ScrolledWindow()
		log_scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		log_scrolled.set_shadow_type(Gtk.ShadowType.NONE)
		log_scrolled.add(self.treeview)

		self.widget = log_scrolled

	def add(self, message):
		if not self.cleanup():
			return

		row = self.store.append([show_timestamp(time.time()), message])
		path = self.store.get_path(row)
		self.treeview.scroll_to_cell(path)
		self.rows.append(row)

	def cleanup(self, new=1):
		max_rows = self.config["log_list_max"]
		num_rows = len(self.rows)

		if max_rows == -1:
			return True
		if num_rows == 0 and max_rows == 0:
			return False

		if max_rows - new < 0:
			stop = 0
		else:
			stop = max_rows - new

		while num_rows > stop:
			row = self.rows.pop(0)
			self.store.remove(row)
			num_rows -= 1

		if max_rows == 0:
			return False

		return True

class NetworkList:
	def __init__(self, networks, locate_network_on_map, on_signal_graph):
		self.network_lines = {}
		self.network_iter = {}
		self.network_selected = None
		self.locate_network_on_map = locate_network_on_map
		self.on_signal_graph = on_signal_graph
		self.networks = networks

		self.networks.notify_add_list["network_list"] = self.add_network
		self.networks.notify_remove_list["network_list"] = self.remove_network
		self.networks.disable_refresh_functions.append(self.pause)
		self.networks.resume_refresh_functions.append(self.resume)

		self.treeview = Gtk.TreeView()
		self.treeview.connect("button-press-event", self.on_treeview_clicked)
		num=0
		columns=("BSSID", "Type", "SSID", "Ch", "Crypt",
			"First Seen", "Last Seen", "Latitude", "Longitude",
			"Signal dbm", "Comment")
		for column in columns:
			renderer = Gtk.CellRendererText()
			if column == "Comment":
				renderer.set_property('editable', True)
				renderer.connect("editing-started", self.on_comment_editing_started)
			elif column == "Signal dbm":
				renderer = Gtk.CellRendererProgress()

			tvcolumn = Gtk.TreeViewColumn(column, renderer, text=num)
			self.treeview.append_column(tvcolumn)
			cell = Gtk.CellRendererText()
			tvcolumn.pack_start(cell, True)
			tvcolumn.set_sort_column_id(num)
			tvcolumn.set_clickable(True)
			tvcolumn.set_resizable(True)
			tvcolumn.connect("clicked", self.on_column_clicked)
			tvcolumn.num = num
			if column == "Signal dbm":
				tvcolumn.add_attribute(renderer, "value", 11)
			num+=1
		self.treeview.show()

		self.store = Gtk.ListStore(
			GObject.TYPE_STRING, #mac
			GObject.TYPE_STRING, #type
			GObject.TYPE_STRING, #ssid
			GObject.TYPE_INT, #channel
			GObject.TYPE_STRING, #cryptset
			GObject.TYPE_STRING, #firsttime
			GObject.TYPE_STRING, #lasttime
			GObject.TYPE_FLOAT, #lat
			GObject.TYPE_FLOAT, #lon
			GObject.TYPE_INT, #signal dbm
			GObject.TYPE_STRING, #comment
			GObject.TYPE_INT, #signal dbm + 100 (progressbar)
			)
		self.treeview.set_model(self.store)

		scrolled = Gtk.ScrolledWindow()
		scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		scrolled.add(self.treeview)

		frame = Gtk.Frame()
		frame.set_label("Networks")
		frame.add(scrolled)

		self.widget = frame

		self.store.set_sort_column_id(6, Gtk.SortType.DESCENDING)

		network_popup = Gtk.Menu()
		locate_item = Gtk.MenuItem.new_with_label('Locate on map')
		network_popup.append(locate_item)
		locate_item.connect("activate", self.on_locate_marker)

		signal_item = Gtk.MenuItem.new_with_label('Signal graph')
		network_popup.append(signal_item)
		signal_item.connect("activate", self.on_signal_graph)

		network_popup.show_all()
		self.network_popup = network_popup

	def on_column_clicked(self, widget):
		self.treeview.set_search_column(widget.num)

	def on_comment_editing_started(self, widget, editable, path):
		editable.connect("editing-done", self.on_comment_editing_done)

	def on_comment_editing_done(self, widget):
		network = self.networks.get_network(self.network_selected)
		network['comment'] = widget.get_text()
		self.add_network(self.network_selected)

	def add_network(self, mac):
		network = self.networks.get_network(mac)
		try:
			crypt = self.crypt_cache[network["cryptset"]]
		except KeyError:
			crypt = decode_cryptset(network["cryptset"], True)
			self.crypt_cache[network["cryptset"]] = crypt

		if network["ssid"] == "":
			ssid_str = "<no ssid>"
		else:
			ssid_str = network["ssid"]

		if "signal_dbm" in network and len(network["signal_dbm"]) == 3:
			signal = network["signal_dbm"]["last"]
		else:
			signal = 0

		line = [mac,
				network["type"],
				ssid_str,
				network["channel"],
				crypt,
				show_timestamp(network["firsttime"]),
				show_timestamp(network["lasttime"]),
				network["lat"],
				network["lon"],
				signal,
				network['comment'],
				signal+100
				]
		try:
			old_line = self.network_lines[mac]
		except:
			old_line = None
		self.network_lines[mac] = line

		if mac in self.network_iter:
			network_iter = self.network_iter[mac]
			num = 0
			for value in line:
				if old_line is not None and old_line.pop(0) == value:
					num += 1
					continue
				self.store.set_value(network_iter, num, value)
				num += 1
		else:
			self.network_iter[mac] = self.store.append(line)

			adj = self.treeview.get_vadjustment()
			self.scroll_value = int(adj.get_value())
			if self.scroll_value == 0:
				GLib.idle_add(self.treeview.scroll_to_point, -1, 0)

	def remove_network(self, mac):
		try:
			network_iter = self.network_iter[mac]
		except KeyError:
			return

		self.store.remove(network_iter)
		del(self.network_iter[mac])

	def pause(self):
		self.treeview.freeze_child_notify()
		self.treeview.set_model(None)

	def resume(self):
		self.treeview.set_model(self.store)
		self.treeview.thaw_child_notify()

	def on_treeview_clicked(self, treeview, event):
		x = int(event.x)
		y = int(event.y)
		pthinfo = treeview.get_path_at_pos(x, y)
		if pthinfo is None:
			return

		path, col, cellx, celly = pthinfo
		treeview.grab_focus()
		treeview.set_cursor(path, col, 0)
		network_iter = self.store.get_iter(path)
		mac = self.store.get_value(network_iter, 0)
		self.network_selected = mac

		if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS: # double click
			self.on_locate_marker(None)
		elif event.button == 3: # right click
			self.network_popup.popup(None, None, None, 0, event.button, event.time, )

	def on_locate_marker(self, widget):
		if self.locate_network_on_map is not None:
			self.locate_network_on_map(self.network_selected)

class MapWindow(KismonWindows):
	def __init__(self, map_widget):
		KismonWindows.__init__(self)
		self.gtkwin.set_title("Map")
		self.gtkwin.show()
		self.gtkwin.set_size_request(640, 480)
		self.map_widget = map_widget.widget
		self.gtkwin.add(self.map_widget)

	def on_destroy(self, window):
		self.remove_map()
		self.gtkwin = None

	def remove_map(self):
		if self.gtkwin is not None:
			self.gtkwin.remove(self.map_widget)

	def hide(self):
		self.gtkwin.hide()

def show_timestamp(timestamp):
	time_format = "%Y/%m/%d %H:%M:%S"
	return time.strftime(time_format, time.localtime(timestamp))

if __name__ == "__main__":
	try:
		from . import core
	except SystemError:
		import core
	core.main()


renumbering = []

def showing():
    with open('list.txt', 'r') as file:
        s = file.read()
        print(s)

def writing(list):
    num = len(list) + 1
    new = input('작성 > ')
    list.append(new)
    renew = "\n" + str(num) + ". " + new
    renumbering.append(renew)
    with open('list.txt', 'w') as file:
        file.writelines(renumbering)
    print(len(list), "번째 글이 성공적으로 작성되었습니다.")

def correcting(list):
    num = int(input('몇 번째 글을 수정하실 건가요?'))
    buffer = input('수정 > ')
    list[num-1] = buffer
    renumbering[num-1] = "\n" + str(num) + ". " + buffer
    with open('list.txt', 'w') as file:
        file.writelines(renumbering)
    print(num, "번째 글이 성공적으로 작성되었습니다.")

def deleting(list):
    renumbering = []
    num = int(input('몇 번째 글을 지울까요?'))
    list.remove(list[num-1])
    for i in range(len(list)):
        new = "\n" + str(i) + ". " + list[i]
        renumbering.append(new)
    with open('list.txt', 'w') as file:
       file.writelines(renumbering)


# Needed on case-insensitive filesystems
from __future__ import absolute_import

# Try to import PIL in either of the two ways it can be installed.
try:
    from PIL import Image, ImageDraw
except ImportError:  # pragma: no cover
    import Image
    import ImageDraw

import qrcode.image.base
from qrcode.image import Style

import base64
import cStringIO
import webcolors

class PilImage(qrcode.image.base.BaseImage):
    """
    PIL image builder, default format is PNG.
    """
    kind = "PNG"
    mask = None

    def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        if fill_color.lower() != "black" or back_color.lower() != "white":
            if back_color.lower() == "transparent":
                mode = "RGBA"
                back_color = None
            else:
                mode = "RGB"
        else:
            mode = "1"

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        try:
            self.back_color = webcolors.name_to_rgb(back_color)
        except:
            self.back_color = back_color
        self._idr = ImageDraw.Draw(img)
        return img

    def draw(self, row, col, style=Style.SQUARE):
        if self.escavate and not self.is_empty(row, col):
            return

        if style == Style.SQUARE:
            self._drawrect(row, col)
        elif style == Style.DOT:
            self._drawround(row, col)

    def _drawrect(self, row, col):
        box = self.pixel_box(row, col)
        self._idr.rectangle(box, fill=self.fill_color)

    def _drawround(self, row, col):
        circle_offset = self.box_size / 10
        box = self.pixel_box(row, col)
        box = (box[0][0]+circle_offset, box[0][1]+circle_offset, box[1][0]-circle_offset, box[1][1]-circle_offset)
        self._idr.ellipse(box, fill=self.fill_color)

    def add_logo(self, logo, override_img=None):
        image_string = cStringIO.StringIO(base64.b64decode(logo))
        img = Image.open(image_string)
        new_size = int(self.pixel_size / 6.2) * 2
        img = img.resize((new_size, new_size))
        center = self.pixel_size / 2
        (override_img or self._img).paste(img, (center - new_size/2, center - new_size/2, center + new_size/2, center + new_size/2), img)

    def set_mask(self, logo):
        img = Image.new("RGB", (self.pixel_size, self.pixel_size), "white")
        self.add_logo(logo, img)
        self.mask = img

    def save(self, stream, format=None, **kwargs):
        if format is None:
            format = kwargs.get("kind", self.kind)
        if "kind" in kwargs:
            del kwargs["kind"]
        if 'size' in kwargs:
            size = int(kwargs.get('size'))
            self._img = self._img.resize((size, size), Image.ANTIALIAS)
        self._img.save(stream, format=format, **kwargs)

    def __getattr__(self, name):
        return getattr(self._img, name)


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

@author: Lukas Sandström
"""

import RSSscpi.znb

import logging

class VISAFilter(logging.Filter):
    def filter(self, record):
        """
        :param logging.LogRecord record:
        :return: bool
        """
        if record.name.endswith(".VISA") and record.levelno <= logging.INFO:
            return False
        return True

# logging.basicConfig(level=logging.WARN, filename=__file__[:-3]+"_log.txt", filemode="w")
logging.basicConfig()
logger = logging.getLogger()
logger.handlers[0].addFilter(VISAFilter())  # don't print VISA INFO logging to the console

znb_ip = "192.168.56.101"

# VISA command logging
# Error checking / handling

znb = RSSscpi.znb.connect_ethernet(znb_ip)

znb.visa_logger.setLevel(logging.DEBUG)
znb.visa_logger.addHandler(logging.FileHandler(filename=__file__[:-3]+"_visa_log.txt", mode="wb"))
znb.init()

# Instrument setup
# Number of points
# Start and stop frequency
# Source power
# IF bandwidth

znb.RST.w()
znb.INITiate.CONTinuous.ALL().w("OFF")

ch = znb.get_channel(1)
ch.name = "SP_ch_1"
dia1 = znb.get_diagram(1)

ch.configure_freq_sweep(start_freq=100e6, stop_freq=3e9, points=801, power=0)

# Add traces
ch.active_trace.delete()  # remove the predefined trace
tr_s11 = ch.create_trace("S11", "S11", dia1)
tr_s21 = ch.create_trace("S21", "S21", dia1)
tr_s12 = ch.create_trace("S12", "S12", dia1)
tr_s22 = ch.create_trace("S22", "S22", dia1)

# Create a diagram with the T-check equation trace
dia2 = znb.get_diagram(2)
dia2.STATe().w("ON")
dia2.name = "Tcheck"
tr_Tcheck = ch.create_trace("T_check", "S11", dia2)
tr_Tcheck.math_equation = "linMag(S11*(Re(S21)-Im(S21)) + S12*(Re(S22)-Im(S22))) / ((1-linMag(S11)^2-linMag(S12)^2)*(1-linMag(S21)^2-linMag(S22)^2))^0.5"
tr_Tcheck.math_is_enabled = True
tr_Tcheck.trace_format = "REAL"
tr_Tcheck.scale_top = 1.25
tr_Tcheck.scale_bottom = 0.75
tr_Tcheck.ref_level = 1
tr_Tcheck.ref_pos = 50

# Add limit lines

# Make a measurement sweep
ch.init_sweep()
znb.query_OPC()


#coding:utf-8
import json
import pymongo
def save_to_file(file_name, contents):
    fh = open(file_name, 'a+',encoding='utf-8')
    fh.write(contents)
    fh.close()
# 读取json 文件
path="C:/Users/Administrator/Desktop/呼伦贝尔new.json"
# 链接62Mongo 数据库查询
client = pymongo.MongoClient(host='172.16.4.62', port=27017)
db_auth = client.operation
db_auth.authenticate("intelligent", "intelligent")
collection = db_auth.laws
f =open(path)
cid=f.read()
list=cid.split("\n")
count=0
findlaw=0
for s in range(len(list)):
    count+=1
    # 不模糊查询,去除左右书名号,尖角号转书名号, 只有开头结尾都是书名号才去除
    try:
        jsons=json.loads(str(list[s]).replace("&gt", "》").replace("&lt", "《").replace("&#60", "《").replace("&#62", "》").replace("\t",""))
        basisList=jsons.get("basisSummaryDefinition")
        if(jsons.get("competentDeptName")==""):
            jsons["competentDeptName"]=""
        for j in range(len(basisList)):
            lawname = str(basisList[j]["law"]).replace("&gt", "》").replace("&lt", "《").replace("&#60", "《").replace("&#62", "》")
            if(lawname.startswith("《") and lawname.endswith("》")):
                lawname = lawname[1:len(lawname)-1]
                if (lawname.startswith("《") and lawname.endswith("》")):
                    lawname = lawname[1:len(lawname)-1]
            lawlist=collection.find({"law":lawname}).sort("implementDate",-1)
            for law in lawlist:
                basisList[j]['uniqId']=law.get("uniqid")
                findlaw+=1
                break
        jsons["basisSummaryDefinition"]=basisList
        list[s]=json.dumps(jsons)
        content=list[s]+"\n"
        # 输出名自定义
        save_to_file("C:/Users/Administrator/Desktop/呼伦贝尔new1.json",content)
        print(count)
        print("find",findlaw)
    except Exception as e:
        print(e)


# -*- coding: utf-8 -*-
"""
Created on Wed May 23 17:41:53 2018

@author: ishida
"""
import pandas as pd
import glob

class CSV():
    def __init__(self, path):
        #pathを格納する
        self.path = path
        #pathに存在する、拡張子が.csvのファイルの絶対パスを一つ取り出す
        self.csvs = path + '/' + '*.csv'
        #filesの中にcsvsに入るものを検索してすべてをリストにして入れる
        self.files = glob.glob(self.csvs)
        self.counter = 1
        self.num_of_csvs = len(self.files)

    def run(self):
        for file_ in self.files:
            #データフレームとしてfilesのcsvファイルを読み取る
            df = pd.read_csv(file_, index_col = 0)
            #pandasのplotメソッドによってcsvファイルのtime[ t]という名前のデータ列をx軸に、voltage [mV]をy軸に設定している
            df.plot(x='T[ms]', y='V[mV]')
            #何個中何番目のファイルを処理しているかを表示する
            print(str(self.counter) + " / " + str(self.num_of_csvs) + " 個目のファイルを処理します")
            self.counter += 1

#csvファイルが置いてある場所を指定する
path = "C:/Users/ishida/Desktop"
#インスタンスを作成
c = CSV(path)
#pathにあるcsvファイルをpandasのplotメソッドを用いてグラフにする関数を走らせる
c.run()


import random

import matplotlib.image as mpimg
import numpy as np
import scipy.io
import functions as fn
from functions import nnCostFunction
from functions import optimize
from functions import predict
from functions import sigmoidGradient
from matplotlib import pyplot as plt

show_image = True
mat_dict = scipy.io.loadmat('./data/ex4data1.mat')
X = mat_dict['X']
print(X.shape)
y = mat_dict['y']
print(y.size)
# y = np.array([x - 1 if x < 10 else 0 for x in y])
num_labels = 10

m = X.shape[0]
print(m)

print(X[1].shape)
print(X[1].reshape((20, 20)).shape)
for i in random.sample(range(5000), 2):
    plt.imshow(X[i].reshape((20, 20)).T, cmap='gray',
               interpolation='bicubic')  # interpolation = 'bicubic'
    print(y[i])
    if show_image:
        plt.show()
img = mpimg.imread('./images/nn.png')
imgplot = plt.imshow(img)

if show_image:
    plt.show()

# % Weight regularization parameter (we set this to 0 here).
input_layer_size = 400  # % 20x20 Input Images of Digits
hidden_layer_size = 25  # % 25 hidden units
num_labels = 10  # % 10 labels, from 0 to 9
lambd = 1

parameters = fn.initialize_parameters(
    input_layer_size, hidden_layer_size, num_labels)
print(parameters["W1"].shape)
W1 = parameters["W1"]
b1 = parameters["b1"]
print(W1.shape)
W2 = parameters["W2"]
b2 = parameters["b2"]

yVec = np.zeros((m, num_labels))  # each number became bit vector
for l in range(m):
    idx = y[l]  # set bit according to index
    if idx == 10:
        idx = 0
    yVec[l, idx] = 1

J, cache = fn.nnCostFunction(W1, W2, b1, b2, input_layer_size, hidden_layer_size, num_labels, X, yVec, lambd)
print('Cost at parameters (loaded from ex4weights): ' +
      str(J) + ' (this value should be about 0.287629)')
print(fn.sigmoidGradient(0))
assert (fn.sigmoidGradient(0) == 0.25)

w1, w2, b1, b2 = fn.optimize(W1, W2, b1, b2, input_layer_size,
                             hidden_layer_size, num_labels, X, yVec, 1, 5000, True)

pred = fn.predict(w1, w2, b1, b2, X)

res = (np.count_nonzero(pred == np.array(y).reshape(m)) / m) * 100

print('Training Set Accuracy: in ' + str(res) + '%')

for i in random.sample(range(5000), num_labels):
    r = pred[i]
    res = 'The predicted value is ' + \
        str(r) + ', actual y is ' + str(y[i]) + '...'
    print(res)
    plt.imshow(X[i].reshape((20, 20)).T, cmap='gray',
               interpolation='bicubic')  # interpolation = 'bicubic'
    if show_image:
        plt.show()


#Import necessary libraries
import cv2
from darkflow.net.build import TFNet
import numpy
import time

#threshold specifies the confidence needed to create a box, model specifies the location, load is to setup the weights,  gpu utilizes the graphics card (I have a NVIDIA GeForce)
options = {'threshold': 0.2,'model': 'tiny/yolov2.cfg','load': 'bin/yolov2.weights','gpu': 1.0}

#This initializes the model to make predictions
network = TFNet(options)

#Create a list of random colours for variation of box colours; it will be an array that is 3 elements long
randcolour = [tuple(numpy.random.rand(3)*255) for i in range(10)]

#Specify the webcam as the camera being used (0 is the default camera)
capt = cv2.VideoCapture(0)

#Set the frame size to the full 1080p
capt.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
capt.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

while True:
    #Time how long each frame takes
    start = time.time()
    #Read from capture device
    ret, frame = capt.read()
    #This line will pass in the frame and make the prediction
    results = network.return_predict(frame)
    #This loop will run while the capture device is running
    if ret:
        #This will use the random colour and display the prediction as well as the confidence level
        for color, result in zip(randcolour, results):
            #Takes the top left and bottom right coordinates
            coord1 = (result['topleft']['x'], result['topleft']['y'])
            coord2 = (result['bottomright']['x'], result['bottomright']['y'])
            label = result['label']
            conf = result['confidence']
            text = '{}: {:.0f}%'.format(label, conf * 100)
            frame = cv2.rectangle(frame, coord1, coord2, color, 7)
            frame = cv2.putText(
                frame, text, coord1, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
        #Settings for frame window
        cv2.imshow('frame', frame)
        #Print out the frames per second with 1 decimal
        print('FPS {:.1f}'.format(1 / (time.time() - start)))

    #The e key will exit the window
    if cv2.waitKey(1) & 0xFF == ord('e'):
        break

#Release capture device
capt.release()
#Exits the windows
cv2.destroyAllWindows()


def solve():
  desired_sequence = [9, 9, 0, 9, 4, 1]

  elf_to_recipe = [0, 1]
  recipes = [3, 7]

  while True:
    total = recipe_sum(elf_to_recipe, recipes)
    new_recipes = [int(c) for c in str(total)]
    for r in new_recipes:
      recipes.append(r)
      if len(recipes) < len(desired_sequence):
        continue
      if sequence_equals(desired_sequence, recipes[-len(desired_sequence):]):
        print(len(recipes)-len(desired_sequence))
        return

    for i in range(0, len(elf_to_recipe)):
      r_index = elf_to_recipe[i]
      steps = 1 + recipes[r_index]
      new_index = ((r_index + steps) % len(recipes))
      elf_to_recipe[i] = new_index

def sequence_equals(s1, s2):
  if len(s1) != len(s2):
    return False
  for i in range(0, len(s1)):
    if s1[i] != s2[i]:
      return False
  return True

def show(recipes, elf_to_recipe):
  outputs = []
  for i in range(0, len(recipes)):
    if i == elf_to_recipe[0]:
      outputs.append("("+str(recipes[i])+")")
    elif i == elf_to_recipe[1]:
      outputs.append("["+str(recipes[i])+"]")
    else:
      outputs.append(" "+str(recipes[i])+" ")

  return " ".join(outputs)

def recipe_sum(elf_to_recipe, recipes):
  sum = 0
  for recipe_idx in elf_to_recipe:
    sum = sum + recipes[recipe_idx]
  return sum

if __name__ == '__main__':
  solve()


from django.http import HttpResponse, QueryDict
from django.views.generic import View, TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from ..system.models import UnitOfMeasurement
from ..things.models import Thing, ThingSensorCrossRef, SensorDataType, SensorData, Sensor, SensorLocationCrossRef
from ..events.models import EVENT_STATUS_CODES, EVENT_TIME_TYPES, Event, EventType, EventPersonCrossRef, EventLocationCrossRef, EventSensorDataCrossRef, DataDebitEventCrossRef
from ..locations.models import Location, LocationType
from ..users.models import Person
from django_extensions.db.fields import UUIDField
from ..users.models import Recipient
from datetime import datetime
import json
from pprint import pformat
import logging
from views import ApiException
import re

from ..locations.models import LocationPersonCrossRef, LocationThingCrossRef, LocationSensorCrossRef, LocationToLocationCrossRef

from ..bundles.models import Bundle_Filter, Bundle_Union, Bundle_Join
from django.db import connection

class NavigationViewBase(View):
	def add_error(self, error):
		self.response_data['errors'].append(error)
	# Check to see if the current request has any errors
	def has_errors(self):
		return len(self.response_data['errors']) > 0

	def __init__(self, **kwargs):
		# Set blank response data
		self.response_data = {
			'response': {},
			'errors': [
			]
		}

	def response(self, request, *args, **kwargs):
		# Set the response result based on errors
		# if not self.has_errors():
		# 	self.response_data['response'] = 'success'
		# 	self.response_data.pop("errors", None)
		# else:
		# 	self.response_data['response'] = 'error'

		# Return json response
		return HttpResponse(json.dumps(self.response_data), content_type="application/json")

class GetNavigationTreeView(NavigationViewBase):
	"""
		Navigation Tree View

		Retrieves information from all cross reference tables to build up the Navigation Tree for data views:
		(not a strict hierarchy, but a DAG)

		- Person
		|
		|-- Related Persons
		|  |
		|  |- Person
		|
		|-- Locations (LocationPersonCrossRef)
		|  |
		|  |
		|  |-- Location (LocationToLocationCrossRef; relationship_type = "Private Residence")
		|     |
		|     |-- Location (LocationToLocationCrossRef; relationship_type = "Room in a House")
		|     |  |
		|     |  |- Location (LocationToLocationCrossRef; relationship_type = "Room in a Room")
		|     |
		|     |-- Thing (LocationThingCrossRef; Room to Thing)
		|     |  |
		|     |  |- Property (Thing Property)
		|     |  |- Sensor (Thing Sensor)
		|     |
		|     |- Sensor (LocationSensorCrossRef)
		|
		|-- Things (ThingPersonCrossRef)
		|  |
		|  |- Thing
		|
		|-- Interactions
		   |
		   |- Emails
		   |- Messages
		   |- Social Media

	"""

	def construct_info_dictionary(self, data, dataType):
		r_info = {}
		for item in data:
			r_info[dataType+str(item.id)] = {
				"properties": {
					"id": item.id,
					"name": (item.first_name + " " + item.last_name if dataType == "person" else item.name),
					"type": dataType
				},
				"id": item.id,
				"children": [],
				"parents": []
			}
		return r_info

	def get_persons(self):
		try:
			persons = Person.objects.all()
			return self.construct_info_dictionary(persons, "person")
		except Person.DoesNotExist:
			return ApiException("No person exists")

	def get_locations(self):
		try:
			locations = Location.objects.all()
			return self.construct_info_dictionary(locations, "location")
		except Location.DoesNotExist:
			return ApiException("No location exists")

	def get_things(self):
		try:
			things = Thing.objects.all()
			return self.construct_info_dictionary(things, "thing")
		except Thing.DoesNotExist:
			return ApiException("No thing exists")

	def get_sensors(self):
		try:
			sensors = Sensor.objects.all()
			return self.construct_info_dictionary(sensors, "sensor")
		except Sensor.DoesNotExist:
			return ApiException("No sensor exists")

	def get_personLocationCrossrefs(self):
		try:
			relationships = LocationPersonCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "person"+str(rel.person.id)
				destination = "location"+str(rel.location.id)
				links.append({"source": source, "destination": destination})
			return links
		except LocationPersonCrossRef.DoesNotExist:
			raise ApiException("No Locations could be found in the Location - Person cross references")

	def get_locationThingCrossrefs(self):
		try:
			relationships = LocationThingCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "location"+str(rel.location.id)
				destination = "thing"+str(rel.thing.id)
				links.append({"source": source, "destination": destination})
			return links
		except LocationThingCrossRef.DoesNotExist:
			raise ApiException("No Things could be found in the Location")

	def get_locationSensorCrossrefs(self):
		try:
			relationships = LocationSensorCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "location"+str(rel.location.id)
				destination = "sensor"+str(rel.sensor.id)
				links.append({"source": source, "destination": destination})
			return links
		except LocationSensorCrossRef.DoesNotExist:
			raise ApiException("No Things could be found in the Location")

	def get_sensorLocationCrossrefs(self):
		try:
			relationships = SensorLocationCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "location"+str(rel.location.id)
				destination = "sensor"+str(rel.sensor.id)
				links.append({"source": source, "destination": destination})
			return links
		except SensorLocationCrossRef.DoesNotExist:
			raise ApiException("No Things could be found in the Location")

	def get_locationLocationCrossrefs(self):
		try:
			relationships = LocationToLocationCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "location"+str(rel.loc_one.id)
				destination = "location"+str(rel.loc_two.id)
				links.append({"source": source, "destination": destination})
			return links
		except LocationToLocationCrossRef.DoesNotExist:
			raise ApiException("No Location crossrefs found")

	def get_thingSensorCrossrefs(self):
		try:
			relationships = ThingSensorCrossRef.objects.all()
			links = []
			for rel in relationships:
				source = "thing"+str(rel.thing.id)
				destination = "sensor"+str(rel.sensor.id)
				links.append({"source": source, "destination": destination})
			return links
		except ThingSensorCrossRef.DoesNotExist:
			raise ApiException("No Sensors could be found in Things")

	def get_nodes(self):
		persons = self.get_persons()
		locations = self.get_locations()
		things = self.get_things()
		sensors = self.get_sensors()

		nodes = {}
		nodes.update(persons)
		nodes.update(locations)
		nodes.update(things)
		nodes.update(sensors)
		return nodes

	def get_links(self):
		links = []
		links = links + self.get_personLocationCrossrefs()
		links = links + self.get_locationThingCrossrefs()
		links = links + self.get_thingSensorCrossrefs()
		links = links + self.get_locationSensorCrossrefs()
		links = links + self.get_sensorLocationCrossrefs()
		links = links + self.get_locationLocationCrossrefs()
		return links

	@method_decorator(csrf_exempt)
	def dispatch(self, *args, **kwargs):
		return super(GetNavigationTreeView, self).dispatch(*args, **kwargs)

	def get(self, request, *args, **kwargs):
		logger = logging.getLogger("navbar")
		try:
			nodes = self.get_nodes()
			links = self.get_links()
			self.response_data['response'] = {"nodes": nodes, "links": links}
		except ApiException as error:
			error_string = str(error) if str(error) != "" else "Unknown error has occured."
			self.add_error(error_string)

		return self.response(request, *args, **kwargs)

class FilterSensorData(NavigationViewBase):

	@method_decorator(csrf_exempt)
	def dispatch(self, *args, **kwargs):
		return super(FilterSensorData, self).dispatch(*args, **kwargs)

	def get_allSensorData(self, sensors, limit=200, page=0):
		data = list(SensorData.objects.filter(sensor__id__in=sensors).values("source_description", "value", "sensor__name", "sensor_id", "type__name", "unit__name", "date_created")[page*limit:(page+1)*limit])
		for record in data:
			record['date_created'] = str(record['date_created'])
		return data

	def post(self, request, *args, **kwargs):
		logger = logging.getLogger("navbar")
		try:
			filter = json.loads(request.body)
			sensors = filter['sensors']
			logger.debug(sensors)
			self.response_data['response'] = self.get_allSensorData(sensors, filter['limit'], filter['page'])
		except ApiException as error:
			error_string = str(error) if str(error) != "" else "Unknown error has occured."
			self.add_error(error_string)

		self.add_error('Not implemented')
		return self.response(request, *args, **kwargs)

class GetBundles(NavigationViewBase):

	@method_decorator(csrf_exempt)
	def dispatch(self, *args, **kwargs):
		return super(GetBundles, self).dispatch(*args, **kwargs)

	def get_bundles(self):
		filters = list(Bundle_Filter.objects.all().values('id', 'name', 'description'))
		unions = list(Bundle_Union.objects.all().values('id', 'name', 'description'))
		joins = list(Bundle_Join.objects.all().values('id', 'name', 'description'))

		return {
			"filter": filters,
			"union": unions,
			"join": joins
		}

	def get(self, request, *args, **kwargs):
		logger = logging.getLogger("navbar")
		try:
			bundles = self.get_bundles()
			self.response_data['response']['data'] = bundles
		except ApiException as error:
			error_string = str(error) if str(error) != "" else "Unknown error has occured."
			self.add_error(error_string)

		return self.response(request, *args, **kwargs)

class GetBundleData(NavigationViewBase):

	@method_decorator(csrf_exempt)
	def dispatch(self, *args, **kwargs):
		return super(GetBundleData, self).dispatch(*args, **kwargs)

	def dictfetchall(self, cursor):
		"""Returns all rows from a cursor as a dict"""
		desc = cursor.description
		return [
			dict(zip([col[0] for col in desc], map(str, row) )) for row in cursor.fetchall()
		]

	def dictfetchall(self, cursor, columns):
		return [
			dict(zip(columns, map(str, row) )) for row in cursor.fetchall()
		]

	date_regex = re.compile(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\+\d{2}:\d{2})')
	like_regex = re.compile(r'LIKE %(.*)%')
	columns = ["source_description", "value", "sensor__name", "sensor_id", "type__name", "unit__name", "date_created"]

	def get_querysetData(self, bundle):
		""" Handle the logic of extracting data from database using the bundle's queryset """

		qs = bundle.querySet().values(*self.columns)

		strQuery = str(qs.query)
		strQuery = re.sub(self.date_regex, r"'\1'", strQuery)
		strQuery = re.sub(self.like_regex, r"""LIKE '%\1%'""", strQuery)

		cursor = connection.cursor()
		cursor.execute(strQuery)
		data = self.dictfetchall(cursor, self.columns)

		return (data, qs.query.__str__())

	def get_data(self, bundle_type, bundle_id):
		""" Get data for the given bundle type and id """

		logger = logging.getLogger("navbar")
		logger.debug(bundle_id)
		bundle = None
		if (bundle_type == "filter"):
			bundle = Bundle_Filter.objects.get(id=int(bundle_id))
			return self.get_querysetData(bundle)
		elif (bundle_type == "union"):
			bundle = Bundle_Union.objects.get(id=int(bundle_id))
			return self.get_querysetData(bundle)
		elif (bundle_type == "join"):
			bundle = Bundle_Join.objects.get(id=int(bundle_id))
			query = str(bundle.rawQuery())
			strQuery = str(query)
			strQuery = re.sub(self.date_regex, r"'\1'", strQuery)
			strQuery = re.sub(self.like_regex, r"""LIKE '%\1%'""", strQuery)

			cursor = connection.cursor()
			cursor.execute(strQuery)
			dbdata = cursor.fetchall()

			rdata = {}
			bundleNames = bundle.serializeBundleNames()
			for bundleName in bundleNames:
				rdata[bundleName] = []
			for row in dbdata:
				chunks=[row[x:x+len(self.columns)] for x in xrange(0, len(row), len(self.columns))]
				for (c, bundleName) in zip(chunks, bundleNames):
					rdata[bundleName].append( dict(zip(self.columns, map(str, c) )) )

			return (rdata, query)
		else:
			raise(ApiException("Invalid parameters"))

	def post(self, request, *args, **kwargs):
		logger = logging.getLogger("navbar")
		try:
			filter = json.loads(request.body)
			bundle_type = filter['bundle_type']
			logger.debug(bundle_type)
			bundle = filter['bundle']
			logger.debug(bundle)
			(self.response_data['response']['data'], self.response_data['response']['query']) = self.get_data(bundle_type, bundle)
		except ApiException as error:
			error_string = str(error) if str(error) != "" else "Unknown error has occured."
			self.add_error(error_string)
		except KeyError as error:
			error_string = "Incomplete parameters."
			self.add_error(error_string)

		self.add_error('Not implemented')
		return self.response(request, *args, **kwargs)


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
rng = np.random

# mock data
x = rng.rand(50)*10
y = 2*x + rng.randn(50)

# linear regression
model = LinearRegression()

x_new = x.reshape(-1,1)

# train
model.fit(x_new,y)

# test model
xfit = np.linspace(-1,11)
xfit_new = xfit.reshape(-1,1)

yfit = model.predict(xfit_new)

# analysis model
plt.scatter(x,y)
plt.plot(xfit,yfit)
plt.show()


import typing
from datetime import timedelta

import click
from loguru import logger

from sqlite2pg import DEV_LOG_CONFIG

__all__: typing.List[str] = [
    "S2PLogger",
]

LOG_FILE_FMT: str = "./sqlite2pg.{time:X}.log"

class S2PLogger:
    """Logging for the program."""

    FORMAT: str = "<green>{time}</green> | <level>{level: <8}</level> ||| <level>{message}</level>"

    @staticmethod
    def configure(
        enable: bool,
        to_cwd: bool,
        log_level: str,
        retention: int,
    ) -> None:
        """Configures  logger object."""

        logger.remove()

        if not enable:
            logger.disable("sqlite2pg")
            return

        try:
            logger.add(
                LOG_FILE_FMT if to_cwd else (DEV_LOG_CONFIG / LOG_FILE_FMT),
                format=S2PLogger.FORMAT,
                level=log_level.upper(),
                retention=timedelta(days=retention),
            )

        except Exception as e:
            print(e)
            click.secho("ERROR:", fg="red", bold=True)
            click.echo(
                "invalid logging level retrieved from config.\n"
                "please validate your config or run `sqlite2pg config regen`."
            )
            exit(1)

        else:
            logger.debug("logging configuration completed.")


from django.db import models
from main.models import User,Language

# Create your models here.
class ForumSections(models.Model):
    name = models.CharField(max_length=64,unique=True)
    title = models.CharField(max_length=256)
    description = models.TextField()

class Thread(models.Model):
    section = models.ForeignKey(ForumSections,
                                on_delete=models.RESTRICT)
    language = models.ForeignKey(Language,
                                 on_delete=models.RESTRICT)
    title = models.CharField(max_length=512)
    created_by = models.ForeignKey(User,
                                   related_name='forum_thread',
                                   on_delete=models.RESTRICT)
    created_on = models.DateTimeField(auto_now_add = True)
# Thread()

class ThreadPost(models.Model):
    Thread = models.ForeignKey(Thread,
                               on_delete=models.RESTRICT)
    created_by = models.ForeignKey(User,
                                   on_delete=models.RESTRICT,
                                   related_name='forum_post')
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.TextField()
# ThreadPost()


#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')

from gi.repository import Gtk
from gi.repository import GObject

import os
import fcntl
import subprocess

class StreamTextBuffer(Gtk.TextBuffer):
	def __init__(self):
		Gtk.TextBuffer.__init__(self)
		self.IO_WATCH_ID = tuple()

	def bind_subprocess(self, proc):
		self.unblock_fd(proc.stdout)
		watch_id_stdout = GObject.io_add_watch(
			channel   = proc.stdout,
			priority_ = GObject.IO_IN,
			condition = self.buffer_update,
		)

		self.unblock_fd(proc.stderr)
		watch_id_stderr = GObject.io_add_watch(
			channel   = proc.stderr,
			priority_ = GObject.IO_IN,
			condition = self.buffer_update,
		)

		self.IO_WATCH_ID = (watch_id_stdout, watch_id_stderr)
		return self.IO_WATCH_ID

	def buffer_update(self, stream, condition):
		self.insert_at_cursor(stream.read().decode('utf-8'))
		self.textview.scroll_to_mark(self.get_insert(), 0.0, True, 0.5, 0.5)
		return True

	def unblock_fd(self, stream):
		fd = stream.fileno()
		fl = fcntl.fcntl(fd, fcntl.F_GETFL)
		fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

	def set_textview(self, textview):
		self.textview = textview

	def append_text(self, text):
		self.insert_at_cursor(text)
		self.textview.scroll_to_mark(self.get_insert(), 0.0, True, 0.5, 0.5)


#Python Program to Calculate the Area of a Triangle

#If a, b and c are three sides of a triangle. Then,

#s = (a+b+c)/2
#area = √(s(s-a)*(s-b)*(s-c))

#Source Code

# Python Program to find the area of triangle

#a = 25
#b = 50
#c = 70

# Uncomment below to take inputs from the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter
s = (a + b + c) / 2

# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.3f' %area)
print('The semi-perimeter of the triangle is %0.3f' %s)


import time

import numpy as np
from get_score import *
from utils.rgblab import rgb2lab
from utils.rgblab import *
import multiprocessing

from get_score.get_scores import get_score

def cal(color_use_,count,score):
    score_1 = 0;
    score_2 = score;
    t1 = time.time();
    return_score = [];
    return_color = [];
    # color1 = np.linspace(0, 255, 8);
    color1 = np.random.randint(0,255,6);

    for i in range(len(color1)):
        for j in range(len(color1)):
            for k in range(len(color1)):
                color_use_1 = np.transpose(color_use_)
                column_use = [color1[i], color1[j], color1[k]];
                column_use = np.array(column_use);
                color_use_1[count] = column_use;
                color_use_1 = np.transpose(color_use_1);
                score_use = get_score(color_use_1);
                if score_use > score_2 + 0.05:
                    column_1 = column_use;
                    break;
                else:
                    if score_use > score_1:
                        score_1 = score_use;
                        column_1 = column_use;

    color_best_1_lab = rgb2lab(column_1);
    lab_1 = color_best_1_lab[0];
    lab_2 = color_best_1_lab[1];
    lab_3 = color_best_1_lab[2];
    lab_mm_count = 20;
    lab_1_min = lab_1 - lab_mm_count;
    lab_1_max = lab_1 + lab_mm_count;
    lab_2_min = lab_2 - lab_mm_count;
    lab_2_max = lab_2 + lab_mm_count;
    lab_3_min = lab_3 - lab_mm_count;
    lab_3_max = lab_3 + lab_mm_count;
    for i in np.arange(lab_1_min, lab_1_max, 20):
        for j in np.arange(lab_2_min, lab_2_max, 20):
            for k in np.arange(lab_3_min, lab_3_max, 20):
                lab_use = np.array([i, j, k]);
                rgb_use = lab2rgb(lab_use);
                color_2 = np.transpose(color_use_);
                color_2[count] = rgb_use;
                color_2 = np.transpose(color_2);
                score_2_use = get_score(color_2);
                if score_2_use > score + 0.1:
                    score_2 = score_2_use;
                    color_2 = color_2;
                    return_score.append(score_2);
                    return_color.append(color_2);
    return return_color,return_score;
def get_better_color_by_cal_3(color,score):

    color_use_ = color;
    x = len(color[0]);

    msgs = [];
    for count in range(x):
        msgs.append([color_use_,count,score]);
    with multiprocessing.Pool(multiprocessing.cpu_count()) as pool:
        return_inf = pool.starmap(cal, msgs)
    colors = [];
    scores = [];
    for i in range(x):
        if return_inf[i][1] != []:
            colors.append(return_inf[i][0]);
            scores.append(return_inf[i][1]);
    return_colors = [];
    return_scores = [];
    if color == []:
        return_info = 0;
    else:
        if color[0] == []:
            return_info = 0;
        else:
            return_info = 1;
            for o in range(len(scores)):
                return_colors.append(np.array(colors[o][0]));
                return_scores.append(np.array(scores[o][0]));
    return return_colors, return_scores,return_info;


#  python-holidays
#  ---------------
#  A fast, efficient Python library for generating country, province and state
#  specific sets of holidays on the fly. It aims to make determining whether a
#  specific date is a holiday as fast and flexible as possible.
#
#  Authors: dr-prodigy <dr.prodigy.github@gmail.com> (c) 2017-2023
#           ryanss <ryanssdev@icloud.com> (c) 2014-2017
#  Website: https://github.com/dr-prodigy/python-holidays
#  License: MIT (see LICENSE file)

import warnings
from datetime import date

from holidays.countries.south_korea import SouthKorea, KR, KOR, Korea
from tests.common import TestCase

class TestSouthKorea(TestCase):
    @classmethod
    def setUpClass(self):
        super().setUpClass(SouthKorea)

    def test_country_aliases(self):
        self.assertCountryAliases(SouthKorea, KR, KOR)

    def test_common(self):
        self.assertNonObservedHolidaysName("New Year's Day", "2019-01-01")

        self.assertNotIn(date(1582, 10, 2), self.holidays)
        self.assertNotIn(date(1582, 11, 14), self.holidays)

    def test_first_day_of_january(self):
        for year in range(2006, 2021):
            self.assertIn(self.holidays[date(year, 1, 1)], "New Year's Day")

    def test_lunar_new_year(self):
        for year, month, day in [
            (2006, 1, 28),
            (2007, 2, 17),
            (2010, 2, 13),
            (2014, 1, 30),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "The day preceding of Lunar New Year's Day",
            )

        for year, month, day in [
            (1916, 2, 4),
            (1944, 1, 26),
            (1954, 2, 4),
            (1958, 2, 19),
            (1966, 1, 22),
            (1988, 2, 18),
            (1997, 2, 8),
            (2008, 2, 7),
            (2009, 1, 26),
            (2011, 2, 3),
            (2012, 1, 23),
            (2014, 1, 31),
            (2015, 2, 19),
            (2016, 2, 8),
            (2017, 1, 28),
            (2018, 2, 16),
            (2019, 2, 5),
            (2020, 1, 25),
            (2027, 2, 7),
            (2028, 1, 27),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Lunar New Year's Day",
            )

        for year, month, day in [
            (2006, 1, 30),
            (2007, 2, 19),
            (2008, 2, 8),
            (2009, 1, 27),
            (2010, 2, 15),
            (2011, 2, 4),
            (2012, 1, 24),
            (2013, 2, 11),
            (2014, 2, 1),
            (2015, 2, 20),
            (2016, 2, 9),
            (2018, 2, 17),
            (2019, 2, 6),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "The second day of Lunar New Year's Day",
            )

        for year, month, day in [(2016, 2, 10), (2017, 1, 30), (2020, 1, 27)]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of Lunar New Year's Day",
            )

        self.assertNotIn(date(2015, 2, 21), self.holidays)
        self.assertNotIn(date(2015, 2, 7), self.holidays)

    def test_independence_movement_day(self):
        for year, month, day in [
            (2006, 3, 1),
            (2022, 3, 1),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Independence Movement Day",
            )

        for year, month, day in [(2025, 3, 3)]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of Independence Movement Day",
            )

    def test_tree_planting_day(self):
        for year, month, day in [
            (1949, 4, 5),
            (2005, 4, 5),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Tree Planting Day",
            )

        for year, month, day in [
            (1960, 4, 5),
            (2006, 4, 5),
        ]:
            self.assertNotIn(date(year, month, day), self.holidays)

    def test_childrens_day(self):
        for year, month, day in [
            (2015, 5, 5),
            (2018, 5, 5),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Children's Day",
            )

        for year, month, day in [(2018, 5, 7), (2019, 5, 6)]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of Children's Day",
            )
        for year, month, day in [(2025, 5, 6), (2044, 5, 6)]:
            self.assertIn(
                "Alternative holiday of Children's Day",
                self.holidays[date(year, month, day)],
            )

    def test_birthday_of_buddha(self):
        name = "Birthday of the Buddha"
        for year, month, day in [
            (1931, 5, 25),
            (1968, 5, 5),
            (2010, 5, 21),
            (2011, 5, 10),
            (2012, 5, 28),
            (2013, 5, 17),
            (2014, 5, 6),
            (2015, 5, 25),
            (2016, 5, 14),
            (2017, 5, 3),
            (2018, 5, 22),
            (2019, 5, 12),
            (2020, 4, 30),
            (2021, 5, 19),
            (2022, 5, 8),
            (2023, 5, 27),
            (2024, 5, 15),
            (2026, 5, 24),
            (2027, 5, 13),
            (2028, 5, 2),
            (2029, 5, 20),
            (2030, 5, 9),
        ]:
            self.assertEqual(self.holidays[date(year, month, day)], name)

        for year, month, day in [(2001, 5, 1)]:
            self.assertIn(
                "Birthday of the Buddha",
                self.holidays[date(year, month, day)],
            )

    def test_labour_day(self):
        for year in [1948, 1993]:
            self.assertIn("Labour Day", self.holidays[date(year, 3, 10)])

        for year in [1994, 2023]:
            self.assertIn("Labour Day", self.holidays[date(year, 5, 1)])

        self.assertNotIn(date(1993, 5, 1), self.holidays)
        self.assertNotIn(date(1994, 3, 10), self.holidays)

    def test_memorial_day(self):
        for year in [2006, 2022]:
            self.assertEqual(self.holidays[date(year, 6, 6)], "Memorial Day")

    def test_constitution_day(self):
        for year in [1948, 2007]:
            self.assertEqual(
                self.holidays[date(year, 7, 17)], "Constitution Day"
            )
        self.assertNotIn(date(1947, 7, 17), self.holidays)
        self.assertNotIn(date(2008, 7, 17), self.holidays)

    def test_liberation_day(self):
        for year in [1945, 2020]:
            self.assertEqual(
                self.holidays[date(year, 8, 15)], "Liberation Day"
            )
        self.assertEqual(
            self.holidays[date(2021, 8, 16)],
            "Alternative holiday of Liberation Day",
        )

    def test_chuseok(self):
        for year, month, day in [
            (2010, 9, 21),
            (2011, 9, 11),
            (2012, 9, 29),
            (2013, 9, 18),
            (2014, 9, 7),
            (2015, 9, 26),
            (2016, 9, 14),
            (2018, 9, 23),
            (2019, 9, 12),
            (2020, 9, 30),
            (2021, 9, 20),
            (2022, 9, 9),
            (2023, 9, 28),
            (2024, 9, 16),
            (2025, 10, 5),
            (2026, 9, 24),
            (2027, 9, 14),
            (2028, 10, 2),
            (2029, 9, 21),
            (2030, 9, 11),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "The day preceding of Chuseok",
            )

        for year, month, day in [(2017, 10, 3)]:
            self.assertIn(
                "The day preceding of Chuseok",
                self.holidays[date(year, month, day)],
            )

        for year, month, day in [
            (1942, 9, 25),
            (1978, 9, 17),
            (2010, 9, 22),
            (2011, 9, 12),
            (2012, 9, 30),
            (2013, 9, 19),
            (2014, 9, 8),
            (2015, 9, 27),
            (2016, 9, 15),
            (2017, 10, 4),
            (2018, 9, 24),
            (2019, 9, 13),
            (2020, 10, 1),
            (2021, 9, 21),
            (2022, 9, 10),
            (2023, 9, 29),
            (2024, 9, 17),
            (2025, 10, 6),
            (2026, 9, 25),
            (2027, 9, 15),
            (2029, 9, 22),
            (2030, 9, 12),
            (2040, 9, 21),
        ]:
            self.assertEqual(self.holidays[date(year, month, day)], "Chuseok")

        for year, month, day in [(2028, 10, 3)]:
            self.assertIn("Chuseok", self.holidays[date(year, month, day)])

        for year, month, day in [
            (2010, 9, 23),
            (2011, 9, 13),
            (2012, 10, 1),
            (2013, 9, 20),
            (2014, 9, 9),
            (2015, 9, 28),
            (2016, 9, 16),
            (2017, 10, 5),
            (2018, 9, 25),
            (2019, 9, 14),
            (2020, 10, 2),
            (2021, 9, 22),
            (2022, 9, 11),
            (2023, 9, 30),
            (2024, 9, 18),
            (2025, 10, 7),
            (2026, 9, 26),
            (2027, 9, 16),
            (2028, 10, 4),
            (2029, 9, 23),
            (2030, 9, 13),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "The second day of Chuseok",
            )

        for year, month, day in [
            (2014, 9, 10),
            (2015, 9, 29),
            (2018, 9, 26),
            (2022, 9, 12),
            (2025, 10, 8),
            (2029, 9, 24),
        ]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of Chuseok",
            )

    def test_national_foundation_day(self):
        for year in [1951, 2049]:
            self.assertIn(
                "National Foundation Day",
                self.holidays[date(year, 10, 3)],
            )

        for year, month, day in [(2021, 10, 4)]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of National Foundation Day",
            )

    def test_hangeul_day(self):
        for year in [1948, 1990]:
            self.assertEqual(self.holidays[date(year, 10, 9)], "Hangeul Day")

        for year in [2013, 2023]:
            self.assertEqual(self.holidays[date(year, 10, 9)], "Hangeul Day")

        for year in [1991, 2012]:
            self.assertNotIn(date(year, 10, 9), self.holidays)

        for year, month, day in [(2021, 10, 11)]:
            self.assertEqual(
                self.holidays[date(year, month, day)],
                "Alternative holiday of Hangeul Day",
            )

    def test_christmas_day(self):
        for year in [1948, 2050]:
            self.assertEqual(
                self.holidays[date(year, 12, 25)], "Christmas Day"
            )

    def test_years_range(self):
        for year in [2006, 2021]:
            self.assertIn(self.holidays[date(year, 1, 1)], "New Year's Day")

    def test_special_holidays(self):
        self.assertIn("2020-08-17", self.holidays)

    def test_korea_deprecation_warning(self):
        warnings.simplefilter("default")
        with self.assertWarns(Warning):
            Korea()

        warnings.simplefilter("error")
        with self.assertRaises(Warning):
            Korea()


def count_words(doc):
    normalised_doc = ''.join(c.lower() if c.isalpha() else ' ' for c in doc)
    frequencies = {}
    for word in normalised_doc.split():
        frequencies[word] = frequencies.get(word, 0) + 1
    return frequencies

documents = [
    'It is the best of times, it was the worst of times',
    'I went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could not learn what it had to teach, and not, when I came to die, discover that I had not lived',
    'Friend, Romans, countrymen, lend me your earsl I come to bury Caesar, not to praise him',
    'I do not like green eggs and ham. I do not like them, Sam-I-Am.'
]

counts = map(count_words, documents)

def combine_counts(d1, d2):
    d = d1.copy()
    for word, count in d2.items():
        d[word] = d.get(word, 0) + count
    return d


from datetime import datetime, timedelta
from app import config
import jwt

def issue_token(username, phone, pickup_user_id, name, pickteam_id):
    now = datetime.utcnow()
    payload = {
        'username': username,
        'phone': phone,
        'pickup_user_id': pickup_user_id,
        'pickteam_id' : pickteam_id,
        'acc_type' : 'pickup',
        'name': name,
        'iat': now,
        'exp': now + timedelta(5)
    }
    jwt_token = jwt.encode(payload, config.JWT['secret'], config.JWT['algorithm'])
    token = jwt_token.decode('utf-8')
    return token


from flask import Flask, render_template, request, redirect, url_for,flash,session
from flask.ext.session import Session
from flask.ext.bootstrap import Bootstrap
from flask.ext.wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from suitor_python import SubReddit_Postings

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
CsrfProtect(app)
suitor_flask_session = Session

class SubRedditForm(Form):

	form_name = StringField('What is the subreddit name?', validators=[Required()])
	form_phone_number = StringField('What is the recipients phone number?', \
	validators=[Required()])

	form_twilio_number = StringField('Your Twilio Tel Number - optional')
	form_account_sid = StringField('Your account_sid - optional')
	form_auth_token = StringField('Your auth_token - optional')
	form_submit = SubmitField('Submit')

@app.errorhandler(403)
def page_forbidden(e):
	return render_template('403.html'), 403

@app.errorhandler(404)
def page_not_found(e):
	return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
	return render_template('500.html'), 500

@app.route('/', methods=['GET', 'POST'])
def subreddit_post():
	form = SubRedditForm()
	if form.validate_on_submit():

		name=form.form_name.data
		phone_number = form.form_phone_number.data

		twilio_number = form.form_twilio_number.data
		account_sid = form.form_account_sid.data
		auth_token = form.form_auth_token.data

		subreddit = SubReddit_Postings(name,phone_number)
		if twilio_number:
			subreddit.twilio_setup(account_sid,auth_token,twilio_number)

		subreddit.subreddit_extract_post()
		valid = subreddit.sms_subreddit_post()
		if valid:
			flash("SMS successfully sent!!!")
		else:
			flash("SMS not sent, error with number or Twilio account !!!")

		return redirect(url_for('subreddit_post'))

	return render_template('suitor_flask.html', form=form)

if __name__ == '__main__':

	app.debug = True
	app.run()


#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import os
import sys
import argparse as ap
import re
from matplotlib.lines import Line2D
import matplotlib.patches as patches

def printf(format, *args):
        sys.stdout.write(format % args)

dest = "../figs/"

indir = "../data/bursty-5Hz"

files = [ f for f in os.listdir( indir )
                if os.path.isfile( os.path.join( indir, f ) ) ]

mydata = map( lambda x: os.path.join( indir, x ), files )

apps = [ "cth-st", "hpcg", "lmps-lj", "lmps-snap", "lmps-crack", "miniFE",
                "sparc", "milc" ]

while mydata:

        el = mydata.pop( 0 )

        try:
                config = re.search(r"(([-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)Hz_([-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)nodes)\.delta", el ).group( 1 )
        except AttributeError:
                continue

        printf( "Generating scaling plot for %s\n", el )

        data = np.genfromtxt( el, names=True, dtype=None,
                        deletechars=set("""~!@#$%^&*()=+~\|]}[{';: /?.>,<"""),
                        autostrip=True, missing_values='-', )

        fig, ax = plt.subplots()
        ax.set_xscale( 'log', basex = 10 )

        for i, a in enumerate( apps ):

                mask = np.isfinite( data[ a ] )
                the_min = min( data[ a ][ mask ] )

                if  not the_min:
                        printf( "Min not found: %s\n", a )
                        continue

                percent = [ ( x - the_min ) / the_min * 100.0
                                for x in data[ a ][ mask ] ]
                plt.plot( data[ "Delta" ][ mask ],
                        percent,
                        lw = 1,
                        label = a )
        ymin, ymax = plt.ylim()

        plt.legend( loc = 'best' )
        plt.xlabel( "Duration of Error (sec)" )
        plt.ylabel( "Pecent Slowdown" )
        plt.savefig( dest + config + "-apps-delta.pdf" );
        plt.close()


import sqlite3
import os
import pandas as pd

class DbLite:

    def __init__(self, db):
        self.db=db
        self.conn = sqlite3.connect(db)
        self.cur = self.conn.cursor()

    def readPandasFromDB(self, table):
        table = pd.read_sql_query("select * from "+table+";", self.conn)
        return table

    def writePandasToDB(self, table, dataFrame, create=False):

        if create == True:
            dataFrame.to_sql(table, con=self.conn, if_exists='replace', index=False)
        else:
            sameDateRows = pd.read_sql_query("select * from "+table+" WHERE date='"+dataFrame['date'][0].strftime('%Y-%m-%d')+"';", con=self.conn)

            if sameDateRows.empty:
                print("Writing new rows to database")
                dataFrame.to_sql(table, con=self.conn, if_exists='append', index=False)
            else:
                print("Rows already exist in database")