import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import json
import random

client = commands.Bot(command_prefix=".ari ")
# used on_guild_join to easier put data into json file (i putted here for no reason)
tamplate = {}

# opens json file and loads it data in data variable
with open(r"C:\Users\ariso\Desktop\Snake projects\aribot\cogs\data.json", "r") as f:
    data = json.load(f)
# when bots is entering the serwer it's used to get all nessesary channels ids

@client.event
async def on_guild_join(guild):
    # checks if guild is already in our database , technicly impossible to fail, but it's just in case
    if guild.id in data["serwers"]:
        return
    else:
        # ask owner in serwer to fill this if all nessesart ids
        await guild.text_channels[0].send('''hello!
I will need you to complete some spets before we can work together
pls use command *.ari add_channels*
id of helpers_channels one or more seperated by "|" ,
id of channel that you want to users to send art_requests ,
id of channel you want to artists only channel,
id of chanel that would helpers only channel [note id Has to be write without spaces and have to be saperated by ,] ''')
        # commands for setting up bot

        @client.command()
        @commands.is_owner()
        async def add_channels(ctx, *, rest):
            help_channels = []
            splited_rest = rest.split(",")
            for x in splited_rest[0].split("|"):
                help_channels.append(x)
                for x in help_channels:
                    # checks if channels exits in serwer
                    if int(x)not in guild.text_channel:
                        await ctx.send("one of channels doesn't exists in your serwer")
            for x in range(len(splited_rest)-1):
                if int(splited_rest[x+1]) not in guild.text_channel:
                    await ctx.send("one of channels doesn't exists in your serwer")
            # adds modified template to data.json
            tamplate.setdefault(guild.id, {"help_channels": help_channels, "art_request_channel":
                               splited_rest[1], "artists_channel": splited_rest[2], "helpers_channel": splited_rest[3]})
            data["serwers"].append(tamplate)
            with open(r"C:\Users\ariso\Desktop\Snake projects\aribot\cogs\data.json", "w") as f:
                json.dump(data, f, indent=2)
            await ctx.send('''cool, everything seems to be working. Last thing are channel permisions
helpers_channels should be visable for everyone and mods/helpers should be allow to manage them
art_request channel should be public
artists only channel i think speaks for it self
same with helpers only ''')

# removing all of data about the guild after leaving

@client.event
async def on_guild_remove(guild):
    for x in data["serwers"]:
        if guild.id == int(x):
            del x

#indicator after bot is ready for use

@client.event
async def on_ready():
    print("i am ready")

# realoding cogs

@client.command()
@commands.has_permissions(manage_messages=True)
async def reload(ctx, extension):
    client.unload_extension(f"cogs.{extension}")
    client.load_extension(f"cogs.{extension}")

#deleting said amount of messages from a channel

@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, ammout):
    await ctx.channel.purge(limit=int(ammout))

@client.event
async def on_message(message):
    #my interactions with bot XD
    if "hi aribot" in str(message.content) and message.author.id == 384350694905217034:
        await message.channel.send("Hi creator! ❤")
    if "bad aribot" in str(message.content) and message.author.id == 384350694905217034:
        await message.channel.send("I am so sorry, creator 😭")
    #those to may not work since they are links to image that were sent in discord which could be deleted.
    #Better would be to set them to images sent in private channels on your server instead.
    #Should to be addable by command <- to do
    if ":hipnotize:" in str(message.content):
        await message.channel.purge(limit=1)
        await message.channel.send("https://cdn.discordapp.com/attachments/798653357660045333/813708811721768970/ezgif.com-video-to-gif.gif ")
    if ":'merica:" in str(message.content):
        await message.channel.purge(limit=1)
        await message.channel.send("https://cdn.discordapp.com/attachments/809656965063507998/811570670332543016/llama_marica.gif ")
    await client.process_commands(message)

#mixins
@client.command()
async def mixin(ctx):
    msg =  await ctx.send("https://github.com/SpongePowered/Mixin/wiki")
    await msg.delete()

for f in os.listdir(r"C:\Users\ariso\Desktop\Snake projects\aribot\cogs"):
    if f.endswith(".py"):
        client.load_extension(f"cogs.{f[:-3]}")

client.run('')


from __future__ import division
import logging
import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D  # Seemingly unused, but for 3D plots
from matplotlib.colors import ColorConverter
from shapely.geometry import box, Polygon
from descartes.patch import PolygonPatch

from cops_and_robots.helpers.visualizations import plot_multisurface

# The following are class methods of Softmax

def plot(self, class_=None, show_plot=True, plot_3D=True, plot_probs=True,
         plot_dominant_classes=True, plot_poly=False, plot_normals=False,
         plot_subclasses=False, plot_legend=True, fig=None, ax=None,
         title='Softmax Classification',
         **kwargs):
    """Display the class and/or PDF plots of the Softmax distribution.

    The class plot shows only the critical classes (those that have the
    greatest probability at any given state).

    Parameters
    ----------
    plot_dominant_classes : bool, optional
        Plot the critical classes. Defaults to `True`.
    plot_probs : bool, optional
        Plot the probability densities. Defaults to `True`.
    plot_poly : bool, optional
        Plot the polygon from which the boundaries are formed. Defaults to
        `False`.
    **kwargs
        Keyword arguments for ``plot_dominant_classes``.
    """

    # Define probabilities lazily
    if not hasattr(self, 'probs') and not plot_subclasses:
            self.probability()
    if not hasattr(self, 'subclass_probs') and plot_subclasses:
            self.probability(find_subclass_probs=True)

    # Plotting attributes
    self.plot_3D = plot_3D
    self.plot_subclasses = plot_subclasses

    if plot_dominant_classes and plot_probs and class_ is None:
        if fig is None:
            self.fig = plt.figure(figsize=(14, 8))
        else:
            self.fig = fig
        bbox_size = (-1.3, -0.175, 2.2, -0.075)

        if ax is None:
            ax1 = self.fig.add_subplot(1, 2, 1)
            if plot_3D and self.state.shape[1] > 1:
                ax2 = self.fig.add_subplot(1, 2, 2, projection='3d')
            else:
                ax2 = self.fig.add_subplot(1, 2, 2)
        else:
            ax1 = ax[0]
            ax2 = ax[1]
        self._plot_dominant_classes(ax1)
        self._plot_probs(ax2)
        axes = [ax1, ax2]

    elif plot_dominant_classes and class_ is None:
        if fig is None:
            self.fig = plt.figure(figsize=(8, 8))
        else:
            self.fig = fig
        if ax is None:
            ax1 = self.fig.add_subplot(111)
        else:
            ax1 = ax
        bbox_size = (0, -0.175, 1, -0.075)
        self._plot_dominant_classes(ax=ax1, **kwargs)
        axes = [ax1]

    elif plot_probs:
        if fig is None:
            self.fig = plt.figure(figsize=(8, 8))
        else:
            self.fig = fig

        if class_ is not None:
            if ax is None:
                if plot_3D and self.state.shape[1] > 1:
                    ax = self.fig.add_subplot(1, 1, 1, projection='3d')
                else:
                    ax = self.fig.add_subplot(1, 1, 1)
            self.classes[class_].plot(ax=ax, **kwargs)
            axes = [self.fig.gca()]
        else:
            if plot_3D and self.state.shape[1] > 1 and ax is None:
                ax1 = self.fig.add_subplot(111, projection='3d')
            elif ax is None:
                ax1 = self.fig.add_subplot(111)
            else:
                ax1 = ax
            self._plot_probs(ax1, **kwargs)
            axes = [ax1]
        bbox_size = (0, -0.15, 1, -0.05)

    if plot_legend:
        # Create Proxy artists for legend labels
        proxy = [None] * self.num_classes
        for i in range(self.num_classes):
            if self.class_labels[i] not in self.class_labels[:i]:
                proxy_label = self.class_labels[i]
            else:
                proxy_label = "_nolegend_"
            proxy[i] = plt.Rectangle((0, 0), 1, 1, fc=self.class_colors[i],
                                     alpha=0.6, label=proxy_label,)

        plt.legend(handles=proxy, loc='lower center', mode='expand', ncol=5,
                   bbox_to_anchor=(0, 1.0 ,1, 0), borderaxespad=0.)

        # plt.legend(handles=proxy, loc='lower center', mode='expand', ncol=4,
        #            bbox_to_anchor=bbox_size, borderaxespad=0.)
    plt.suptitle(title, fontsize=16)

    # Plot polygon
    if self.poly is not None and plot_poly and plot_dominant_classes:
        try:
            for poly in self.polys:
                patch = PolygonPatch(poly, facecolor='none', zorder=2,
                                     linewidth=3, edgecolor='black',)
                ax1.add_patch(patch)
        except:
            patch = PolygonPatch(self.poly, facecolor='none', zorder=2,
                                 linewidth=3, edgecolor='black',)
            ax1.add_patch(patch)

    # Plot normals
    # <>TODO fix crashing issue with vertical normals
    if self.normals is not None and plot_normals and plot_dominant_classes:
        t = np.arange(self.bounds[0], self.bounds[2] + 1)
        for i, normal in enumerate(self.normals):
            if abs(normal[1]) < 0.0001:
                ax1.axvline(self.offsets[i], ls='--', lw=3, c='black')
            else:
                slope = normal[0]
                y = slope * t - self.offsets[i]
                ax1.plot(t, y, ls='--', lw=3, c='black')

    if show_plot:
        plt.show()
    try:
        return axes
    except UnboundLocalError:
        logging.warn('No axes to return.')

def _plot_probs(self, ax=None, class_=None):
    if self.state.shape[1] == 1:
        if ax is None:
            ax = self.fig.gca()
        self._plot_probs_1D(ax, class_)
    elif self.state.ndim == 2:
        if ax is None and self.plot_3D:
            ax = self.fig.gca(projection='3d')
        elif ax is None:
            ax = self.fig.gca()
        self._plot_probs_2D(ax, class_)
    elif self.state.ndim == 3:
        if ax is None:
            ax = self.fig.gca(projection='3d')
        self._plot_probs_3D(ax, class_)
    else:
        raise ValueError('The state vector must be able to be represented '
                         'in 1D, 2D or 3D to be plotted.')

    # Shrink current axis's height by 10% on the bottom
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])

def _plot_probs_1D(self, ax, class_):
    if type(class_) is str:
        try:
            class_ = self.classes[class_].id
        except KeyError:
            logging.debug('Couldn\'t find class {}. Looking in subclasses.'
                          .format(class_))
            class_ = self.subclasses[class_].id
            if not hasattr(self, 'subclass_probs'):
                self.probability(find_subclass_probs=True)
            self.plot_subclasses = True
        except e:
            logging.error('Couldn\'t find {} as a class or subclass.'
                           .format(class_))
            raise e
    if self.plot_subclasses:
        Z = self.subclass_probs[:]
    else:
        Z = self.probs[:]

    if class_ is not None:
        ax.plot(self.X[0, :], Z[:,class_], color=self.class_colors[class_])
        ax.fill_between(self.X[0, :], 0, Z[:,class_], color=self.class_colors[class_],
                        alpha=0.4)
    else:
        for i in range(self.num_classes):
            ax.plot(self.X[0, :], Z[:,i], color=self.class_colors[i])
            ax.fill_between(self.X[0, :], 0, Z[:,i], color=self.class_colors[i],
                            alpha=0.4)

    ax.set_xlim(self.bounds[0], self.bounds[2])
    ax.set_ylim(0, 1)
    ax.set_xlabel('x')
    ax.set_ylabel('Probability P(D=i|X)')
    ax.set_title('Class Probabilities')

def _plot_probs_2D(self, ax, class_):
    if class_ is not None:
        if type(class_) is str:
            try:
                class_ = self.classes[class_].id
            except KeyError:
                logging.debug('Couldn\'t find class {}. Looking in subclasses.'
                              .format(class_))
                class_ = self.subclasses[class_].id
                if not hasattr(self, 'subclass_probs'):
                    self.probability(find_subclass_probs=True)
                self.plot_subclasses = True
            except e:
                logging.error('Couldn\'t find {} as a class or subclass.'
                               .format(class_))
                raise e
        if self.plot_subclasses:
            Z = self.subclass_probs[:, class_].reshape(self.X.shape[0], self.X.shape[1])
        else:
            Z = self.probs[:, class_].reshape(self.X.shape[0], self.X.shape[1])
    elif self.plot_subclasses:
        Z = self.subclass_probs.reshape(self.X.shape[0], self.X.shape[1],
                                        self.num_subclasses)
    else:
        Z = self.probs.reshape(self.X.shape[0], self.X.shape[1],
                               self.num_classes)

    if self.plot_3D:

        if class_ is not None:
            ax.plot_surface(self.X, self.Y, Z, cstride=2, rstride=2,
                            linewidth=0, antialiased=False,
                            cmap=plt.get_cmap(self.class_cmaps[class_]))
        else:
            #<>TODO: replace with mlab mayavi plotting
            plot_multisurface(self.X, self.Y, Z, ax, cstride=4, rstride=4)

        ax.set_xlim(self.bounds[0], self.bounds[2])
        ax.set_ylim(self.bounds[1], self.bounds[3])
        ax.set_zlabel('P(D=i|X)')
    else:
        levels = np.linspace(0, np.max(Z), 50)
        # <>TODO: Fix contourf plotting for multiple classes
        for i in range(self.num_classes):
            ax.contourf(self.X, self.Y, Z[:,:,i], levels=levels,
                        cmap=plt.get_cmap(self.class_cmaps[i]), alpha=0.8)

    ax.set_xlabel('x1')
    ax.set_ylabel('x2')
    ax.set_title('Class Likelihoods')

def _plot_probs_3D(self, ax, class_):
    pass

def _plot_dominant_classes(self, ax=None, plot_poly=False, **kwargs):
    """Plot only the critical classes.

    Critical classes are defined as the classes with highest probability
    for a given state vector `x`.

    """
    # <>TODO: Fix the checking of the state vector to allow, say, 1 x y x^2
    # Plot based on the dimension of the state vector
    if ax is None:
        ax = self.fig.gca()

    if self.state.shape[1] == 1:
        self._plot_dominant_classes_1D(ax, **kwargs)
    elif self.state.ndim == 2:
        self._plot_dominant_classes_2D(ax, **kwargs)
    elif self.state.ndim == 3:
        self._plot_dominant_classes_3D(ax, **kwargs)
    else:
        raise ValueError('The state vector must be able to be represented '
                         'in 1D, 2D or 3D to be plotted.')

    # Shrink current axis's height by 10% on the bottom
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])

def _plot_dominant_classes_1D(self, ax, **kwargs):

    if self.plot_subclasses:
        probs = self.subclass_probs
    else:
        probs = self.probs

    res = 1 / self.X.size
    fake_X, fake_Y = np.mgrid[self.bounds[0]:self.bounds[2] + res:res,
                              0:0.1]
    max_pdf_indices = np.argmax(probs, axis=1)
    max_colors = np.take(self.class_colors, max_pdf_indices)
    cc = ColorConverter()
    max_colors_rgb = np.array([cc.to_rgb(_) for _ in max_colors])

    ax.bar(self.X.T, np.ones_like(self.X.T), color=max_colors_rgb,
           linewidth=0, alpha=1)

    ax.set_xlim(self.bounds[0], self.bounds[2])
    ax.set_ylim(0, 0.01)
    ax.set_yticks([])

    ax.set_xlabel('x')
    ax.set_title('Critical Classes')

def _plot_dominant_classes_2D(self, ax, **kwargs):

    if self.plot_subclasses:
        probs = self.subclass_probs
    else:
        probs = self.probs

    # <>TODO: come up with more elegant solution than scatter plot
    # Identify colors of critical classes for each state
    np.set_printoptions(threshold=np.nan)
    max_pdf_indices = np.argmax(probs, axis=1)
    max_colors = np.take(self.class_colors, max_pdf_indices)
    cc = ColorConverter()
    max_colors_rgb = np.array([cc.to_rgb(_) for _ in max_colors])

    ax.scatter(self.X, self.Y, c=max_colors_rgb, marker='s', s=50,
               linewidths=0, alpha=1)

    ax.set_xlim(self.bounds[0], self.bounds[2])
    ax.set_ylim(self.bounds[1], self.bounds[3])
    ax.set_xlabel(r'$X_1$')
    ax.set_ylabel(r'$X_2$')
    ax.set_title('Critical Classes')

def _plot_dominant_classes_3D(self, **kwargs):
    pass


from pyspark import SparkContext
from copy import deepcopy
import time
import sys

def bfs(root, graph):
    q = [root]
    visited = set()
    while len(q) != 0:
        node = q.pop(0)
        if node not in visited:
            visited.add(node)
            q.extend(graph[node])
    return visited

def bfs_al(root,al):
    parents = {}
    numPaths = {}
    q = [(root, 0)]
    parents[root] = [(-1, -1)]
    numPaths[root] = 1
    visited = []

    while len(q) != 0:
        node = q.pop(0)
        if node[0] not in visited:
            if node[0] not in al:
                visited.append(node[0])
            else:
                for i in al[node[0]]:
                    if i not in parents:
                        parents[i] = [node]
                        numPaths[i] = numPaths[node[0]]
                    elif parents[i][0][1] == node[1]:
                        parents[i].append(node)
                        numPaths[i] = numPaths[i] + numPaths[node[0]]
                    q.append((i, node[1] + 1))
                visited.append(node[0])

    return visited, parents, numPaths

def getBetweenessFromNode(node,adjacency_list):
    visited,parents,numPaths = bfs_al(node,adjacency_list)
    visited.reverse()
    edge_betweeness = {}
    node_credit = {vertex: 1 for vertex in visited}
    for vertex in visited[:-1]:
        for parent in parents[vertex]:
            edge = (min(vertex, parent[0]),max(vertex, parent[0]))
            credit = float(node_credit[vertex] * numPaths[parent[0]])/float(numPaths[vertex])
            if edge not in edge_betweeness.keys():
                edge_betweeness[edge] = 0
            edge_betweeness[edge] += credit
            node_credit[parent[0]] += credit

    #return edge_betweeness
    return [(k, v) for k, v in edge_betweeness.items()]

def createAdjacencyList(edges):
    adjacency_list = {}
    for i in edges:
        if i[0] in adjacency_list:
            adjacency_list[i[0]].add(i[1])
        else:
            adjacency_list[i[0]] = set([i[1]])
        if i[1] in adjacency_list:
            adjacency_list[i[1]].add(i[0])
        else:
            adjacency_list[i[1]] = set([i[0]])

    return adjacency_list

def findConnectedComponents(adj_list):
    seen = set()
    connected_components = []
    for i in adj_list:
        if i not in seen:
            visited= bfs(i,adj_list)
            connected_components.append(visited)
            seen = seen.union(visited)
    return connected_components

#                            int,  int->set,    int ->set
def findModContriOfComponent(m, adjacency_list,component):
        modularity = 0
        for i in component:
            for j in component:
                wt = 0
                if j in adjacency_list[i]:
                    wt = 1
                modularity += wt - (len(adjacency_list[i])*len(adjacency_list[j])/float(2*m))
        return [(1,modularity)]

st = time.time()

sc = SparkContext('local[*]', 'LSH')
sc.setLogLevel("ERROR")

ip_data  = sc.textFile(sys.argv[1])

nodes = ip_data.flatMap(lambda x: (x.split(" ")[0],x.split(" ")[1])).distinct().persist()

nodes_data  = nodes.collect()

edges = ip_data.map(lambda x: (x.split(" ")[0],x.split(" ")[1])).collect()

adjacency_list = {}

adjacency_list = createAdjacencyList(edges)

betweeness = nodes.flatMap(lambda node: getBetweenessFromNode(node,adjacency_list)).reduceByKey(lambda x,y: x+y).mapValues(lambda x: x/2).sortBy(lambda x: (-1 * x[1],x[0][0],x[0][1])).collect()

bet_file = open(sys.argv[2],"w")
for bet in betweeness:
    bet_file.write(str(bet[0])+", "+str(bet[1])+"\n")

max_betweeness = betweeness[0]
# print(max_betweeness)

modularity = -1
m = len(edges)
c = len(edges)
connected_components = findConnectedComponents(adjacency_list)
argMaxComponents = connected_components

# print(len(connected_components))
connected_components_rdd = sc.parallelize(connected_components)

adjacency_list_copy = deepcopy(adjacency_list)

while c!=1:
    # print(c)

    mod = connected_components_rdd.flatMap(lambda component: findModContriOfComponent(m,adjacency_list,component))

    mod = float(mod.reduceByKey(lambda x,y : x+y).collect()[0][1])/(2*m)
    if mod > modularity:
        modularity = mod
        argMaxComponents = deepcopy(connected_components)

    u = max_betweeness[0][0]
    v = max_betweeness[0][1]

    adjacency_list_copy[u].remove(v)
    adjacency_list_copy[v].remove(u)

    max_betweeness = nodes.flatMap(lambda node: getBetweenessFromNode(node, adjacency_list_copy)).reduceByKey(
        lambda x, y: x + y).mapValues(lambda x: x / 2).sortBy(lambda x: -1 * x[1]).take(1)[0]

    connected_components = findConnectedComponents(adjacency_list_copy)
    # print(len(connected_components))
    connected_components_rdd = sc.parallelize(connected_components)

    c  -= 1

components = []
for comp in argMaxComponents:
    com = list(comp)
    com.sort()
    components.append(com)

components.sort()
components.sort(key = len)

comp_file  = open(sys.argv[3],"w")

for comp in components:
    comp_file.write(str(comp)[1:-1]+"\n")
#
# print(modularity)
# print(len(argMaxComponents))
# print(argMaxComponents)

# adj = {0:[1,2],1:[0,2],2:[0,1,3],3:[2,4,5,6],4:[3,5],5:[3,4,6],6:[3,5]}
# m = 9
# cc = {0:[1,2],1:[0,2],2:[0,1]}
#
# print(findModContriOfComponent(m,adj,cc))

print(time.time() - st)

##wrong modularity calculation and very slow


import urllib.request
import re

url = 'http://pythonprogramming.net/parse-website-using-regular-expressions-urllib/'

resp = urllib.request.urlopen(url)
respData = str(resp.read())

paragraphs = re.findall(r'<p>(.*?)</p>', respData)

for para in paragraphs :
    print(para)

Web Parsing Using urllib/Urllib_and_RE.py


import time
import smbus
import sys
import socket
import psutil
class My1602(object):
    BUS = smbus.SMBus(1)
    LCD_ADDR = 0x27
    BLEN = 1
    def turn_light(self, key):
        self.BLEN = key
        if key == 1:
            self.BUS.write_byte(self.LCD_ADDR, 0x08)
        else:
            self.BUS.write_byte(self.LCD_ADDR, 0x00)
    def write_word(self, addr, data):
        temp = data
        if self.BLEN == 1:
            temp |= 0x08
        else:
            temp &= 0xF7
        self.BUS.write_byte(addr, temp)
    def send_command(self, comm):
        buf = comm & 0xF0
        buf |= 0x04
        self.write_word(self.LCD_ADDR, buf)
        time.sleep(0.002)
        buf &= 0xFB
        self.write_word(self.LCD_ADDR, buf)
        buf = (comm & 0x0F) << 4
        buf |= 0x04
        self.write_word(self.LCD_ADDR, buf)
        time.sleep(0.002)
        buf &= 0xFB
        self.write_word(self.LCD_ADDR, buf)
    def send_data(self, data):
        buf = data & 0xF0
        buf |= 0x05
        self.write_word(self.LCD_ADDR, buf)
        time.sleep(0.002)
        buf &= 0xFB
        self.write_word(self.LCD_ADDR, buf)
        buf = (data & 0x0F) << 4
        buf |= 0x05
        self.write_word(self.LCD_ADDR, buf)
        time.sleep(0.002)
        buf &= 0xFB
        self.write_word(self.LCD_ADDR, buf)
    def __init__(self):
        try:
            self.send_command(0x33)
            time.sleep(0.005)
            self.send_command(0x32)
            time.sleep(0.005)
            self.send_command(0x28)
            time.sleep(0.005)
            self.send_command(0x0C)
            time.sleep(0.005)
            self.send_command(0x01)
            self.BUS.write_byte(self.LCD_ADDR, 0x08)
        except:
            return None
        else:
            return None
    def clear_lcd(self):
        self.send_command(0x01)
    def print_lcd(self, x, y, str):
        if x < 0:
            x = 0
        if x > 15:
            x = 15
        if y < 0:
            y = 0
        if y > 1:
            y = 1
        addr = 0x80 + 0x40 * y + x
        self.send_command(addr)
        for chr in str:
            self.send_data(ord(chr))
if __name__ == '__main__':
    my1602 = My1602()
    def get_ip_address():
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip_address = s.getsockname()[0]
            s.close()
            return ip_address
        except:
            return "Error: Unable to get IP address"
    def get_cpu_usage():
        cpu_usage = psutil.cpu_percent(interval=1)
        return f"CPU Usage: {cpu_usage}%"
    def get_memory_usage():
        memory = psutil.virtual_memory()
        memory_usage = memory.percent
        return f"Memory Usage: {memory_usage}%"
    status_functions = [get_ip_address, get_cpu_usage, get_memory_usage]
    current_status_index = 0
    while True:
        # 显示当前时间
        current_time = time.strftime("%H:%M:%S")
        my1602.print_lcd(0, 0, "Time: " + current_time)
        # 显示状态信息
        current_status = status_functions[current_status_index]()
        my1602.print_lcd(0, 1, current_status)
        # 切换到下一个状态函数
        current_status_index = (current_status_index + 1) % len(status_functions)
        time.sleep(1)


import random
from pandas import json
from pprint import pprint
from flask import Flask, render_template, render_template_string, make_response, jsonify
from flask_bower import Bower
from gowell_mtd_mfc import make_basic_plot, gowell_plot_div, gowell_plot_json
from MISC.plotly_basic import modify_basic_plot, make_basic_plot
from MISC.mpl_trial import create_mpl_response
from try_mpld3 import try_mpld3_html

app = Flask(__name__)
Bower(app)

@app.route('/')
def hello_world():
    return render_template('MISC/trial_xtk/trial.html')

@app.route('/2')
def try2():
    pprint("HELLO")
    # return render_template('trial_xtk/trial2.html')
    return ("HELLO WORLD")

@app.route('/3')
def three():
    return render_template('MISC/three_try.html')

@app.route('/mpl')
def render_basic():
    # return("Hello World")
    render_template('MISC/flask_jinja_pyplot/submit.html')

@app.route('/mpl/get_image')
def get_flask():
    response = make_response(create_mpl_response())
    response.content_type = 'image/svg+xml'
    return response

@app.route('/px')
def newpage():
    try:
        # generate some random integers, sorted
        exponent = .7 + random.random() * .6
        dta = []
        for i in range(5):
            rnum = int((random.random() * 10) ** exponent)
            dta.append(rnum)
            y = sorted(dta)
            x = range(len(y))
        return render_template('MISC/flask_jinja_pyplot/figures.html', y=y)

    except Exception as e:
        pprint(e)

@app.route('/ex')
def indexPage():
    try:
        return render_template('MISC/flask_jinja_pyplot/figures.html', y=y)

    except Exception as e:
        pprint(e)

@app.route('/trans')
def new_trans():
    try:
        return render_template('TRANS/trans_hello.html')

    except Exception as e:
        pprint(e)

@app.route('/jqdemo')
def jqdemo():
    try:
        return render_template('TRANS/jquery_demo.html')

    except Exception as e:
        pprint(e)

@app.route('/d3demo')
def trans_d3():
    try:
        return render_template('TRANS/d3_demo.html')

    except Exception as e:
        pprint(e)

@app.route('/mathbox')
def mathbox():
    try:
        return render_template('derived_three.html')  # 'threestrap.html')

    except Exception as e:
        pprint(e)

@app.route('/mpld_eg', methods=['GET', 'POST'])
def mpld_eg():
    try:
        # return render_template_string(try_mpld3_html())
        return try_mpld3_html()
    except Exception as e:
        pprint(e)

@app.route('/plotly', methods=['GET', 'POST'])
def plotly():
    try:
        get_plotly_plot = make_basic_plot()
        return render_template('PLOTLY/plotly_base.html')

    except Exception as e:
        pprint(e)

@app.route('/go_plotly_div', methods=['GET', 'POST'])
def go_plot_div():
    try:
        return gowell_plot_div()
    except Exception as e:
        pprint(e)

@app.route('/go_plotly_json', methods=['GET', 'POST'])
def go_plot():
    try:
        return gowell_plot_json()
    except Exception as e:
        pprint(e)

@app.route('/plotly_ajax', methods=['GET', 'POST'])
def plotly_ajax():

    try:
        return make_basic_plot()

    except Exception as e:
        pprint(e)

@app.route('/get_new_data', methods=['GET', 'POST'])
def high_update():
    try:
        return modify_basic_plot()

    except Exception as e:
        pprint(e)

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


import collections
import inspect
import threading

from tensorflow.core.framework import graph_debug_info_pb2
from tensorflow.python.util import _tf_stack

# Generally such lookups should be done using `threading.local()`. See
# https://blogs.gnome.org/jamesh/2008/06/11/tls-python/ for a detailed
# explanation of why. However the transform stacks are expected to be empty
# when a thread is joined, so reusing the key does not introduce a correctness
# issue. Moreover, get_ident is faster than storing and retrieving a unique
# key in a thread local store.
_get_thread_key = threading.get_ident

# TODO(mdan): Move these to C++ as well.
# Moving to C++ can further avoid extra copies made by get_effective_map.
_source_mapper_stacks = collections.defaultdict(lambda: [SentinelMapper()])
_source_filter_stacks = collections.defaultdict(lambda: [SentinelFilter()])

class StackTraceTransform(object):
  """Base class for stack trace transformation functions."""

  _stack_dict = None  # Subclasses should override
  _thread_key = None

  def __enter__(self):
    # Any given instance is assumed to be used by a single thread, which reduces
    # expensive thread local lookups.
    if self._thread_key is None:
      self._thread_key = _get_thread_key()
    else:
      assert self._thread_key == _get_thread_key(), 'Shared across threads?'

    stack = self._stack_dict[self._thread_key]
    self.parent = stack[-1]
    stack.append(self)
    self.update()
    return self

  def __exit__(self, unused_type, unused_value, unused_traceback):
    top = self._stack_dict[self._thread_key].pop()
    assert top is self, 'Concurrent access?'

  def update(self):
    raise NotImplementedError('subclasses need to override this')

class StackTraceMapper(StackTraceTransform):
  """Allows remapping traceback information to different source code."""
  _stack_dict = _source_mapper_stacks

  def __init__(self):
    self.internal_map = _tf_stack.PyBindSourceMap()

  def update(self):
    self.internal_map.update_to(tuple(self.get_effective_source_map().items()))

  def get_effective_source_map(self):
    """Returns a map (filename, lineno) -> (filename, lineno, function_name)."""
    raise NotImplementedError('subclasses need to override this')

EMPTY_DICT = {}

class SentinelMapper(StackTraceMapper):

  def get_effective_source_map(self):
    return EMPTY_DICT

class StackTraceFilter(StackTraceTransform):
  """Allows filtering traceback information by removing superfluous frames."""
  _stack_dict = _source_filter_stacks

  def __init__(self):
    self.internal_set = _tf_stack.PyBindFileSet()

  def update(self):
    self.internal_set.update_to(set(self.get_filtered_filenames()))

  def get_filtered_filenames(self):
    raise NotImplementedError('subclasses need to override this')

EMPTY_SET = frozenset()

class SentinelFilter(StackTraceFilter):

  def get_filtered_filenames(self):
    return EMPTY_SET

class CurrentModuleFilter(StackTraceFilter):
  """Filters stack frames from the module where this is used (best effort)."""

  def __init__(self):
    super().__init__()
    filter_filename = None
    outer_f = None
    f = inspect.currentframe()
    try:
      if f is not None:
        # The current frame is __init__. The first outer frame should be the
        # caller.
        outer_f = f.f_back
        if outer_f is not None:
          filter_filename = inspect.getsourcefile(outer_f)
      self._filename = filter_filename
      # This may be called repeatedly: once on entry by the superclass, then by
      # each child context manager.
      self._cached_set = None
    finally:
      # Avoid reference cycles, see:
      # https://docs.python.org/3.7/library/inspect.html#the-interpreter-stack
      del f
      del outer_f

  def get_filtered_filenames(self):
    if self._cached_set is not None:
      return self._cached_set

    filtered_filenames = frozenset((self._filename,))
    if self.parent is not None:
      filtered_filenames |= self.parent.get_filtered_filenames()
    self._cached_set = filtered_filenames
    return filtered_filenames

def extract_stack(stacklevel=1):
  """An eager-friendly alternative to traceback.extract_stack.

  Args:
    stacklevel: number of initial frames to skip when producing the stack.

  Returns:
    A list-like FrameSummary containing StackFrame-like objects, which are
    namedtuple-like objects with the following fields: filename, lineno, name,
    line, meant to masquerade as traceback.FrameSummary objects.
  """
  thread_key = _get_thread_key()
  return _tf_stack.extract_stack(
      _source_mapper_stacks[thread_key][-1].internal_map,
      _source_filter_stacks[thread_key][-1].internal_set,
      stacklevel,
  )

def LoadTracesFromDebugInfo(debug_info):
  return _tf_stack.LoadTracesFromDebugInfo(debug_info.SerializeToString())

class GraphDebugInfoBuilder(_tf_stack.GraphDebugInfoBuilder):

  def AppendGraphDebugInfo(self, fn_name, fn_debug_info):
    debug_info_str = fn_debug_info.SerializeToString()
    super().AppendGraphDebugInfo(fn_name, debug_info_str)

  def Build(self):
    debug_info_str = super().Build()
    debug_info = graph_debug_info_pb2.GraphDebugInfo()
    debug_info.ParseFromString(debug_info_str)
    return debug_info

StackSummary = _tf_stack.StackTrace
FrameSummary = _tf_stack.StackFrame


import pandas as pd
import os
import numpy as np
from scipy import optimize
from scipy import integrate
from scipy.integrate import odeint

from basemodel import BaseModel

class SEIRModel(BaseModel):
    """
    SEIR MODEL

    """
    def __init__(self, beta_init=0.1, gamma_init=0.3, delta_init = 1/3,N = 70* 10**6, i0 = 1):
        self.beta_0 = beta_init
        self.gamma_0 = gamma_init
        self.delta_0 = delta_init
        self.beta_ = None
        self.gamma_ = None
        self.delta_ = None
        self.N = N
        self.i0 = 1
        self.s0 = self.N - self.i0
        self.r0 = 0
        self.e0 = 1 # number of confirmed cases on the 5th day

    def seir_model(self, y, x, beta, gamma, delta):
        sus = -beta * y[0] * y[2] / self.N
        expo = beta * y[0] * y[2] / self.N - delta * y[1]
        inf = delta * y[1] - gamma * y[2]
        rec = gamma * y[2]
        return sus, expo, inf, rec

    def fit_odeint(self, x, beta, gamma, delta):
        return integrate.odeint(self.seir_model, (self.s0, self.e0, self.i0, self.r0), x, args=(beta, gamma, delta))[:,1]

    def fit(self, X, y):
        popt, pcov = optimize.curve_fit(self.fit_odeint, X, y)
        fitted = self.fit_odeint(X, *popt)
        self.X_fit = fitted
        self.beta = popt[0]
        self.gamma = popt[1]
        self.delta = popt[2]
        return self

    def predict(self, x):
        return integrate.odeint(self.seir_model, (self.s0, self.e0, self.i0, self.r0), x, args=(self.beta, self.gamma, self.delta)).T


from absl.testing import parameterized

from lingvo import compat as tf
from lingvo.core import attention_util
from lingvo.core import test_utils

import numpy as np

FLAGS = tf.flags.FLAGS

class RelPositionBiasTest(test_utils.TestCase, parameterized.TestCase):

  def testBasic(self):
    with self.session():
      t = 3
      # [BTNH].
      content = tf.linalg.diag(tf.ones([t]))[None, :, None, :]
      # [LNH].
      abs_pos_emb = tf.reshape(
          tf.range(t * (2 * t - 1), dtype=tf.float32), [2 * t - 1, 1, t])
      tf.logging.info('content=%s abs_pos_emb=%s', content.eval(),
                      abs_pos_emb.eval())
      p = attention_util.PositionalAttenLogits.Params().Set(name='rel_pos_bias')
      pos_atten_logits = p.Instantiate()
      self.assertAllClose(
          [[[[6., 3., 0.], [10., 7., 4.], [14., 11., 8.]]]],
          pos_atten_logits.RelPositionBias(content, abs_pos_emb).eval(),
      )

def OracleAttentionLogits(query,
                          key,
                          abs_pos_emb,
                          content_bias,
                          positional_bias,
                          skip_term_b=False):
  """Computes expected attention logits using non-vectorized approach."""
  batch, seqlen, num_heads, _ = query.shape
  tgtlen, srclen = seqlen, seqlen

  logits = np.zeros((batch, num_heads, tgtlen, srclen))

  for b in range(batch):
    for n in range(num_heads):
      for i in range(tgtlen):
        for j in range(srclen):
          offset = seqlen - 1
          pos_emb = abs_pos_emb[i - j + offset]
          logits[b][n][i][j] = np.dot(query[b][i][n], key[b][j][n])
          if not skip_term_b:
            logits[b][n][i][j] += np.dot(query[b][i][n], pos_emb[n])
          if content_bias is not None:
            logits[b][n][i][j] += np.dot(content_bias[n], key[b][j][n])
          if positional_bias is not None:
            logits[b][n][i][j] += np.dot(positional_bias[n], pos_emb[n])
  return logits

class TransformerXLRelativeAttentionTest(test_utils.TestCase,
                                         parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.input_dim = 32
    self.num_heads = 4
    self.batch = 4
    self.seqlen = 16

  def _GetTestInputs(self):
    np.random.seed(FLAGS.test_random_seed)
    query = 3 * np.random.rand(self.batch, self.seqlen, self.num_heads,
                               self.input_dim).astype(np.float32)
    key = 5 * np.random.rand(self.batch, self.seqlen, self.num_heads,
                             self.input_dim).astype(np.float32)
    abs_pos_emb = 7 * np.random.rand(2 * self.seqlen - 1, self.num_heads,
                                     self.input_dim).astype(np.float32)
    content_bias = 11 * np.random.rand(self.num_heads, self.input_dim).astype(
        np.float32)
    positional_bias = 13 * np.random.rand(self.num_heads,
                                          self.input_dim).astype(np.float32)
    return query, key, abs_pos_emb, content_bias, positional_bias

  @parameterized.named_parameters(
      ('Base', False),
      ('Lite', True),
  )
  def testTransformerXL(self, skip_term_b):
    (query, key, abs_pos_emb, content_bias,
     positional_bias) = self._GetTestInputs()
    expected = OracleAttentionLogits(query, key, abs_pos_emb, content_bias,
                                     positional_bias, skip_term_b)
    p = attention_util.PositionalAttenLogits.Params().Set(name='transformer_xl')
    pos_atten_logits = p.Instantiate()
    actual_t = pos_atten_logits.AttenLogitsXL(query, key, abs_pos_emb,
                                              content_bias, positional_bias,
                                              skip_term_b)
    with self.session() as sess:
      actual = sess.run(actual_t)
    self.assertAllClose(expected, actual)

  def testRPE(self):
    (query, key, abs_pos_emb, _, _) = self._GetTestInputs()
    expected = OracleAttentionLogits(query, key, abs_pos_emb, None, None)
    p = attention_util.PositionalAttenLogits.Params().Set(name='rpe')
    pos_atten_logits = p.Instantiate()
    actual_t = pos_atten_logits.AttenLogitsRPE(query, key, abs_pos_emb)
    with self.session() as sess:
      actual = sess.run(actual_t)
    self.assertAllClose(expected, actual)

class BlockUtilsTest(test_utils.TestCase, parameterized.TestCase):

  @parameterized.named_parameters(
      ('single_block', 7),
      ('one_frame_block', 1),
      ('two_frame_blocks', 2),
  )
  def testConvertToBlocks(self, block_size):
    x_val = np.random.random([2, 6, 2, 3, 4])
    with self.session() as sess:
      x = tf.convert_to_tensor(x_val, tf.float32)
      x_blocks = attention_util.ConvertToBlocks(x, block_size)
      x_blocks_val = sess.run(x_blocks)
    # Check shape.
    batch_size = x_val.shape[0]
    other_dims = x_val.shape[2:]
    num_blocks = int(np.ceil(x_val.shape[1] / float(block_size)))
    expected_shape = (batch_size, num_blocks, block_size) + other_dims
    self.assertAllEqual(expected_shape, x_blocks_val.shape)

    # Check values.
    x_recover = x_blocks_val.reshape((x_blocks_val.shape[0], -1) +
                                     x_blocks_val.shape[3:])
    x_recover = x_recover[:, :x_val.shape[1], ...]
    self.assertAllClose(x_val, x_recover)

  @parameterized.named_parameters(
      ('single_block', 7, 2, 1),
      ('single_frame_context', 1, 1, 0),
      ('other_case_1', 3, 4, 1),
      ('other_case_2', 4, 2, 4),
  )
  def testExtractBlockContext(self, block_size, left_context, right_context):
    x_val = np.random.random([2, 6, 2, 3, 4])
    with self.session() as sess:
      x = tf.convert_to_tensor(x_val, tf.float32)
      x_context = attention_util.ExtractBlockContext(x, block_size,
                                                     left_context,
                                                     right_context)
      x_context_val = sess.run(x_context)
    # Check shape.
    batch_size = x_val.shape[0]
    other_dims = x_val.shape[2:]
    num_blocks = int(np.ceil(x_val.shape[1] / float(block_size)))
    context_size = block_size + left_context - 1 + right_context
    expected_shape = (batch_size, num_blocks, context_size) + other_dims
    self.assertAllEqual(expected_shape, x_context_val.shape)

    # Check values block by block.
    for block_idx in range(num_blocks):
      context_start = block_idx * block_size - left_context + 1
      context_end = (block_idx + 1) * block_size + right_context
      slice_start = max(0, context_start)
      slice_end = min(x_val.shape[1], context_end)
      expected_val = x_val[:, slice_start:slice_end, ...]
      actual_val = x_context_val[:, block_idx, ...]
      # remove paddings
      front_padding = slice_start - context_start
      back_padding = context_end - slice_end
      actual_val = actual_val[:, front_padding:context_size - back_padding, ...]
      self.assertAllClose(expected_val, actual_val)

  def _getReferenceCausalPadding(self, seq_len, block_size, left_context,
                                 right_context):
    num_blocks = int(np.ceil(seq_len / float(block_size)))
    context_size = block_size + left_context - 1 + right_context
    padding = np.ones((num_blocks, block_size, context_size))

    for i in range(num_blocks):
      for j in range(block_size):
        actual_src_pos = j + i * block_size
        if actual_src_pos < seq_len:
          for k in range(context_size):
            actual_tgt_pos = k + i * block_size - (left_context - 1)
            if 0 <= actual_tgt_pos and actual_tgt_pos < seq_len:
              diff = actual_src_pos - actual_tgt_pos
              if -right_context <= diff and diff < left_context:
                padding[i, j, k] = 0

    return padding

  @parameterized.named_parameters(
      ('single_block', 6, 9, 2, 1),
      ('single_frame_block', 6, 1, 2, 1),
      ('single_frame_context', 6, 1, 1, 0),
      ('other_case_1', 6, 3, 4, 1),
      ('other_case_2', 6, 4, 2, 4),
  )
  def testMakeLocalMask(self, seq_len, block_size, left_context, right_context):
    with self.session() as sess:
      seq_len_t = tf.convert_to_tensor(seq_len)
      mask = attention_util.MakeLocalMask(seq_len_t, block_size, left_context,
                                          right_context)
      padding = 1.0 - mask
      padding_val = sess.run(padding)

    ref_padding = self._getReferenceCausalPadding(seq_len, block_size,
                                                  left_context, right_context)
    self.assertAllEqual(ref_padding, padding_val)

class KMeansClusteringForAttenTest(test_utils.TestCase):

  def testFProp(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 2
    p.dim_per_head = 4
    p.num_heads = 3
    batch_size = 5
    seq_length = 6
    x = np.random.rand(batch_size, seq_length, p.num_heads,
                       p.dim_per_head).astype(np.float32)
    k_means = p.Instantiate()

    with self.session():
      dists, loss = k_means.FProp(k_means.theta, x, update=True)
      self.evaluate(tf.global_variables_initializer())
      dists, loss = self.evaluate([dists, loss])
      self.assertEqual(dists.shape,
                       (batch_size, seq_length, p.num_heads, p.num_clusters))
      self.assertEqual(loss.shape, ())

  def testFPropWithBfloat16AndNonTrainable(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 2
    p.dim_per_head = 4
    p.num_heads = 3
    p.trainable = False
    p.use_bfloat16 = True
    batch_size = 5
    seq_length = 6
    x = np.random.rand(batch_size, seq_length, p.num_heads,
                       p.dim_per_head).astype(np.float32)
    k_means = p.Instantiate()

    with self.session():
      dists, loss = k_means.FProp(k_means.theta, x, update=True)
      self.evaluate(tf.global_variables_initializer())
      dists, loss = self.evaluate([dists, loss])
      self.assertEqual(dists.shape,
                       (batch_size, seq_length, p.num_heads, p.num_clusters))
      self.assertEqual(loss.shape, ())

  def testFPropFixedInput(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 3
    p.dim_per_head = 6
    p.num_heads = 4
    p.decay = 0.5
    k_means = p.Instantiate()
    batch_size = 2
    seq_length = 5

    with self.session():
      x = np.random.rand(batch_size, seq_length, p.num_heads,
                         p.dim_per_head).astype(np.float32)
      self.evaluate(tf.global_variables_initializer())
      fixed_loss = None
      for _ in range(10):
        dists, loss = k_means.FProp(k_means.theta, x, update=False)
        dists, loss = self.evaluate([dists, loss])
        if not fixed_loss:
          fixed_loss = loss
        else:
          # If we do not update, the loss remain fixed.
          self.assertEqual(loss, fixed_loss)
      prev_loss = fixed_loss
      self.evaluate(k_means.FProp(k_means.theta, x, update=True))
      for _ in range(5):
        dists, loss = k_means.FProp(k_means.theta, x, update=True)
        _, loss = self.evaluate([dists, loss])
        # If we update the centroids, the loss should strictly decrease.
        self.assertGreater(prev_loss - loss, 1e-5)
        prev_loss = loss

  def testFPropClustering(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 2
    p.dim_per_head = 3
    p.num_heads = 2
    p.decay = 0.8
    k_means = p.Instantiate()
    batch_size = 3
    seq_length = 3

    with self.session() as sess:
      self.evaluate(tf.global_variables_initializer())

      def _GenInput():
        # We randomly generate inputs such that head 0 is clustered
        # around (±1/√2, ±1/√2, ∓√2), while head 1 is clustered around
        # (∓-√2, ±1/√2, ±1/√2).
        noise = 0.05 * np.random.rand(batch_size, seq_length, p.num_heads,
                                      p.dim_per_head).astype(np.float32)
        x1 = np.random.binomial(1, 0.5, [batch_size, seq_length, 1, 1]) * 2 - 1
        x1 = np.tile(
            np.array([1., 1., -1.], dtype=np.float32),
            [batch_size, seq_length, 1, 1]) * x1
        x2 = np.random.binomial(1, 0.5, [batch_size, seq_length, 1, 1]) * 2 - 1
        x2 = np.tile(
            np.array([-1., 1., 1.], dtype=np.float32),
            [batch_size, seq_length, 1, 1]) * x2
        x = np.concatenate([x1, x2], axis=2) + noise
        return x.astype(np.float32)

      for _ in range(25):
        _, loss = sess.run(
            k_means.FProp(k_means.theta, _GenInput(), update=True))
      final_means = k_means.theta.means.eval()
    # We assert that the centroids are close to the true centers.
    self.assertAllClose(
        np.abs(final_means), [[[0.71, 0.71, 1.41], [0.71, 0.71, 1.41]],
                              [[1.41, 0.71, 0.71], [1.41, 0.71, 0.71]]],
        rtol=0.03,
        atol=0.03)
    self.assertLess(loss, 0.005)

  def testFPropPadding(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 2
    p.dim_per_head = 3
    p.num_heads = 1
    p.decay = 0.7
    k_means = p.Instantiate()
    batch_size = 3
    seq_length = 5

    with self.session() as sess:
      self.evaluate(tf.global_variables_initializer())

      def _GenInput():
        # We randomly generate inputs such that inputs are clustered
        # around (±1/√2, ±1/√2, ∓√2) or (∓-√2, ±1/√2, ±1/√2) with one of them
        # hidden by padding.
        paddings = np.random.binomial(1, 0.5, [batch_size, seq_length]).astype(
            np.float32)
        x = np.expand_dims(np.expand_dims(paddings, axis=-1), axis=-1)
        # When padding is 0, we generate (∓1, 1, ±1); when padding is 1, we
        # generate (±1, 1, ∓1).
        x = np.concatenate([2 * x - 1, np.ones_like(x), 1 - 2 * x], axis=-1)
        x *= np.random.binomial(1, 0.5, [batch_size, seq_length, 1, 1]) * 2 - 1
        return x, paddings

      for _ in range(30):
        x, paddings = _GenInput()
        self.assertEqual(x.shape,
                         (batch_size, seq_length, p.num_heads, p.dim_per_head))
        self.assertEqual(paddings.shape, (batch_size, seq_length))
        _, loss1 = sess.run(
            k_means.FProp(k_means.theta, x, paddings, update=True))
      means1 = k_means.theta.means.eval()

      # We reverse the padding to hide the other half.
      for _ in range(40):
        x, paddings = _GenInput()
        _, loss2 = sess.run(
            k_means.FProp(k_means.theta, x, 1.0 - paddings, update=True))
      means2 = k_means.theta.means.eval()

      # We compute the loss using the previous input centering on
      # different centroids. The squared distance should be 3.
      _, loss3 = sess.run(
          k_means.FProp(k_means.theta, x, paddings, update=False))

    self.assertAllClose(
        np.abs(means1), [[[1.41, 0.71, 0.71], [1.41, 0.71, 0.71]]],
        rtol=0.03,
        atol=0.03)
    self.assertLess(loss1, 1e-5)
    self.assertAllClose(
        np.abs(means2), [[[0.71, 0.71, 1.41], [0.71, 0.71, 1.41]]],
        rtol=0.03,
        atol=0.03)
    self.assertLess(loss2, 1e-5)

    self.assertAllClose(loss3, 3.0, 1e-4, 1e-4)

  def testFPropClusteringEmptyCluster(self):
    p = attention_util.KMeansClusteringForAtten.Params()
    p.name = 'k_means'
    p.num_clusters = 10
    p.dim_per_head = 3
    p.num_heads = 1
    p.decay = 0.8
    k_means = p.Instantiate()
    batch_size = 3
    seq_length = 4

    # All of our inputs are (1, 1, -1)
    x = np.ones([batch_size, seq_length, 1, 1], dtype=np.float32)
    x = np.concatenate([x, x, -x], axis=-1)
    with self.session() as sess:
      self.evaluate(tf.global_variables_initializer())
      for _ in range(30):
        dists, loss = sess.run(k_means.FProp(k_means.theta, x, update=True))
      means = k_means.theta.means.eval()
    idx = np.argmin(dists, axis=-1)
    idx_1 = idx[0, 0, 0]
    # We assert that 'dists' achieves minimum all at the same cluster.
    self.assertAllEqual(idx,
                        np.array(idx_1 * np.ones([batch_size, seq_length, 1])))
    # We assert that at this index the centroid is close to (1/√2, 1/√2, -√2).
    means = np.squeeze(means[:, idx_1, :])
    self.assertAllClose(means, [0.71, 0.71, -1.41], rtol=0.03, atol=0.03)
    self.assertLess(loss, 1e-4)

class ComputeSparseAttention(test_utils.TestCase):

  def testBasics(self):
    batch_size = 3
    source_length = 5
    target_length = 4
    num_heads = 2
    dim_per_head = 3
    q = np.random.rand(batch_size, target_length, num_heads,
                       dim_per_head).astype(np.float32)
    k = np.random.rand(batch_size, source_length, num_heads,
                       dim_per_head).astype(np.float32)
    v = np.random.rand(batch_size, source_length, num_heads,
                       dim_per_head).astype(np.float32)
    # attention window = 2
    sparsity_indices = np.concatenate([
        np.zeros([batch_size, target_length, num_heads, 1], dtype=np.int32),
        np.ones([batch_size, target_length, num_heads, 1], dtype=np.int32),
    ],
                                      axis=-1)

    with self.session() as sess:
      out, probs = sess.run(
          attention_util.ComputeSparseAttention(q, k, v, sparsity_indices))
      self.assertEqual(out.shape,
                       (batch_size, target_length, num_heads, dim_per_head))
      self.assertEqual(probs.shape,
                       (batch_size, target_length, num_heads, source_length))
      # attention weights sum to 1.
      self.assertAllClose(
          np.sum(probs, axis=-1),
          np.ones([batch_size, target_length, num_heads]))

    # attention window = 4, but last two are always paddings.
    sparsity_indices = np.concatenate([
        sparsity_indices,
        -np.ones([batch_size, target_length, num_heads, 2], dtype=np.int32),
    ],
                                      axis=-1)
    with self.session() as sess:
      out2, probs2 = sess.run(
          attention_util.ComputeSparseAttention(q, k, v, sparsity_indices))
      # We assert that the encoded outputs are the same as before,
      # and the attention weights are 0 on the padded positions.
      self.assertAllClose(out, out2)
      self.assertAllClose(probs, probs2)

    # attention window = 4.
    sparsity_indices = np.tile(
        np.arange(4, dtype=np.int32), [batch_size, target_length, num_heads, 1])
    # but position 2 and 3 are padded.
    paddings = np.tile([0., 0., 1., 1., 0.], [batch_size, 1])
    with self.session() as sess:
      out3, probs3 = sess.run(
          attention_util.ComputeSparseAttention(q, k, v, sparsity_indices,
                                                paddings))
      # We assert that the encoded outputs and attention weights are the same
      # as before.
      self.assertAllClose(out2, out3)
      self.assertAllClose(probs2, probs3)

  def testFullAttention(self):
    batch_size = 4
    source_length = 7
    target_length = 6
    num_heads = 3
    dim_per_head = 5
    q = np.random.rand(batch_size, target_length, num_heads,
                       dim_per_head).astype(np.float32)
    k = np.random.rand(batch_size, source_length, num_heads,
                       dim_per_head).astype(np.float32)
    v = np.random.rand(batch_size, source_length, num_heads,
                       dim_per_head).astype(np.float32)
    # attention window = source length, randomly permutated
    # np.arange(source_length)
    sparsity_indices = np.tile(
        np.random.permutation(source_length).astype(np.int32),
        [batch_size, target_length, num_heads, 1])

    with self.session() as sess:
      out, probs = sess.run(
          attention_util.ComputeSparseAttention(q, k, v, sparsity_indices))

    # compute full attention in numpy
    expected_logit = np.einsum('BTNH, BSNH -> BTNS', q, k)
    expected_logit /= np.sqrt(dim_per_head)
    elexp = np.exp(expected_logit)
    expected_probs = elexp / np.expand_dims(np.sum(elexp, axis=-1), axis=-1)
    expected_output = np.einsum('BTNS, BSNH -> BTNH', expected_probs, v)

    # We assert that the output is close to the full attention,
    # since our sparsity_indices is range(source_length)
    self.assertAllClose(probs, expected_probs)
    self.assertAllClose(out, expected_output)

if __name__ == '__main__':
  tf.test.main()


from BinaryTree import BinaryTree
from Node import Node

class BST(BinaryTree) :
    def __init__(self):
         super().__init__()

    def Add(self,value):

         if (self.root is None):
              self.root = Node(value)
         else:
            self.add_rec(value,self.root)

    def add_rec(self,value,root):

         if(value==root.value):
              print("No need to add it")

         elif(value<root.value):
              if(root.left):
                   self.add_rec(value,root.left)
              else:
               root.left = Node(value)

         elif(value>root.value):
           if(root.right):
                   self.add_rec(value,root.right)
           else:
              root.right = Node(value)

    def contains(self,value):
         if(self.root == value) : return True
         else :
          return self.contains_rec(self.root, value)

    def contains_rec(self,root,value):

          if (value == root.value):
              return True

          elif(value<root.value):
              if(root.left):
                return self.contains_rec(root.left,value)
              else:
               return False

          else :
           if(root.right):
                return  self.contains_rec(root.right,value)
           else:
              return False

tree_test = BinaryTree()

Node1 = Node(2)
tree_test.root = Node1

Node2 = Node(7)
tree_test.root.left = Node2

Node3 = Node(5)
tree_test.root.right = Node3

Node4 = Node(2)
tree_test.root.left.left = Node4

Node5 = Node(6)
tree_test.root.left.right = Node5

Node5_1 = Node(5)
tree_test.root.left.right.left = Node5_1

Node5_2 = Node(11)
tree_test.root.left.right.right = Node5_2

Node6 = Node(9)
tree_test.root.right.right = Node6

Node6_1 = Node(4)
tree_test.root.right.right.left = Node6_1

# print(tree_test.pre_order(tree_test.root))
# print(tree_test.in_order(tree_test.root))
# print(tree_test.post_order(tree_test.root))

# BST_test = BST()
# BST_test.Add(10)
# BST_test.Add(5)
# BST_test.Add(15)
# BST_test.Add(20)
# BST_test.Add(12)
# BST_test.Add(6)
# BST_test.Add(3)

# print(BST_test.pre_order(BST_test.root))
# print(BST_test.in_order(BST_test.root))
# print(BST_test.post_order(BST_test.root))

# print(BST_test.contains(5))
# print(tree_test.getMax())
print(tree_test.tree_breadth_first(tree_test.root))


# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

#region : File Description and Imports

"""
environment_interpretation.py

Skills activity code for environment interpretation lab guide.
Please review the accompanying "Lab Guide - Environment Interpretation" PDF
"""

import numpy as np
from scipy.special import logit, expit
from scipy import ndimage
from threading import Thread, Lock
import time
import pyqtgraph as pg
import signal

from pal.products.qcar import QCar, QCarGPS, QCarLidar, IS_PHYSICAL_QCAR
from pal.utilities.scope import MultiScope
from pal.utilities.math import find_overlap, wrap_to_2pi, wrap_to_pi
from hal.products.qcar import QCarEKF, QCarDriveController
from hal.products.mats import SDCSRoadMap
#endregion

# ================ Experiment Configuration ================
# ===== Timing Parameters
# - tf: experiment duration in seconds.
# - startDelay: delay to give filters time to settle in seconds.
# - controllerUpdateRate: control update rate in Hz. Shouldn't exceed 500
tf = 100
startDelay = 1
controllerUpdateRate = 100

# ===== Vehicle Controller Parameters
# - enableVehicleControl: If true, the QCar will drive through the specified
#   node sequence. If false, the QCar will remain stationary.
# - v_ref: desired velocity in m/s
# - nodeSequence: list of nodes from roadmap. Used for trajectory generation.
enableVehicleControl = False
v_ref = 0.3
nodeSequence = [0, 20, 0]

# ===== Occupancy Grid Parameters
# - cellWidth: edge length for occupancy grid cells (in meters)
# - r_res: range resolution for polar grid cells (in meters)
# - r_max: maximum range of the lidar (in meters)
# - p_low: likelihood value for vacant cells (according to lidar scan)
# - p_high: likelihood value for occupied cells (according to lidar scan)
cellWidth = 0.02
r_res = 0.05
r_max = 4
p_low = 0.4
p_high = 0.6

#region Initial Setup
lock = Lock()

roadmap = SDCSRoadMap()
waypointSequence = roadmap.generate_path(nodeSequence)
initialPose = roadmap.get_node_pose(nodeSequence[0]).squeeze()
x_hat = initialPose
t_hat = 0

if not IS_PHYSICAL_QCAR:
    import qlabs_setup
    from qvl.qcar import QLabsQCar
    hQCar = qlabs_setup.setup(
        initialPosition=[initialPose[0], initialPose[1], 0],
        initialOrientation=[0, 0, initialPose[2]]
    )

# Used to enable safe keyboard triggered shutdown
KILL_THREAD = False
def sig_handler(*args):
    global KILL_THREAD
    KILL_THREAD = True
signal.signal(signal.SIGINT, sig_handler)

gps = QCarGPS(initialPose=initialPose)
while (not KILL_THREAD) and (gps.readGPS() or  gps.readLidar()):
    pass

#endregion

class OccupancyGrid:

    def __init__(self,
            x_min=-4,
            x_max=3,
            y_min=-3,
            y_max=6,
            cellWidth=0.02,
            r_max=5,
            r_res=0.02,
            p_low=0.4,
            p_high=0.6
        ):

        #region define probabilities and their log-odds forms
        self.p_low = p_low
        self.p_prior = 0.5
        self.p_high = p_high
        self.p_sat = 0.001

        self.l_low = logit(self.p_low)
        self.l_prior = logit(self.p_prior)
        self.l_high = logit(self.p_high)
        self.l_min = logit(self.p_sat)
        self.l_max = logit(1-self.p_sat)
        #endregion

        self.init_polar_grid(r_max, r_res)

        self.init_world_map(
            x_min=x_min,
            x_max=x_max,
            y_min=y_min,
            y_max=y_max,
            cellWidth=cellWidth
        )
        self.init_patch()

    # ==============  SECTION A - Polar Grid ====================
    def init_polar_grid(self, r_max, r_res):
        # Configuration Parameters for polar grid
        fov = 2*np.pi
        self.phiRes = 1 * np.pi/180
        self.r_max = r_max
        self.r_res = r_res

        # Size of polar patch
        self.mPolarPatch = np.int_(np.ceil(fov / self.phiRes))
        self.nPolarPatch = np.int_(np.floor(self.r_max/self.r_res))

        self.polarPatch = np.zeros(
            shape = (self.mPolarPatch, self.nPolarPatch),
            dtype = np.float32
        )

    def update_polar_grid(self, r):
        # Implement code here to populate the values of self.polarPatch
        # given LiDAR range data 'r'.
        # - r is a 1D list of length self.mPolarPatch
        # - All range measurements are equally self.phiRes radians apart,
        #   starting with 0

        # Implement Your Solution Here

        pass

        ''' Quanser Solution Implemented Below
        r = np.int_(np.round(r / self.r_res))
        for i in range(self.mPolarPatch):
            if r[i] > 0:
                self.polarPatch[i,:r[i]] = self.l_low
                self.polarPatch[i,r[i]:r[i]+1] = self.l_high
                self.polarPatch[i,r[i]+1:] = self.l_prior
            else:
                self.polarPatch[i,:] = self.l_prior
        '''

    # ==============  SECTION B - Interpolation ====================
    def init_patch(self):
        self.nPatch = np.int_(2*np.ceil(self.r_max/self.cellWidth) + 1)
        self.patch = np.zeros(
            shape = (self.nPatch, self.nPatch),
            dtype = np.float32
        )

    def generate_patch(self, th):
        # Implement Your Solution Here
        pass

        ''' Quanser Solution Implemented Below

        cx = (self.nPatch * self.cellWidth) / 2
        cy = cx

        x = np.linspace(-cx, cx, self.nPatch)
        y = np.linspace(-cy, cy, self.nPatch)
        xv, yv = np.meshgrid(x, y)

        rPatch = (
            np.sqrt(np.square(xv) + np.square(yv)) / self.r_res
        )
        phiPatch = (
            wrap_to_2pi(np.arctan2(yv, xv) + th) / self.phiRes
        )
        ndimage.map_coordinates(
            input=self.polarPatch,
            coordinates=[phiPatch, rPatch],
            output=self.patch
        )
        '''

    # ==============  SECTION C - Occupancy Grid Update  ====================
    def init_world_map(self,
            x_min = -4,
            x_max = 3,
            y_min = -3,
            y_max = 6,
            cellWidth=0.02
        ):

        self.x_min = x_min
        self.x_max = x_max
        self.y_min = y_min
        self.y_max = y_max
        self.cellWidth = cellWidth
        self.xLength = x_max - x_min
        self.yLength = y_max - y_min
        self.m = np.int_(np.ceil(self.yLength/self.cellWidth))
        self.n = np.int_(np.ceil(self.xLength/self.cellWidth))

        self.map = np.full(
            shape = (self.m, self.n),
            fill_value = self.l_prior,
            dtype = np.float32
        )

    def xy_to_ij(self, x, y):
        i = np.int_(np.round( (self.y_max - y) / self.cellWidth ))
        j = np.int_(np.round( (x - self.x_min) / self.cellWidth ))
        return i, j

    def updateMap(self, x, y, th, angles, distances):

        # Function created in SECTION A
        self.update_polar_grid(distances)

        # Function created in SECTION B
        self.generate_patch(th)
        # Implement code here to update self.map using self.patch

        pass
        ''' Quanser Solution Implemented Below
        # calculate Location of cells to update position offsets
        iy, jx = self.xy_to_ij(x, y)

        iTop = np.int_(iy - np.round((self.nPatch-1)/2))
        jLeft = np.int_(jx - np.round((self.nPatch-1)/2))

        mapSlice, patchSlice = find_overlap(
            self.map,
            self.patch,
            iTop,
            jLeft
        )

        self.map[mapSlice] = np.clip(
            (self.map[mapSlice] + self.patch[patchSlice]),
            self.l_min,
            self.l_max
        )
        '''

def controlLoop():
    #region controlLoop setup
    global KILL_THREAD, x_hat, t_hat
    u = 0
    delta = 0
    # used to limit data sampling to 10hz
    countMax = controllerUpdateRate / 10
    count = 0
    #endregion

    #region Set up plot items
    arrow1 = pg.ArrowItem(
        angle=180,
        tipAngle=60,
        headLen=10,
        tailLen=10,
        tailWidth=5,
        pen={'color': 'w', 'width': 1},
        brush='r'
    )
    arrow1.setPos(0,0)
    scope.axes[1].plot.addItem(arrow1)

    arrow2 = pg.ArrowItem(
        angle=180,
        tipAngle=60,
        headLen=10,
        tailLen=10,
        tailWidth=5,
        pen={'color': 'w', 'width': 1},
        brush='r'
    )
    scope.axes[2].plot.addItem(arrow2)
    #endregion

    #region QCar interface setup
    with lock:
        ekf = QCarEKF(x_0=x_hat)
    driveController = QCarDriveController(waypointSequence, cyclic=False)

    qcar = QCar(readMode=1, frequency=controllerUpdateRate)
    #endregion

    with qcar:
        t0 = time.time()
        t = 0
        while (t < tf+startDelay) and (not KILL_THREAD):
            #region : Loop timing update
            tp = t
            t = time.time() - t0
            dt = t-tp
            #endregion

            #region : Update QCar state estimates and drive controller
            qcar.read()
            if gps.readGPS():
                y_gps = np.array([
                    gps.position[0],
                    gps.position[1],
                    gps.orientation[2]
                ])
                ekf.update(
                    [qcar.motorTach, delta],
                    dt,
                    y_gps,
                    qcar.gyroscope[2],
                )
            else:
                ekf.update(
                    [qcar.motorTach, delta],
                    dt,
                    None,
                    qcar.gyroscope[2],
                )
            with lock:
                t_hat = time.time()
                x_hat = ekf.x_hat[:]

            x = ekf.x_hat[0, 0]
            y = ekf.x_hat[1, 0]
            v = qcar.motorTach
            th = ekf.x_hat[2, 0]
            p = np.array([x, y]) + np.array([np.cos(th), np.sin(th)]) * 0.2

            if t < startDelay or (not enableVehicleControl):
                u = 0
                delta = 0
            else:
                u, delta = driveController.update(p, th, v, v_ref, dt)
            qcar.write(u, delta)
            #endregion

            #region : Update Scopes
            count += 1
            if count >= countMax and t > startDelay:
                scope.axes[2].sample(t, [[p[0], p[1]]])
                arrow1.setStyle(angle=180-th*180/np.pi)
                arrow2.setPos(p[0],p[1])
                arrow2.setStyle(angle=180-th*180/np.pi)

                count = 0
            #endregion

            if driveController.steeringController.pathComplete:
                return
            continue
        with lock:
            print('Control thread terminated')

def mappingLoop():
    global KILL_THREAD, x_hat, t_hat

    og = OccupancyGrid(
        cellWidth=cellWidth,
        r_res=r_res,
        r_max=r_max,
        p_low=p_low,
        p_high=p_high
    )

    #region Configure Plots
    scope.axes[0].images[0].rotation = 90
    scope.axes[0].images[0].scale = (og.r_res, -og.phiRes*180/np.pi)
    scope.axes[0].images[0].offset = (0, 0)
    scope.axes[0].images[0].levels = (0, 1)

    scope.axes[1].images[0].scale = (og.r_res, -og.r_res)
    scope.axes[1].images[0].offset = (-og.nPatch/2, -og.nPatch/2)
    scope.axes[1].images[0].levels = (0, 1)

    scope.axes[2].images[0].scale = (og.cellWidth, -og.cellWidth)
    scope.axes[2].images[0].offset = (
        og.x_min/og.cellWidth,
        -og.y_max/og.cellWidth
    )
    scope.axes[2].images[0].levels = (0, 1)
    #endregion

    t0 = time.time()
    while time.time()-t0 < startDelay:
        gps.readLidar()

    while (not KILL_THREAD):
        #region Get latest pose estimate
        with lock:
            t = t_hat
            x = x_hat[0,0]
            y = x_hat[1,0]
            th = x_hat[2,0]

        x += 0.125 * np.cos(th)
        y += 0.125 * np.sin(th)
        #endregion

        #region Read from Lidar and Update Occupancy Grid
        while not KILL_THREAD:
            gps.readLidar()
            if  gps.scanTime >= t:
                break
        og.updateMap(x, y, th, gps.angles, gps.distances)
        #endregion

        scope.axes[0].images[0].setImage(image=expit(og.polarPatch))
        scope.axes[1].images[0].setImage(image=expit(og.patch))
        scope.axes[2].images[0].setImage(image=expit(og.map))

    with lock:
        print('Mapping thread terminated')

#region : Setup and run experiment
if __name__ == '__main__':

    #region : Setup Scopes
    if IS_PHYSICAL_QCAR:
        fps = 10
    else:
        fps = 30

    scope = MultiScope(
        rows=2,
        cols=2,
        title='Environment Interpretation',
        fps=fps
    )

    # Polar Patch
    scope.addXYAxis(
        row=0,
        col=0,
        xLabel='Angle [deg]',
        yLabel='Range [m]'
    )
    scope.axes[0].attachImage()

    # Patch
    scope.addXYAxis(
        row=1,
        col=0,
        xLabel='x Position [m]',
        yLabel='y Position [m]'
    )
    scope.axes[1].attachImage()

    # Generated Map and followed trajectory
    scope.addXYAxis(
        row=0,
        col=1,
        rowSpan=2,
        xLabel='x Position [m]',
        yLabel='y Position [m]',
        xLim=(-4, 3),
        yLim=(-2, 6)
    )
    scope.axes[2].attachSignal(name='Measured', width=2, style='--.')
    scope.axes[2].attachImage()

    referencePath = pg.PlotDataItem(
        pen={'color': (85,168,104), 'width': 2},
        name='Reference'
    )
    referencePath.setData(waypointSequence[0, :], waypointSequence[1, :])
    scope.axes[2].plot.addItem(referencePath)
    #endregion

    #region : Setup threads, then run experiment
    controlThread = Thread(target=controlLoop)
    mappingThread = Thread(target=mappingLoop)

    controlThread.start()
    mappingThread.start()

    try:
        while controlThread.is_alive() and mappingThread.is_alive():
            MultiScope.refreshAll()
            time.sleep(0.01)
    finally:
        KILL_THREAD = True
        controlThread.join()
        mappingThread.join()
        gps.terminate()
    #endregion

    input('Experiment complete. Press any key to exit...')
#endregion


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

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

import tensorflow as tf
import os
from data.io import image_preprocess
from configs.config import Config
from libs.box_utils import boxes_utils, make_anchor

def train_parse_fn(example):
    """
    :param example: 序列化的输入
    :return:
    """
    config = Config()
    features = tf.parse_single_example(
        serialized=example,
        features={
            'img_name': tf.FixedLenFeature([], tf.string),
            'img_height': tf.FixedLenFeature([], tf.int64),
            'img_width': tf.FixedLenFeature([], tf.int64),
            'img': tf.FixedLenFeature([], tf.string),
            'gtboxes_and_label': tf.FixedLenFeature([], tf.string)
        }
    )
    img_name = features['img_name']
    img_height = tf.cast(features['img_height'], tf.int32)
    img_width = tf.cast(features['img_width'], tf.int32)
    img = tf.decode_raw(features['img'], tf.uint8)

    img = tf.reshape(img, shape=[img_height, img_width, 3])
    img = tf.cast(img, tf.float32)

    gt_boxes_and_label = tf.decode_raw(features['gtboxes_and_label'], tf.int32)
    gt_boxes_and_label = tf.reshape(gt_boxes_and_label, [-1, 5])
    # shape of img is (1024, 1024, 3), image_window(4,)[y1, x1, y2, x2]
    img, gt_boxes_and_label, image_window = image_preprocess.image_resize_pad(img_tensor=img,
                                                                              gtboxes_and_label=gt_boxes_and_label,
                                                                              target_side=config.TARGET_SIDE)
    img, gt_boxes_and_label = image_preprocess.random_flip_left_right(img_tensor=img,
                                                                      gtboxes_and_label=gt_boxes_and_label)
    # choose or padding make the gt_bbox_labels is FAST_RCNN_MAX_INSTANCES
    num_objects = tf.shape(gt_boxes_and_label)[0]
    object_index = tf.range(num_objects)
    object_index = tf.random_shuffle(object_index)
    object_index = object_index[:config.FAST_RCNN_MAX_INSTANCES]
    gt_boxes_and_label = tf.gather(gt_boxes_and_label, object_index)
    anchor = make_anchor.generate_pyramid_anchors(config)
    minibatch_indices, minibatch_encode_gtboxes, \
    rpn_objects_one_hot = boxes_utils.build_rpn_target(gt_boxes_and_label[:, :4], anchor, config)
    num_padding = config.FAST_RCNN_MAX_INSTANCES - tf.shape(gt_boxes_and_label)[0]
    # (FAST_RCNN_MAX_INSTANCES, 5)[y1, x1, y2, x2, label]
    num_padding = tf.maximum(num_padding, 0)
    gt_box_label_padding = tf.zeros((num_padding, 5), dtype=tf.int32)
    gt_boxes_and_label = tf.concat([gt_boxes_and_label, gt_box_label_padding], axis=0)

    return {"image_name": img_name, "image": img, "image_window": image_window}, \
           {"gt_box_labels": gt_boxes_and_label, "minibatch_indices": minibatch_indices,
            "minibatch_encode_gtboxes": minibatch_encode_gtboxes, "minibatch_objects_one_hot": rpn_objects_one_hot}

def evaluate_predict_parse_fn(example):

    config = Config()
    features = tf.parse_single_example(
        serialized=example,
        features={
            'img_name': tf.FixedLenFeature([], tf.string),
            'img_height': tf.FixedLenFeature([], tf.int64),
            'img_width': tf.FixedLenFeature([], tf.int64),
            'img': tf.FixedLenFeature([], tf.string),
            'gtboxes_and_label': tf.FixedLenFeature([], tf.string),
        }
    )
    img_name = features['img_name']
    img_height = tf.cast(features['img_height'], tf.int32)
    img_width = tf.cast(features['img_width'], tf.int32)
    img = tf.decode_raw(features['img'], tf.uint8)

    img = tf.reshape(img, shape=[img_height, img_width, 3])
    # img.set_shape([None, None, 3])
    img = tf.cast(img, tf.float32)
    gt_boxes_and_label = tf.decode_raw(features['gtboxes_and_label'], tf.int32)
    gt_boxes_and_label = tf.reshape(gt_boxes_and_label, [-1, 5])
    img, gt_boxes_and_label, image_window = image_preprocess.image_resize_pad(img_tensor=img,
                                                                              gtboxes_and_label=gt_boxes_and_label,
                                                                              target_side=config.TARGET_SIDE)

    return {"image_name": img_name, "image": img, "image_window": image_window, "gt_box_labels": gt_boxes_and_label}

def train_input_fn(data_dir, batch_size=1, epochs=1):

    dataset = tf.data.TFRecordDataset(os.path.join(data_dir, "tct", "train.tfrecord"))
    dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(buffer_size=batch_size * (epochs + 2), count=epochs))
    dataset = dataset.apply(
            tf.contrib.data.map_and_batch(train_parse_fn, batch_size, num_parallel_batches=batch_size + 1))
    dataset = dataset.prefetch(buffer_size=1 + batch_size)
    return dataset

def eval_predict_input_fn(data_dir, batch_size=1):
    dataset = tf.data.TFRecordDataset(os.path.join(data_dir, "tct", "test.tfrecord"))
    dataset = dataset.apply(
        tf.contrib.data.map_and_batch(evaluate_predict_parse_fn, batch_size, num_parallel_batches=batch_size + 1))
    return dataset


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

from Timba.TDL import *
from Timba.Meq import meq
from Meow.Parameterization import *
import Meow

class xyzComponent (Parameterization):

    """A xyzComponent represents an abstract ITRF element.
    xyzComponents have an name and an associated xyz vector in ITRF coordinates. These can be eg. satellite or station positions.
    """

    def __init__(self, ns, name, position):
        Parameterization.__init__(self, ns, name)
        self.xyz = position

    def make_rot_matrix(self):
        """returns the rotation matrix to ENU with this xyz position as referencepoint. NOTE for the moment this can only be done with constant xyz positions (restriction of longlat)"""
        if not self.ns.rot_matrix(self.name).isdefined():
            lon, lat = self.make_longlat()
            cosl = self.ns.cosl(self.name) << Meq.Cos(lon)
            sinl = self.ns.sinl(self.name) << Meq.Sin(lon)
            cosphi = self.ns.cosphi(self.name) << Meq.Cos(lat)
            sinphi = self.ns.sinphi(self.name) << Meq.Sin(lat)

            self.ns.rot_matrix(self.name) << MeqComposer(-1 * sinl, cosl, 0,
                                                         -1 * sinphi * cosl, -1 * sinphi * sinl, cosphi,
                                                         cosphi * cosl, cosphi * sinl, sinphi,
                                                         dims=[3, 3])

        rot_matrix = self.ns.rot_matrix(self.name)
        return rot_matrix

    def make_longlat(self, use_w=1):
        if not self.ns.longlat(self.name).isdefined():

            ll = self.ns.longlat(self.name) << Meq.LongLat(self.xyz, use_w=use_w)
            # use_w=1: use elliptical model for earth

            lon = self.ns.lon(self.name) << Meq.Selector(ll, index=0)
            lat = self.ns.lat(self.name) << Meq.Selector(ll, index=1)

        lon = self.ns.lon(self.name)
        lat = self.ns.lat(self.name)
        return lon, lat


import math
# (2.40,0.02)

import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import numpy as np
import math
import random

ODZ  = [-1.999999999, -0.0000000001 ,0.0000000001, 1000 ]

numbers =[-1.999, -0.001 ,0.001, 1000 ]
prev_number = 0

def check_number_in_range(n):
    global numbers
    global prev_number
    bound = 0
    prev_number = n

    if(prev_number<=0):
        bound =-0.001
    else:
        bound =0.001
    # Получаем минимальное значение из списка
    min_num = min(numbers)
    max_num = max(numbers)
    # Проверяем, находится ли число в заданном диапазоне
    if(n<0):
        if n < min_num:
            return min_num
        elif numbers[0] <= n <= numbers[-1]:
            return n
        else:
            return bound
    elif(n>0):
        if n > max_num:
            return max_num
        elif numbers[0] <= n <= numbers[-1]:
            return n
        else:
            return bound
    elif(n==0):
        return bound

import math

def f(x):
    try:
        return math.log10(x + 2) / x
    except ValueError:
        return float('nan')

def integrate_rectangular(a, b, n=1000):
    """Вычисление интеграла функции f на интервале [a, b] с использованием метода прямоугольников."""

    # Если границы включают неопределенные точки, сместите их немного.
    if a == 0 or a == -2:
        a += 1e-10
    if b == 0 or b == -2:
        b -= 1e-10

    h = (b - a) / n
    integral = 0

    for i in range(n):
        # Вычисляем значение в начале интервала для текущего прямоугольника
        x_value = a + i * h
        integral += f(x_value) * h

    return integral

def integrate_trapezoidal(a, b, n=1000):
    """Вычисление интеграла функции f на интервале [a, b] с использованием метода трапеций."""

    # Если границы включают неопределенные точки, сместите их немного.
    if a == 0 or a == -2:
        a += 1e-10
    if b == 0 or b == -2:
        b -= 1e-10

    h = (b - a) / n
    integral = 0.5 * (f(a) + f(b))

    for i in range(1, n):
        x_value = a + i * h
        integral += f(x_value)

    integral *= h

    return integral

def integrate_monte_carlo(a, b, samples=1000):
    """Вычисление интеграла функции f на интервале [a, b] с использованием метода Монте-Карло."""

    sum_of_samples = 0
    for _ in range(samples):
        # Генерируем случайное число в интервале [a, b]
        random_point = a + (b - a) * random.random()
        # Добавляем значение функции в этой точке к сумме
        sum_of_samples += f(random_point)

    # Усредняем сумму и умножаем на длину интервала
    average = sum_of_samples / samples
    integral = average * (b - a)

    return integral

def plot_graph(from_x, to_x):
    x_values = np.linspace(from_x, to_x, 1000)

    # Filter out -2 and 0 from x_values
    x_values = x_values[(x_values != -2) & (x_values != 0)]

    y_values = [f(x) for x in x_values]

    plt.figure(figsize=(12, 6))
    plt.plot(x_values, y_values, label="Equation: math.log10(x + 2) / x")
    plt.axhline(0, color='black', linewidth=0.5, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.5, linestyle='--')
    plt.title("Graph of the Equation")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid(True)
    plt.show()
def display_results_in_table(a, b, integral_result , type):
    global tree
    # Create a new window for the table

    # Initialize treeview for the table

    # Insert integration results into the table
    tree.insert("", "end", values=(a, b, integral_result,type))
def on_plot_button_click():
    a=-2
    b=-1
    n=1000
    n =  int(color_var.get())
    a = float(from_entry.get())
    b = float(to_entry.get())
    function_dropdown2 = function_dropdown.get()
    print(function_dropdown2)

    if(function_dropdown2 == "прямокутників"):
        area = integrate_rectangular(a, b)

        print(f"Площадь под графиком: {area}")
    if(function_dropdown2 == "трапецій"):
        area = integrate_trapezoidal(a, b)

        print(f"Площадь под графиком: {area}")

    if(function_dropdown2 == "Монте-Карло"):
        area = integrate_monte_carlo(a, b)

        print(f"Площадь под графиком: {area}")

    display_results_in_table(a, b, area, function_dropdown2)

    # for i in range(n):
    #     if equation(a+i*dx)*equation(a+i*dx+dx)<0:
    #         answer = (a+i*dx+a+i*dx+dx)/2
    #         print(f"answ {answer},iterationEpoch {i}")
    #         break
    plot_graph(-10, 3)

# Create the main application window
app = tk.Tk()
app.title("Equation Plotter")

# Create and place widgets
from_label = tk.Label(app, text="From:")
from_label.grid(row=0, column=0)
from_entry = tk.Entry(app)
from_entry.grid(row=0, column=1)
from_entry.insert(-2, "-2")

to_label = tk.Label(app, text="To:")
to_label.grid(row=1, column=0)
to_entry = tk.Entry(app)
to_entry.grid(row=1, column=1)
to_entry.insert(-1, "-1")

plot_button = tk.Button(app, text="Plot", command=on_plot_button_click)
plot_button.grid(row=3, columnspan=2)

# Dropdown for selecting a function
function_label = tk.Label(app, text="метод:")
function_label.grid(row=4, column=0)
functions = ["прямокутників", "трапецій", "Монте-Карло"]
function_var = tk.StringVar(value=functions[0])
function_dropdown = ttk.Combobox(app, textvariable=function_var, values=functions)
function_dropdown.grid(row=4, column=1)

# Dropdown for selecting a color
color_label = tk.Label(app, text="N:")
color_label.grid(row=5, column=0)
colors = [10, 20, 50,100,1000]
color_var = tk.StringVar(value=colors[0])
color_dropdown = ttk.Combobox(app, textvariable=color_var, values=colors)
color_dropdown.grid(row=5, column=1)
table_window = tk.Toplevel()
table_window.title('Integration Results')
tree = ttk.Treeview(table_window, columns=('A', 'B', 'Result', 'type'), show='headings')
tree.heading('A', text='From (A)')
tree.heading('B', text='To (B)')
tree.heading('Result', text='Integration Result')
tree.heading('type', text='Integration type')

tree.pack(pady=20)

app.mainloop()


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

# In[77]:

import matplotlib.pyplot as plt
import seaborn as sns
import os
import gc
import sys
get_ipython().system('pip install tensorflow')
get_ipython().system('pip install keras')
from sklearn.model_selection import train_test_split
from tqdm import tqdm

import numpy as np
import pandas as pd
from keras import Sequential
from keras.callbacks import EarlyStopping
from keras.callbacks import ReduceLROnPlateau

from keras.optimizers import Adam,SGD
from keras.layers import Dense,Dropout,Flatten,BatchNormalization,Activation
from keras.layers import Lambda,Input,GlobalAveragePooling2D,BatchNormalization
from keras.utils import to_categorical
from tensorflow.keras.models import Model
from keras.preprocessing.image import load_img

# In[78]:

labels = pd.read_csv(r'C:\sem2\SDGP\DataSet\labels.csv')
labels.head()

# In[79]:

labels.describe()

# In[80]:

from IPython.display import display,Image
Image(r"C:\sem2\SDGP\DataSet\train\e08c321bfa4141ecfc3dc6c5488ec770.jpg")

# In[81]:

import os
if len(os.listdir(r'C:\sem2\SDGP\DataSet\train')) == len(labels['id']):
  print("Number of file matches of actual images!")
else:
  print("Number of file does not matches number of actual images!!")

# In[83]:

#Create list of alphabetically sorted labels.
classes = sorted(list(set(labels['breed'])))
n_classes = len(classes)
print('Total unique breed {}'.format(n_classes))

#Map each label string to an integer label.
class_to_num = dict(zip(classes, range(n_classes)))
class_to_num

# In[86]:

input_shape = (331,331,3)

def images_to_array(directory, label_dataframe, target_size = input_shape):

    image_labels = label_dataframe['breed']
    images = np.zeros([len(label_dataframe), target_size[0], target_size[1], target_size[2]],dtype=np.uint8) #as we have huge data and limited ram memory. uint8 takes less memory
    y = np.zeros([len(label_dataframe),1],dtype = np.uint8)

    for ix, image_name in enumerate(tqdm(label_dataframe['id'].values)):
        img_dir = os.path.join(directory, image_name + '.jpg')
        img = load_img(img_dir, target_size = target_size)
#         img = np.expand_dims(img, axis=0)
#         img = processed_image_resnet(img)
#         img = img/255
        images[ix]=img
#         images[ix] = img_to_array(img)
        del img

        dog_breed = image_labels[ix]
        y[ix] = class_to_num[dog_breed]

    y = to_categorical(y)

    return images,y

# In[87]:

import time
t = time.time()

X,y = images_to_array(r'C:\sem2\SDGP\DataSet\train', labels[:])

print('runtime in seconds: {}'.format(time.time() - t))

# In[88]:

n=25
plt.figure(figsize=(20,20))
for i in range (n):
    ax=plt.subplot(5,5,i+1)
    plt.title(classes[np.where(y[i]==1)[0][0]])
    plt.imshow(X[i].astype('int32'))

lrr= ReduceLROnPlateau(monitor='val_acc', factor=.01, patience=3, min_lr=1e-5,verbose = 1)

#Prepare call backs
EarlyStop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)

# Hyperparameters
batch_size= 128
epochs=50
learn_rate=.001
sgd=SGD(lr=learn_rate,momentum=.9,nesterov=False)
adam=Adam(lr=learn_rate, beta_1=0.9, beta_2=0.999, epsilon=None,  amsgrad=False)

#function to extract features from the dataset by a given pretrained model
img_size = (331,331,3)

def get_features(model_name, model_preprocessor, input_size, data):

    input_layer = Input(input_size)
    preprocessor = Lambda(model_preprocessor)(input_layer)
    base_model = model_name(weights='imagenet', include_top=False,
                            input_shape=input_size)(preprocessor)
    avg = GlobalAveragePooling2D()(base_model)
    feature_extractor = Model(inputs = input_layer, outputs = avg)

    #Extract feature.
    feature_maps = feature_extractor.predict(data, verbose=1)
    print('Feature maps shape: ', feature_maps.shape)
    return feature_maps

# Extract features using InceptionV3
from keras.applications.inception_v3 import InceptionV3, preprocess_input
inception_preprocessor = preprocess_input
inception_features = get_features(InceptionV3,
                                  inception_preprocessor,
                                  img_size, X)

import pickle
with open('InceptionV3_s01','wb') as f:
    pickle.dump(InceptionV3,f)

with open('inception_preprocessor_s01','wb') as f:
    pickle.dump(inception_preprocessor,f)

with open('inception_features_s01','wb') as f:
    pickle.dump(inception_features,f)

#read InceptionV3 model
with open('InceptionV3_s01','rb') as f:
    InceptionV3 = pickle.load(f)

with open('inception_preprocessor_s01','rb') as f:
    inception_preprocessor = pickle.load(f)

with open('inception_features_s01','rb') as f:
    inception_features = pickle.load(f)

# Extract features using Xception
from keras.applications.xception import Xception, preprocess_input
xception_preprocessor = preprocess_input
xception_features = get_features(Xception,
                                 xception_preprocessor,
                                 img_size, X)

with open('Xception_s01','wb') as f:
    pickle.dump(Xception,f)

with open('xception_preprocessor_s01','wb') as f:
    pickle.dump(xception_preprocessor,f)

with open('xception_features_s01','wb') as f:
    pickle.dump(xception_features,f)

with open('Xception_s01','rb') as f:
    Xception = pickle.load(f)

with open('xception_preprocessor_s01','rb') as f:
    xception_preprocessor = pickle.load(f)

with open('xception_features_s01','rb') as f:
    xception_features = pickle.load(f)

# Extract features using InceptionResNetV2
from keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input
inc_resnet_preprocessor = preprocess_input
inc_resnet_features = get_features(InceptionResNetV2,
                                   inc_resnet_preprocessor,
                                   img_size, X)

with open('InceptionResNetV2_s01','wb') as f:
    pickle.dump(InceptionResNetV2,f)

with open('inc_resnet_preprocessor_s01','wb') as f:
    pickle.dump(inc_resnet_preprocessor,f)

with open('inc_resnet_features_s01','wb') as f:
    pickle.dump(inc_resnet_features,f)

#read InceptionResNetV2 model
with open('InceptionResNetV2_s01','rb') as f:
    InceptionResNetV2 = pickle.load(f)

with open('inc_resnet_preprocessor_s01','rb') as f:
    inc_resnet_preprocessor = pickle.load(f)

with open('inc_resnet_features_s01','rb') as f:
    inc_resnet_features = pickle.load(f)

# Extract features using NASNetLarge
from keras.applications.nasnet import NASNetLarge, preprocess_input
nasnet_preprocessor = preprocess_input
nasnet_features = get_features(NASNetLarge,
                               nasnet_preprocessor,
                               img_size, X)

with open('NASNetLarge_s01','wb') as f:
    pickle.dump(NASNetLarge,f)

with open('nasnet_preprocessor_s01','wb') as f:
    pickle.dump(nasnet_preprocessor,f)

with open('nasnet_features_s01','wb') as f:
    pickle.dump(nasnet_features,f)

#read NASNetLarge model
with open('NASNetLarge_s01','rb') as f:
    NASNetLarge = pickle.load(f)

with open('nasnet_preprocessor_s01','rb') as f:
    nasnet_preprocessor = pickle.load(f)

with open('nasnet_features_s01','rb') as f:
    nasnet_features = pickle.load(f)

del X #to free up some ram memory
gc.collect()

#Creating final featuremap by combining all extracted features

final_features = np.concatenate([inception_features,
                                 xception_features,
                                 nasnet_features,
                                 inc_resnet_features,], axis=-1) #axis=-1 to concatinate horizontally

print('Final feature maps shape', final_features.shape)

#Prepare Deep net

model = Sequential()
# model.add(Dense(1028,input_shape=(final_features.shape[1],)))
model.add(Dropout(0.7,input_shape=(final_features.shape[1],)))
model.add(Dense(n_classes,activation= 'softmax'))

model.compile(optimizer=adam,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

#Training the model.
history = model.fit(final_features, y,
            batch_size=batch_size,
            epochs=epochs,
            validation_split=0.2,
            callbacks=[lrr,EarlyStop])

#deleting to free up ram memory

del inception_features
del xception_features
del nasnet_features
del inc_resnet_features
del final_features
gc.collect()

#Function to read images from test directory

def images_to_array_test(test_path, img_size = (331,331,3)):
    test_filenames = [test_path + fname for fname in os.listdir(test_path)]

    data_size = len(test_filenames)
    images = np.zeros([data_size, img_size[0], img_size[1], 3], dtype=np.uint8)

    for ix,img_dir in enumerate(tqdm(test_filenames)):
#         img_dir = os.path.join(directory, image_name + '.jpg')
        img = load_img(img_dir, target_size = img_size)
#         img = np.expand_dims(img, axis=0)
#         img = processed_image_resnet(img)
#         img = img/255
        images[ix]=img
#         images[ix] = img_to_array(img)
        del img
    print('Ouptut Data Size: ', images.shape)
    return images

test_data = images_to_array_test('/kaggle/input/dog-breed-identification/test/', img_size)

#Extract test data features.
def extact_features(data):
    inception_features = get_features(InceptionV3, inception_preprocessor, img_size, data)
    xception_features = get_features(Xception, xception_preprocessor, img_size, data)
    nasnet_features = get_features(NASNetLarge, nasnet_preprocessor, img_size, data)
    inc_resnet_features = get_features(InceptionResNetV2, inc_resnet_preprocessor, img_size, data)

    final_features = np.concatenate([inception_features,
                                     xception_features,
                                     nasnet_features,
                                     inc_resnet_features],axis=-1)

    print('Final feature maps shape', final_features.shape)

    #deleting to free up ram memory
    del inception_features
    del xception_features
    del nasnet_features
    del inc_resnet_features
    gc.collect()

    return final_features

test_features = extact_features(test_data)

del test_data
gc.collect()

#Predict test labels given test data features.

pred = model.predict(test_features)

# prediction
print(pred[0])
print(f"Max value (probability of prediction): {np.max(pred[0])}") # the max probability value predicted by the model
print(f"Sum: {np.sum(pred[0])}") # because we used softmax activation in our model, this will be close to 1
print(f"Max index: {np.argmax(pred[0])}") # the index of where the max value in predictions[0] occurs
print(f"Predicted label: {classes[np.argmax(pred[0])]}")

# Create pandas DataFrame with empty columns
preds_df = pd.DataFrame(columns=["id"] + list(classes))
preds_df.head()

# Append test image ID's to predictions DataFrame
test_path = "/kaggle/input/dog-breed-identification/test/"
preds_df["id"] = [os.path.splitext(path)[0] for path in os.listdir(test_path)]
preds_df.head()

preds_df.loc[:,list(classes)]= pred

preds_df.to_csv('submission.csv',index=None)
preds_df.head()

#Testing with Custom input
Image('../input/dog-breed-identification/train/0075dc49dab4024d12fafe67074d8a81.jpg')

#reading the image and converting it into an np array
img_g = load_img('../input/dog-breed-identification/train/0075dc49dab4024d12fafe67074d8a81.jpg',target_size = img_size)
img_g = np.expand_dims(img_g, axis=0)

#Predict test labels given test data features.
test_features = extact_features(img_g)
predg = model.predict(test_features)
print(f"Predicted label: {classes[np.argmax(predg[0])]}")
print(f"Probability of prediction): {round(np.max(predg[0])) * 100} %")


def is_member(val, a):
    if a.count(val) <= 1:
        return True
    else:
        return False

if __name__ == "__main__":
    value = input("Give any value:")
    storage = list(input("Give me a list"))
    print(is_member(value, storage))


import requests
import time
import datetime

def log_iot():
    addr = ('http://127.0.0.1:8080/iotnode/metric/'
            '{"type":"mean_luminance", "channels":["ch0"], "time_window":[60]}')
    fh = open('/ukko/scratch/jari/iot_log.csv', 'w')
    try:
        while True:
            value = requests.get(addr).json()[0]['return']
            now = datetime.datetime.now()
            print(value)
            fh.writelines('%d\t%d\t%0.2f\n' % (now.hour, now.minute, value))
            fh.flush()
            time.sleep(60)
    except KeyboardInterrupt:
        fh.close()
        print("\nBye!")

if __name__ == '__main__':
    log_iot()