from vcl3datlantis.models.PanoDR.layer import init_weights
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import functools
from vcl3datlantis.models.GatedConv.network_module import *
from vcl3datlantis.models.PanoDR.SEAN.normalization import *
from vcl3datlantis.models.PanoDR.SEAN.spade_arch import *
from vcl3datlantis.models.semantic_segmentation_models.unet.model import UNet

class GatedGenerator(nn.Module):
    def __init__(self, opt, device):
        super(GatedGenerator, self).__init__()
        self.opt = opt
        self.sem_layout = None
        self.soft_sem_layout = None
        if opt.structure_model == "unet":
           self.structure_model = UNet(n_channels = opt.in_layout_channels, n_classes = opt.num_classes)

        if opt.type_sp == 'SEAN':
            self.Zencoder = Zencoder(opt.in_SEAN_channels, opt.style_code_dim)
            self.spade_block_1 = SPADEResnetBlock(opt.latent_channels*4, opt.latent_channels*4, opt.in_spade_channels, device=device, Block_Name='up_0')
            self.spade_block_2 = SPADEResnetBlock(opt.latent_channels*2, opt.latent_channels*2, opt.in_spade_channels, device=device, Block_Name='up_1')

        self.refinement = nn.Sequential(
            # Surrounding Context Encoder
            GatedConv2d(opt.in_channels, opt.latent_channels, 5, 2, 2, pad_type = opt.pad_type, activation = opt.activation, norm='none'),
            GatedConv2d(opt.latent_channels, opt.latent_channels * 2, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 2, opt.latent_channels * 4, 3, 2, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 2, dilation = 2, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 4, dilation = 4, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 8, dilation = 8, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 16, dilation = 16, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation, norm = opt.norm),
            GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 4, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation),
        )
        #Structure-Aware Decoder
        self.refine_dec_1 = nn.Sequential(nn.Upsample(scale_factor=2),
        GatedConv2d(opt.latent_channels * 4, opt.latent_channels * 2, 3, 1, 1, activation = opt.activation, pad_type='zero', norm=opt.norm),
        )
        self.refine_dec_2 =  GatedConv2d(opt.latent_channels * 2, opt.latent_channels * 2, 3, 1, 1, pad_type = opt.pad_type, activation = opt.activation)
        self.refine_dec_3 = nn.Sequential(nn.Upsample(scale_factor=2),

        GatedConv2d(opt.latent_channels * 2, opt.latent_channels, 3, 1, 1, pad_type ='zero', activation = opt.activation),
        )
        self.refine_dec_4 = GatedConv2d(opt.latent_channels, opt.out_channels, 3, 1, 1, pad_type = opt.pad_type, norm='none', activation = 'tanh')

    def forward(self, img, inverse_mask, masked_input, device, use_sean):
        self.sem_layout = torch.zeros((self.opt.batch_size, self.opt.in_layout_channels, self.opt.height, self.opt.width)).float().to(device)
        first_out = masked_input
        structure_model_output = self.structure_model(masked_input).clone()

        if self.opt.use_argmax:
            self.soft_sem_layout = torch.softmax(structure_model_output, dim = 1)
            self.soft_sem_layout = torch.argmax(self.soft_sem_layout, dim=1, keepdim=True)
            self.soft_sem_layout = torch.clamp(self.soft_sem_layout, min=0, max=2)
            self.sem_layout.scatter_(1, self.soft_sem_layout, 1)

        else:
            self.sem_layout = torch.softmax(structure_model_output, dim = 1)

        second_out = self.refinement(torch.cat((masked_input, inverse_mask), 1))  #Enconder + bottleneck

        if self.opt.type_sp == 'SEAN':
            style_codes = self.Zencoder(input=img, segmap=self.sem_layout)
            z = self.spade_block_1(second_out, self.sem_layout, style_codes)
            second_out = self.refine_dec_1(z)
            second_out = self.refine_dec_2(second_out)
            z = self.spade_block_2(second_out, self.sem_layout, style_codes)
            second_out = self.refine_dec_3(z)
            second_out = self.refine_dec_4(second_out)
        else:
            second_out = self.refine_dec_1(second_out)
            second_out = self.refine_dec_2(second_out)
            second_out = self.refine_dec_3(second_out)
            second_out = self.refine_dec_4(second_out)
        second_out = torch.clamp(second_out, 0, 1)

        return first_out, second_out, structure_model_output, self.sem_layout

class Discriminator(nn.Module):
    def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.InstanceNorm2d, use_sigmoid=False, getIntermFeatures=True):
        super(Discriminator, self).__init__()
        self.n_layers = n_layers
        self.getIntermFeatures = getIntermFeatures

        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d

        kw = 4
        padw = 1
        sequence = [
            spectral_norm(nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),True),
            nn.LeakyReLU(0.2, True)
        ]

        nf_mult = 1
        nf_mult_prev = 1
        for n in range(1, n_layers):
            nf_mult_prev = nf_mult
            nf_mult = min(2**n, 8)
            sequence += [
                spectral_norm(nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
                          kernel_size=kw, stride=2, padding=padw, bias=use_bias),True),

                nn.LeakyReLU(0.2, True),
            ]

        nf_mult_prev = nf_mult
        nf_mult = min(2**n_layers, 8)
        sequence += [
            spectral_norm(nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
                                    kernel_size=kw, stride=2, padding=padw, bias=use_bias), True),

            nn.LeakyReLU(0.2, True)
        ]

        sequence += [spectral_norm(nn.Conv2d(ndf * nf_mult, 1,
                          kernel_size=kw, stride=2, padding=padw, bias=use_bias),True)]

        if getIntermFeatures:
            for n in range(len(sequence)):
                setattr(self, 'Dmodel'+str(n), nn.Sequential(sequence[n]))

        if use_sigmoid:
            sequence += [nn.Sigmoid()]

        self.model = nn.Sequential(*sequence)

    def forward(self, img, mask, getIntermFeatures):
        self.getIntermFeatures = getIntermFeatures
        input = torch.cat((img,mask), 1)

        if self.getIntermFeatures:
            _out = [input]
            for n in range(self.n_layers+6):
                model = getattr(self, 'Dmodel'+str(n)) #Dmodel
                _out.append(model(_out[-1]))
            #return _out[1:]
            return _out[9], _out[1:6]
        else:
            out = self.model(input)
            return out

def spectral_norm(module, mode=True):
    if mode:
        return nn.utils.spectral_norm(module)

    return module

def get_norm_layer(norm_type='instance'):
    """Return a normalization layer
    Parameters:
        norm_type (str) -- the name of the normalization layer: batch | instance | none
    For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
    For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.
    """
    if norm_type == 'batch':
        norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
    elif norm_type == 'instance':
        norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
    elif norm_type == 'none':
        def norm_layer(x): return Identity()
    else:
        raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
    return norm_layer


#https://www.codechef.com/problems/BSTOPS
# cook your dish here
class Node():
    def __init__(self,val,pos):
        self.val=val
        self.pos=pos
        self.left=None
        self.right=None
def get_min(node):
    while node.left:
        node=get_min(node.left)
    return node
def insert(parent,val,pos):
    if parent is None:
        parent=Node(val,pos)
        print(pos)
        return parent
    elif val<parent.val:
        parent.left=insert(parent.left,val,2*pos)
    else:
        parent.right=insert(parent.right, val, 2*pos + 1)
    return parent
def delete(parent,val,print_pos):
    if parent is None:
        return parent
    if parent.val>val:
        parent.left=delete(parent.left,val,print_pos)
    elif parent.val<val:
        parent.right=delete(parent.right,val,print_pos)
    else:
        if print_pos:
            print(parent.pos)
        if parent.left is not None and parent.right is not None:
            min_val = get_min(parent.right)
            parent.val = min_val.val
            parent.right = delete(parent.right, min_val.val, False)
        elif parent.left is None:
            parent = parent.right
        elif parent.right is None:
            parent = parent.left
    return parent
root=None
q=int(input())
for _ in range(q):
    i,n=input().split()
    if i=='i':
        root = insert(root,int(n), 1)
    else:
        root = delete(root,int(n), True)

'''

'''


import sys
import re
import os
import shutil
import subprocess

"""Copy Special exercise
"""

# +++your code here+++
# Write functions and modify main() to call them

def get_special_paths(dir):
    paths = []
    pattern = "\w+__\w+__.\w{3}"
    for root, dirs, files in os.walk(dir):
        for file in files:
            match = re.search(pattern, file)
            if match:
                paths.append(os.path.abspath(root + r'\\' + file))

    return paths

def copy_to(paths, dir):
    for file in paths:
        destFile = os.path.join(dir, os.path.basename(file))
        print('Copying %s to %s...' % (file, destFile))
        shutil.copy(file, destFile)

    return

def zip_to(paths, zippath):
    for file in paths:
        print('Adding %s to archive: %s' % (file, zippath))

    return

def main():
    # This basic command line argument parsing code is provided.
    # Add code to call your functions below.

    # Make a list of command line arguments, omitting the [0] element
    # which is the script itself.
    args = sys.argv[1:]
    if not args:
        print("usage: [--todir dir][--tozip zipfile] dir [dir ...]")
        sys.exit(1)

    # todir and tozip are either set from command line
    # or left as the empty string.
    # The args array is left just containing the dirs.
    todir = ''
    if args[0] == '--todir':
        todir = args[1]
        del args[0:2]

    tozip = ''
    if args[0] == '--tozip':
        tozip = args[1]
        del args[0:2]

    if len(args) == 0:
        print("error: must specify one or more dirs")
        sys.exit(1)

    # +++your code here+++
    # Call your functions
    special_paths = get_special_paths(args[0])

    if len(todir) > 0:
        copy_to(special_paths, todir)

    if len(tozip) > 0:
        zip_to(special_paths, tozip)

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plt
import numpy as np
import time
import gym
import os
from tqdm import tqdm

from constants import q_params, Q_TABLE_FILENAME

def train_agent(env, config):
    # Retrieve action space and observation space
    action_space_size = env.action_space.n
    state_space_size = env.observation_space.n

    # Construct a Q table
    q_table = np.zeros((state_space_size, action_space_size))

    # Extract Q learning parameters
    num_episodes = config['num_episodes']
    max_steps_per_episode = config['max_steps_per_episode']
    learning_rate = config['learning_rate']
    discount_rate = config['discount_rate']
    exploration_rate = config['exploration_rate']
    max_exploration_rate = config['max_exploration_rate']
    min_exploration_rate = config['min_exploration_rate']
    exploration_decay_rate = config['exploration_decay_rate']

    rewards_total_episodes = []

    for i_episode in tqdm(range(num_episodes)):
        state = env.reset()
        rewards_current_episode = 0

        for i_step in range(max_steps_per_episode):
            # Render the environment
            # env.render()
            exploration_rate_threshold = np.random.uniform()
            if exploration_rate_threshold > exploration_rate and ~np.all(q_table[state] == 0):
                action = np.argmax(q_table[state])
            else:
                action = env.action_space.sample()

            # Take action and get an observation and a reward
            new_state, reward, done, info = env.step(action)

            q_table[state, action] = q_table[state, action] * (1 - learning_rate) + \
                learning_rate * (reward + discount_rate * np.max(q_table[new_state, :]))

            state = new_state
            rewards_current_episode += reward

            if done:
                break

        # Exploration rate decay
        exploration_rate = min_exploration_rate + \
            (max_exploration_rate - min_exploration_rate) * np.exp(-exploration_decay_rate * i_episode)

        # Save the rewards of the current episode
        rewards_total_episodes.append(rewards_current_episode)

    return q_table, rewards_total_episodes

# Create the environment
env = gym.make('FrozenLake-v0')

# Train an agent
q_table, rewards = train_agent(env, q_params)
np.save(Q_TABLE_FILENAME, q_table)

# Print the rewards
rewards_per_thousand = np.split(np.array(rewards), q_params['num_episodes'] / 1000)
for i, r in enumerate(rewards_per_thousand):
    print(f'Average reward after {(i + 1) * 1000} episodes: {r.mean()}')

env.close()


import random
class Game:
    def __init__(self, player):
        self.player = player

    def game_start(self):
        while True:
            print("What do you want to do?")
            print("""
            1. Catch a Pymon
            2. View your status
            3. Quit the gam
            """)
            choice = int(input())

            if choice == 1:
                self.player.catch_pymon()

                if self.check_balls() == False:
                    break

            elif choice == 2:
                print(self.player)

            elif choice == 3:
                print("See you soon!")
                break
            else:
                print("Invalid input!")

    def check_balls(self):
        if self.player.pyballs == 0:
            print("Game Over! You've used all of your balls.")
            print("In this gameplay, you were able to catch {total} Pymons in total.".format(total = sum(self.player.pymons.values())))
            return False
        else:
            pass

class Player:
    def __init__(self, name):
        self.name = name
        self.pymons = {}
        self.pyballs = 20
        self.level = 1

    def __repr__(self):
        player_description = """
        {name} is a {level} level Pymon tamer, and owns {pyball} pyballs.
        Current Pymons are given below:
        """.format(name=self.name, level = self.level, pyball = self.pyballs)

        for pymon, number in self.pymons.items():
            player_description += "\n{pymon}: {number}\n".format(pymon=pymon, number = number)

        return player_description

    def catch_pymon(self):
        possibility_randomizer = random.randint(1,5)
        level_randomizer = random.randint(1, self.level + 2)
        possible_pymons = ["Gitmon","Atommon","Codecademymon","Bugmon"]
        pymon = Pymon(random.choice(possible_pymons), level_randomizer)
        print("{name} threw his ball to catch a {pymon}...".format(name = self.name, pymon = pymon ))
        print(pymon)
        if possibility_randomizer <= 2:
            print("You trapped a {type} inside your pyball.".format(type = pymon.type))

            if  pymon.level <= self.level:
                print("You caught a {type}!".format(type = pymon.type))
                if pymon.type in self.pymons:
                    self.pymons[pymon.type] += 1
                else:
                    self.pymons[pymon.type] = 1
                self.level += 1
            else:
                print("{type} was able to break out of your ball and escape! You better get stronger!".format(type = pymon.type))
                self.pyballs -= 1
                self.level += 1

        else:
            print("{type} dodged the ball and escaped! Good luck next time!".format(type = pymon.type))
            self.pyballs -= 1
        print("You have {pyball} pyballs left".format(pyball = self.pyballs))

class Pymon:
    def __init__(self, type, level):
        self.type = type
        self.level = level

    def __repr__(self):
        return "This Pymon is a {level} level {type}".format(level = self.level, type = self.type)


import torch
from torch.nn import functional as F
from torch import nn, autograd
from torch.autograd import Variable
import numpy as np
import random
from tqdm import tqdm
from torch.utils.data import Subset, ConcatDataset, DataLoader, TensorDataset
from torch import optim
import sys
from torchvision import transforms

def craft_adv(net, X, label, X_target, label_target, epsilon, num_steps, decay=1.0, rule='adaptive', random_init=False):
    if rule == 'adaptive':
        step_size = 2.*epsilon/num_steps
    elif rule == 'fixed':
        step_size = 0.1*epsilon

    net.eval()

    X_pgd = Variable(X.data, requires_grad=True)
    momentum = torch.zeros_like(X_pgd).detach().cuda()
    if random_init:
        random_noise = torch.FloatTensor(*X_pgd.shape).uniform_(-epsilon, epsilon).cuda()
        X_pgd = Variable(X_pgd.data + random_noise, requires_grad=True)

    for idx in range(num_steps):
        with torch.enable_grad():
            loss_target = F.cross_entropy(net(X_target), label_target)
            target_grads = torch.autograd.grad(loss_target, net.parameters(), retain_graph=True, create_graph=True)
            net.zero_grad()

            loss_posion = F.cross_entropy(net(X_pgd), label)
            poison_grads = torch.autograd.grad(loss_posion, net.parameters(), retain_graph=True, create_graph=True)
            net.zero_grad()

            grads = 0
            for poison_grad, target_grad in zip(poison_grads, target_grads):
                grads -= F.cosine_similarity(target_grad.flatten(), poison_grad.flatten(), dim=0)

            X_grad = torch.autograd.grad(grads, X_pgd)[0]

            X_grad = X_grad / torch.mean(torch.abs(X_grad), dim=(1,2,3), keepdim=True)

            X_grad = X_grad + momentum*decay
            momentum = X_grad
            eta = step_size * X_grad.data.sign()

            X_pgd = Variable(X_pgd.data - eta, requires_grad=True)
            eta = torch.clamp(X_pgd.data - X.data, -epsilon, epsilon)
            X_pgd = Variable(X.data + eta, requires_grad=True)
            X_pgd = Variable(torch.clamp(X_pgd, 0, 1.0), requires_grad=True)

    return X_pgd

def dataset_split(dataset, sample_size):
    index = list(range(len(dataset)))
    random.shuffle(index)
    rind = index[:sample_size]

    keep = list(set(index)-set(rind))

    dataset_k = Subset(dataset, keep)
    dataset_r = Subset(dataset, rind)

    return dataset_k, dataset_r

def attack_dataset(net, train_set, target_set, epsilon, num_steps, percentage, decay=1., rule='adaptive', device='cuda:0', random_init=True):
    sample_size = int(len(train_set)*(percentage*0.01))

    clean_set, poison_set = dataset_split(train_set, sample_size)

    poison_loader = DataLoader(poison_set, shuffle=True, num_workers=0, batch_size=500)
    target_loader = DataLoader(target_set, shuffle=True, num_workers=0, batch_size=500)

    poison_data = []
    poison_targets = []

    for _, (X, label) in tqdm(enumerate(poison_loader)):
        X_target, label_target = next(iter(target_loader))
        X_target = X_target.cuda()
        label_target = (label_target+torch.randint_like(label_target,1,10))%10
        label_target = label_target.cuda()

        X = X.cuda()
        label = label.cuda()

        X_adv = craft_adv(net, X, label, X_target, label_target, epsilon, num_steps, decay=decay, rule=rule, random_init=random_init)

        poison_data.append(X_adv.detach().cpu())
        poison_targets.append(label.detach().cpu())

    poison_data = torch.cat(poison_data, 0)

    poison_targets = torch.cat(poison_targets, 0)

    P = TensorDataset(poison_data, poison_targets)

    return clean_set+P


from typing import List

class Solution:
  def moveZeroes(self, nums: List[int]) -> None:
    """
    Do not return anything, modify nums in-place instead.
    """
    i = 0
    j = 1

    while i <= len(nums) - 1 and j < len(nums):
      if j <= i:
        j = i + 1

      while j < len(nums) and nums[j] == 0:
        j += 1

      if nums[i] == 0 and j < len(nums):
        nums[i] = nums[j]
        nums[j] = 0
      i += 1

sol = Solution()
sol.moveZeroes([4,2,4,0,0,3,0,5,1,0])


def rot13(input_strng):
    rotted = ''
    for i in input_strng:
        ch = ord(i)
        if ch >= ord('a') and ch <= ord('z'):
            if ch > ord('m'):
                ch -= 13
            else:
                ch += 13
        elif ch >= ord('A') and ch <= ord('Z'):
            if ch > ord('M'):
                ch -= 13
            else:
                ch += 13
        rotted += chr(ch)
    return rotted

if __name__ == '__main__':
    assert rot13(rot13('ryan was here 2day')) == "ryan was here 2day"
    assert (rot13("Zntargvp sebz bhgfvqr arne pbeare")) == "Magnetic from outside near corner"


import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import utils.database as database
import base64

def download_button(object_to_download, download_filename):
    try:
        # some strings <-> bytes conversions necessary here
        b64 = base64.b64encode(object_to_download.encode()).decode()

    except AttributeError as e:
        b64 = base64.b64encode(object_to_download).decode()

    dl_link = f"""
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
    $('<a href="data:text/csv;base64,{b64}" download="{download_filename}">')[0].click()
    </script>
    </head>
    </html>
    """
    return dl_link

def create_page():
    with st.form(key="dont_refresh", clear_on_submit=False):
        event_to_download = st.number_input("Enter event ID", value=1)
        submitted = st.form_submit_button("Download")

        if submitted:
            create_download(event_to_download)

def create_download(event_id = None):
    if event_id == None:
        event_id = st.experimental_get_query_params()["event"][0]
        if not event_id.isnumeric():
            return

    conn = database.get_connection()

    # Search for the specific event.
    df = pd.read_sql(f"SELECT * FROM event WHERE event_id={event_id} AND pdf IS NOT NULL", conn)

    if df.size == 0:
        st.write(f"A summary of the event {event_id} does not yet exist.")
        return

    pdf_bytes = df.iloc[0]["pdf"]

    components.html(
        download_button(pdf_bytes, f"Summary - event {event_id}.pdf"),
        height=0,
    )

    st.write("Download is finished.")


#!/usr/bin/env python

# This script looks into a directory and checks if
# some files have changed since last execution

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, time
import pickle
import subprocess
from datetime import datetime
import json

dirPath = "/dir_monitoring/to_monitor"
savePath = "/dir_monitoring/tmp/files.pkl"
indexFile = "/dir_monitoring/htdocs/index.json"

time_to_sleep = 60 # Time in seconds between two executions

def save_object(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output)

# Make a system call
def system_call(command, from_docker=True):
	if from_docker:
		command = "docker exec ipfs-container " + command
	print("Executing: ", command)
	p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
	return p.stdout.read()

print("--------------------------")
print("Welcome to IPFS monitoring")
print("--------------------------")

# Wait for other containers to start
time.sleep(10)

##############################
# Load current IPFS state
##############################
try:
	with open(savePath, 'rb') as input:
	    currentIPFSState = pickle.load(input)
except FileNotFoundError:
	# First launch: initialize currentIPFSState to empty dict
	currentIPFSState = {}

# Main loop
while True:

	print("--------------------------------------")
	print("IPFS monitoring")
	print("Looking for modifications in directory")

	##############################
	# Scan monitored directory
	##############################

	# get all entries in the directory w/ stats
	entries = ((os.path.join(dirPath, fn), fn) for fn in os.listdir(dirPath))
	entries = ((os.stat(path), path, fn) for path, fn in entries)

	# leave only regular files, insert creation date
	entries = [(stat[ST_CTIME], path, fn)
	           for stat, path, fn in entries if S_ISREG(stat[ST_MODE])]

	###############################
	# Compare curent IPFS state
	# with directory state
	###############################

	# Select IPFS files that have been modified or removed
	filesToRemove = [mHash for mHash in currentIPFSState if currentIPFSState[mHash] not in entries]

	# Select IPFS files that have been modified or removed
	filesToAdd = [f for f in entries if f not in currentIPFSState.values()]

	################################
	# Record changes in IPFS
	################################

	# Remove old files from IPFS
	print ("Removing files from IPFS...")
	count = 0
	for mHash in filesToRemove:
		# This test protects again empty hash which may cause a freeze in system_call
		if mHash != "":
			count += 1
			# Remove file from ipfs
			print("Removing file from IPFS: ", mHash, currentIPFSState[mHash][1])
			response = system_call("ipfs pin rm " + mHash)
			print (response.strip().decode('UTF-8'))
		# Remove file from dictionary
		currentIPFSState.pop(mHash, None)

	print("%i files removed." % count)

	# Add new files to IPFS
	print ("Adding files to IPFS...")
	count = 0
	for f in filesToAdd:
		count += 1
		# Add file to ipfs
		print("Adding file: ", f[1])
		mHash = system_call("ipfs add -q \"" + f[1] + "\"")
		mHash = mHash.strip().decode('UTF-8')
		print (mHash, f)
		currentIPFSState[mHash] = f

	print ("%i files added." % count)

	#################################
	# Save new IPFS state in file
	#################################

	print ("Saving new state...")
	save_object(currentIPFSState, savePath)

	######################################
	# Create index file with new state
	######################################

	print ("Saving index file: %s" % indexFile)
	index = [{	'hash': mHash,
				'file': currentIPFSState[mHash][2],
				'uploaded_at': datetime.utcfromtimestamp(currentIPFSState[mHash][0]).strftime('%Y-%m-%dT%H:%M:%SZ')}
				for mHash in currentIPFSState]

	with open(indexFile, 'w') as outfile:
	    json.dump(index, outfile)

	print ("IPFS monitoring going to sleep for %d seconds" % time_to_sleep)
	print ("-----------------------------------------------------")

	#####################################
	# Sleep for some time
	#####################################
	time.sleep(time_to_sleep)


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 09:45:12 2021

@author: Administrator
"""

from random import randint
data=[]
head=0
tmp=randint(95,100)
data.append([tmp,-1])
for i in range(1,20):
    tmp=tmp-randint(0,5)
    data.append([tmp,-1])
    data[i-1][1]=i
print(data)
n=int(input("请输入："))
flag=False
if data[0][0]==n:
    head=data[head][1]
    print("已找到n的位置：")
    print(0)
p=head
while(p!=-1):
    q=data[p][1]
    if data[q][0]==n:
        print("已找到n的位置：")
        print(q)
        flag=True
        data[p][1]=data[q][1]
    p=q
if flag==False:
    print("没有找到")
a=head
while data[a][1]!=-1:
    print(data[a],end=" ")
    a=data[a][1]
print(data[a])

高二上/链表删除数据.py


#%%
from sklearn import linear_model, decomposition, ensemble, preprocessing, isotonic, metrics
from sklearn.ensemble import RandomForestClassifier as RF
import sklearn.metrics as me
import pandas as pd
import sys,os
import numpy as np
import logging
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontManager, FontProperties
import pickle
import seaborn as sns
from sklearn.preprocessing import Binarizer

def onehot_to_category(onehot):
    b = np.array([[0], [1], [2],[3],[4],[5]])
    return np.dot(onehot,b).flatten()

def load_X_train():
    path = sys.path[0]
    today_all = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-07-04.xlsx")
    '''
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-07-03.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-07-02.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-29.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-28.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-27.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-26.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-25.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-22.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-21.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-20.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-19.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-15.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-14.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-13.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all_prev = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square_2018-06-12.xlsx")
    today_all = today_all.append(today_all_prev)
    today_all = today_all[today_all.industry == '普钢']
    #today_all = today_all[['trade', 'per', 'mktcap', 'nmc', 'pe', 'pb', 'gpr', 'npr',  \
    #                        'holders', 'roe/pb', 'roe_mean', '10days_percentage']]
    '''
    today_all = today_all[['trade', 'turnoverratio', 'per', 'mktcap', 'nmc', 'industry', 'area', 'pe', 'pb', 'gpr', 'npr',  \
                            'holders', 'roe/pb', 'roe_mean', '10days_percentage']]

    return today_all

def feature_engineering(df):
    print(df.info())

    # check the null values
    print('Total of null values:  ' + str(df.isnull().values.sum()))
    print('Column-wse distribution of null values: \n' + str(df.isnull().sum()))

    # boxplot the data
    font_small = FontProperties(fname='/Library/Fonts/Songti.ttc',size=9)
    font_medium = FontProperties(fname='/Library/Fonts/Songti.ttc',size=10)
    font_large=FontProperties(fname='/Library/Fonts/Songti.ttc', size=12)
    font_xlarge=FontProperties(fname='/Library/Fonts/Songti.ttc', size=14)

    plt.style.use('ggplot')
    fig_train_data, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 15))
    fig_train_data.suptitle('Train Data - boxplot',fontproperties=font_xlarge)

    axes = df.boxplot()
    xlabels = axes.get_xticklabels()
    for xlabel in xlabels:
        xlabel.set_rotation(90)
        xlabel.set_fontproperties(font_small)
    ylabels = axes.get_yticklabels()
    for ylabel in ylabels:
        ylabel.set_fontproperties(font_small)

    plt.draw()

    # value count - frequency distribution
    print('Total of categories in - industry: ')
    print(df['industry'].value_counts().count())
    print('frequency distribution of each category: ')
    print(df['industry'].value_counts())

    print('Total of categories in - area: ')
    print(df['area'].value_counts().count())
    print(df['area'].value_counts())

    '''
    industry_count = df['industry'].value_counts()
    sns.set(style="darkgrid")
    sns.barplot(industry_count.index, industry_count.values, alpha=0.9)
    plt.title('Frequency Distribution of Industry')
    plt.ylabel('Number of Occurrences', fontsize=12)
    plt.xlabel('Industry', fontsize=12)
    plt.draw()
    '''

    ################ procedure to clean the data#####################
    # fillna?
    # dropna?
    # Encoding Categorical Data:
    # Replacing values
    #           (replace with int only, weighting a value improperly?)
    # Encoding labels
    #           (replace with int only, weighting a value improperly?)
    # One-Hot encoding
    #           (The basic strategy is to convert each category value
    #           into a new column and assign a 1 or 0 (True/False) value
    #           to the column, benefit of not weighting a value improperly.)
    # Binary encoding
    #           the categories are encoded as ordinal,
    #           then those integers are converted into binary code,
    #           then the digits from that binary string are split into separate columns.
    # Backward difference encoding
    #           the mean of the dependent variable for a level
    #           is compared with the mean of the dependent variable for the prior level.
    #           This type of coding may be useful for a nominal or an ordinal variable.
    #           http://www.statsmodels.org/dev/contrasts.html
    # Miscellaneous features
    #           split these ranges into two separate columns
    #           or replace them with some measure like the mean of that range.
    # PCA 降维
    ################################################################################

    #import pdb
    #pdb.set_trace()

    '''
    # Replacing values
    df_lc = df.copy()
    df_lc['industry'] = df_lc['industry'].astype('category')
    df_lc['area'] = df_lc['area'].astype('category')
    print(df_lc.dtypes)

    labels = df_lc['industry'].astype('category').cat.categories.tolist()
    replace_map_comp = {'industry' : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}}
    print(replace_map_comp)

    df_replace = df_lc.copy()
    df_replace.replace(replace_map_comp, inplace=True)
    print(df_replace)

    # Encoding labels
    from sklearn.preprocessing import LabelEncoder
    lb_make = LabelEncoder()
    df_replace['area_code'] = lb_make.fit_transform(df_replace['area'])
    print(df_replace)
    '''

    # One-Hot encoding

    cat_df_onehot = df.copy()
    cat_df_onehot = pd.get_dummies(cat_df_onehot, columns=['industry'], prefix = ['industry'])
    cat_df_onehot = pd.get_dummies(cat_df_onehot, columns=['area'], prefix = ['area'])
    #print(cat_df_onehot)

    df = cat_df_onehot

    '''
    # Binary encoding
    cat_df_ce = cat_df_onehot.copy()
    import category_encoders as ce

    encoder = ce.BinaryEncoder(cols=['area'])
    df_binary = encoder.fit_transform(cat_df_ce)

    print(df_binary.head())

    # Backward difference encoding
    cat_df_bd = df.copy()
    encoder = ce.BackwardDifferenceEncoder(cols=['area'])
    df_bd = encoder.fit_transform(cat_df_bd)

    print(df_bd.head())

    # Miscellaneous features
    cat_df_mis = df.copy()
    dummy_df_age = pd.DataFrame({'age': ['0-20', '20-40', '40-60','60-80']})
    dummy_df_age['start'], dummy_df_age['end'] = zip(*dummy_df_age['age'].map(lambda x: x.split('-')))

    dummy_df_age.head()

    '''
    df = df.dropna()
    '''
    # PCA 检测, can only detect for numeric fields
    df = df.dropna()
    pca_df = df.drop(['10days_percentage'], inplace=False, axis=1, errors='ignore')

    sc = preprocessing.StandardScaler()
    X_train_std = sc.fit_transform(pca_df)
    print(pd.DataFrame(X_train_std))
    pca = decomposition.PCA(n_components = 10)
    pca.fit(X_train_std)
    print (pca.explained_variance_ratio_)
    print (pca.explained_variance_)
    #print (pca.components_)
    #pandas.DataFrame(pca.transform(df),
    # columns=['PCA%i' % i for i in range(n_components)],
    # index=df.index)
    df = pd.DataFrame(pca.fit_transform(X_train_std), \
        columns=['PCA%i' % i for i in range(2)], \
        index=X_train_std.index)

    print(df)
    '''
    ################################################################################

    # Y binary classification
    #bound = np.nanpercentile(cat_df_onehot['10days_percentage'], 20)

    #test = pd.DataFrame(Binarizer(threshold=0).fit_transform(df))
    #print(test)

    bound = 0
    df.loc[(df['10days_percentage'] > bound), 'Y_bin'] = 1
    df.loc[(df['10days_percentage'] <= bound), 'Y_bin'] = -1

    return df

def RF_train(df):

    # train dataframe split
    #logging.info(today_all)
    X = df.copy()
    Y = X.pop('Y_bin')
    X.pop('10days_percentage')
    train_size_perc = 0.8
    train_size = np.int16(np.round(train_size_perc * X.shape[0]))
    logging.info(train_size)
    X_train, Y_train = X.iloc[:train_size, :], Y.iloc[:train_size]    #?
    X_test, Y_test = X.iloc[train_size:,:], Y.iloc[train_size:]    #?
    # Random Forest train
    scaler = preprocessing.MinMaxScaler()
    X_train_trans = scaler.fit_transform(X_train)
    model = RF(n_estimators=100).fit(X_train_trans, Y_train)

    # save model file
    path = sys.path[0]
    pkl_filename = path + '/' + "RF_model.pkl"
    print(pkl_filename)
    with open(pkl_filename, 'wb') as file:
        pickle.dump(model, file)
        file.close()

    # validate the model
    Y_pred = model.predict(X_test)
    print (me.classification_report(Y_test, Y_pred))

    feature_importances = pd.Series(model.feature_importances_, index=X.columns)
    print(feature_importances)

    # plot show
    feature_importances.sort_values(ascending=False, inplace=True)

    font_small = FontProperties(fname='/Library/Fonts/Songti.ttc',size=9)
    font_medium = FontProperties(fname='/Library/Fonts/Songti.ttc',size=10)
    font_large=FontProperties(fname='/Library/Fonts/Songti.ttc', size=12)
    font_xlarge=FontProperties(fname='/Library/Fonts/Songti.ttc', size=14)

    plt.style.use('ggplot')
    fig_feature_importance, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 10))
    fig_feature_importance.suptitle('Feature Importances',fontproperties=font_xlarge)

    ax = feature_importances.plot(kind='bar')
    ax.set_xlabel('Features',fontproperties=font_medium)
    ax.set_ylabel('Importance (Gini Coefficient)',fontproperties=font_medium)

    xlabels = ax.get_xticklabels()
    for xlabel in xlabels:
        xlabel.set_fontproperties(font_small)
    ylabels = ax.get_yticklabels()
    for ylabel in ylabels:
        ylabel.set_fontproperties(font_small)

    plt.show()
    return

def load_X_test():
    df = pd.read_excel(io="/Users/huiyang/Documents/SPSS modeler/复盘/today_all_R_square.xlsx")
    return df

def RF_prediction(X, savedModel):
    ###########################predict#############################
    path = sys.path[0]
    pkl_filename = path + '/' + savedModel
    # Load from file
    with open(pkl_filename, 'rb') as file:
        model = pickle.load(file)
    # RF prediction
    Y_pred = model.predict(X)
    #print (me.classification_report(X_test, Y_pred))

    feature_importances = pd.Series(model.feature_importances_, index=X.columns)
    print(feature_importances)

    return Y_pred

if __name__ == '__main__':
    logging.basicConfig(level=logging.ERROR,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

    X_train = load_X_train()

    train_df = feature_engineering(df=X_train)

    #####################################
    # for train and generate model
    RF_train(df=train_df)
    #for load model
    #model = load_model()
    #####################################

    #X_test = load_X_test()
    #RF_prediction(X=X_test, savedModel='RF_model.pkl')
    plt.show(block=False)


import random
import subprocess

# Función para generar una MAC aleatoria
def random_mac():
    mac = [ 0x00, 0x16, 0x3e,
            random.randint(0x00, 0x7f),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff) ]
    return ':'.join(map(lambda x: "%02x" % x, mac))

# Función para generar una MAC que parezca que proviene de un dispositivo Apple
def apple_mac():
    mac = [ 0x00, 0x05, 0x5d,
            random.randint(0x00, 0x7f),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff) ]
    return ':'.join(map(lambda x: "%02x" % x, mac))

# Función para obtener las interfaces de red disponibles
def get_interfaces():
    result = subprocess.run(["ifconfig", "-s"], capture_output=True, text=True)
    if result.returncode != 0:
        print("Error al obtener las interfaces de red disponibles.")
        return []
    output = result.stdout.strip().split('\n')[1:]
    interfaces = [line.split()[0] for line in output]
    return interfaces

# Pide al usuario que elija una opción
print("¿Qué tipo de MAC deseas usar?")
print("1. Aleatoria")
print("2. Apple")
print("3. Ingresar manualmente")
option = input("Ingresa el número de la opción que deseas: ")

# Genera la MAC según la opción elegida
if option == "1":
    mac = random_mac()
elif option == "2":
    mac = apple_mac()
elif option == "3":
    mac = input("Ingresa la dirección MAC que deseas usar: ")
else:
    print("Opción inválida.")
    exit()

# Imprime la MAC elegida
print("La MAC elegida es:", mac)

# Obtiene las interfaces de red disponibles
interfaces = get_interfaces()

# Si no hay interfaces disponibles, muestra un mensaje y sale del programa
if not interfaces:
    print("No se encontraron interfaces de red disponibles.")
    exit()

# Muestra las interfaces de red disponibles
print("Interfaces de red disponibles:")
for i, interface in enumerate(interfaces):
    print(f"{i+1}. {interface}")

# Pide al usuario que elija una interfaz de red
selection = input("Ingresa el número de la interfaz de red que deseas usar: ")
try:
    index = int(selection) - 1
    interface = interfaces[index]
except (ValueError, IndexError):
    print("Selección inválida.")
    exit()

# Comando para desactivar la interfaz de red
cmd = "ifconfig " + interface + " down"
subprocess.call(cmd, shell=True)

# Comando para cambiar la MAC
cmd = "ifconfig " + interface + " hw ether " + mac

# Ejecuta el comando
subprocess.call(cmd, shell=True)

# Comando para activar la interfaz de red
cmd = "ifconfig " + interface + " up"
subprocess.call(cmd, shell=True)


# 几种简单的边缘提取方法
import cv2
import matplotlib.pyplot as plt
import numpy as np
from general import extract_edge, fuse_edge_x_y, thr_process

threshold = None

img_path = "./images/lena.bmp"
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 简单梯度算子
kernel_h = np.array([[-1,1]], dtype=np.float32)
kernel_v = np.array([[-1],
                     [1]], dtype=np.float32)

edge_1 = extract_edge(img, kernel_h, kernel_v, threshold=threshold)

# Roberts梯度算子
kernel_h = np.array([
    [1, 0],
    [0, -1],
], dtype=np.float32)
kernel_v = np.array([
    [0, 1],
    [-1, 0],
], dtype=np.float32)
edge_roberts = extract_edge(img, kernel_h, kernel_v, threshold=threshold)

# Prewitt梯度算子
kernel_h = np.array([
    [-1, 0, 1],
    [-1, 0, 1],
    [-1, 0, 1],
], dtype=np.float32)
kernel_v = np.array([
    [1, 1, 1],
    [0, 0, 0],
    [-1, -1, -1],
], dtype=np.float32)
edge_prewitt = extract_edge(img, kernel_h, kernel_v, threshold=threshold)

# Sobel梯度算子
kernel_h = np.array([
    [-1, 0, 1],
    [-2, 0, 2],
    [-1, 0, 1],
], dtype=np.float32)
kernel_v = np.array([
    [1, 2, 1],
    [0, 0, 0],
    [-1, -2, -1],
], dtype=np.float32)
edge_sobel = extract_edge(img, kernel_h, kernel_v, threshold=threshold)

# # # 沿着x/y两个方向的梯度
# edge_sobel = cv2.Sobel(img, cv2.CV_32F, 1, 1)
# # # 沿x方向的边缘检测
# # sobelx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
# # # 沿y方向的边缘检测
# # sobely = cv2.Sobel(img, cv2.CV_32F, 0, 1)
# # edge_sobel = fuse_edge_x_y(sobelx, sobely)
# edge_sobel = thr_process(edge_sobel, threshold=threshold)

fig, ax = plt.subplots(2,2)
ax = ax.ravel()

ax[0].imshow(edge_1, cmap='gray')
ax[0].axis("off")
ax[0].set_title("简单梯度算子")

ax[1].imshow(edge_roberts, cmap='gray')
ax[1].axis("off")
ax[1].set_title("roberts")

ax[2].imshow(edge_prewitt, cmap='gray')
ax[2].axis("off")
ax[2].set_title("prewitt")

ax[3].imshow(edge_sobel, cmap='gray')
ax[3].axis("off")
ax[3].set_title("Sobel")

#解决中文显示问题
# plt.rcParams['font.sans-serif']=['SimHei'] # 设置字体
# plt.rcParams['axes.unicode_minus'] = False # 使坐标轴刻度表签正常显示正负号
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

plt.show()


#Creating Generator iterators
def sequence_generator(sequence):
    for item in sequence:
        yield item

sequence_generator([1,2,3,4])

for number in sequence_generator([1,2,3,4]):
    print(number)

#Using gen expressions to create iterators
[item for item in [3,4,5,6]]#list comprehension

(item for item in[3,2,4,5,7])#generator expression

generator_expressiom=(item for item in[6,8,9,5])
for item in generator_expressiom:
    print(item)

#Different types of of generator itearators
def square_generator(sequence):
    for item in sequence:
        yield item**2

for square in square_generator([10,23,43,54,95]):
    print(square)

#fibonacci
def fibonacci_generator(stop=10):
    current_fib, next_fib=0,1
    for _ in range(0,stop):
        fib_number=current_fib
        current_fib, next_fib=(
            next_fib, current_fib+next_fib
        )
        yield fib_number

li=list(fibonacci_generator())
print(li)

print(list(fibonacci_generator(20)))

# when the loop finishes, the generator iterator automatically raises a StopIteration exception
def fibonacci_generator(stop=10):
    current_fib, next_fib = 0, 1
    index = 0
    while True:
        if index == stop:
            return
        index += 1
        fib_number = current_fib
        current_fib, next_fib = next_fib, current_fib + next_fib
        yield fib_number

print(fibonacci_generator(9))


import os
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv3D, LSTM, Dense, Dropout, Bidirectional, MaxPool3D, Activation, Reshape, SpatialDropout3D, BatchNormalization, TimeDistributed, Flatten

script_dir = os.path.dirname(os.path.abspath(__file__))
def load_model() -> Sequential:
    model = Sequential()
    # Add a 3D convolutional layer with 128 filters, a kernel size of (3, 3, 3), and input shape of (75, 46, 140, 1)
    # The 'padding' parameter is set to 'same' to ensure that the spatial dimensions of the output remain the same as the input.
    model.add(Conv3D(128, 3, input_shape=(75,46,140,1), padding='same'))
    # Add a ReLU activation function to introduce non-linearity after the convolutional layer.
    model.add(Activation('relu'))
    # Add a 3D max pooling layer with a pool size of (1, 2, 2)
    # This layer reduces the spatial dimensions by taking the maximum value over a 1x2x2 region.
    model.add(MaxPool3D((1,2,2)))

    model.add(Conv3D(256, 3, padding='same'))
    model.add(Activation('relu'))
    model.add(MaxPool3D((1,2,2)))

    model.add(Conv3D(75, 3, padding='same'))
    model.add(Activation('relu'))
    model.add(MaxPool3D((1,2,2)))

    model.add(TimeDistributed(Flatten()))

    model.add(Bidirectional(LSTM(128, kernel_initializer='Orthogonal', return_sequences=True)))
    model.add(Dropout(.5))

    model.add(Bidirectional(LSTM(128, kernel_initializer='Orthogonal', return_sequences=True)))
    model.add(Dropout(.5))

    model.add(Dense(41, kernel_initializer='he_normal', activation='softmax'))

    model.load_weights(os.path.join('..','models','checkpoint'))

    return model


from collections import deque
import math

# The graph: children and costs
G = {}
G["B"] = {"L":5, "P":0}
G["P"] = {"D":35, "G":30}
G["D"] = {"K":10}
G["G"] = {"K":20}
G["L"] = {"G":15, "D":20}
G["K"] = {}

start = "B"
finish = "K"

def get_smallest_cost_node(C, processed):
	smallest_cost_node = None
	smallest_cost = math.inf

	for node in C:
		if (not node in processed) and (C[node] < smallest_cost):
			smallest_cost_node = node
			smallest_cost = C[node]

	return smallest_cost_node

def dijkstra(G, start, finish):
	# Allocate and initialise costs of nodes:
	C = {}
	for node in G.keys():
		if node == start:
			C[node] = 0
		else:
			C[node] = math.inf

	# Allocate parents of nodes:
	P = {}
	P[start] = {}
	processed = []

	# Algorithm
	node = start
	while node is not None:
		processed.append(node)
		neighbours = G[node].keys()
		for neighbour in neighbours:
			if G[node][neighbour] + C[node] < C[neighbour]:  # Calculate the costs for neighbours
				C[neighbour] = G[node][neighbour] + C[node]	 # If the path through this node is shorter, update the cost
				P[neighbour] = node

		node = get_smallest_cost_node(C, processed)

	# Get resulting path
	path = [finish]
	while P[path[-1]]:
		path.append(P[path[-1]])

	return path[::-1]

print(dijkstra(G, start, finish))


import pickle
from fastsklearnfeature.candidates.CandidateFeature import CandidateFeature
from typing import List, Dict, Set
import copy
from fastsklearnfeature.transformations.Transformation import Transformation
from fastsklearnfeature.transformations.UnaryTransformation import UnaryTransformation
from fastsklearnfeature.transformations.IdentityTransformation import IdentityTransformation
from fastsklearnfeature.candidates.RawFeature import RawFeature
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

#path = '/home/felix/phd/fastfeatures/results/heart_new_all'
#path = '/home/felix/phd/fastfeatures/results/heart_small'
#path = '/home/felix/phd/fastfeatures/results/transfusion'
path = '/home/felix/phd/fastfeatures/results/credit'

load_combination = False

cost_2_raw_features: Dict[int, List[RawFeature]] = pickle.load(open(path + "/data_raw.p", "rb"))
cost_2_unary_transformed: Dict[int, List[CandidateFeature]] = pickle.load(open(path + "/data_unary.p", "rb"))
cost_2_binary_transformed: Dict[int, List[CandidateFeature]] = pickle.load(open(path + "/data_binary.p", "rb"))
if load_combination:
	cost_2_combination: Dict[int, List[CandidateFeature]] = pickle.load(open(path + "/data_combination.p", "rb"))
cost_2_dropped_evaluated_candidates: Dict[int, List[CandidateFeature]] = pickle.load(open(path + "/data_dropped.p", "rb"))

#build tree from logged data

#get last layer:
all_layers = list(cost_2_raw_features.keys())
all_layers.extend(list(cost_2_unary_transformed.keys()))
all_layers.extend(list(cost_2_binary_transformed.keys()))
if load_combination:
	all_layers.extend(list(cost_2_combination.keys()))
all_layers.extend(list(cost_2_dropped_evaluated_candidates.keys()))

last_layer = max(all_layers)
print('last layer: ' + str(last_layer))

#create string2candidate dictionary
def extend_string2candidate(my_dict: Dict[int, List[CandidateFeature]], string2candidate: Dict[str, CandidateFeature], last_layer):
	for c in range(0, last_layer + 1):
		if c in my_dict:
			for v in my_dict[c]:
				string2candidate[str(v)] = v

string2candidate: Dict[str, CandidateFeature] = {}
extend_string2candidate(cost_2_raw_features, string2candidate, last_layer)
extend_string2candidate(cost_2_unary_transformed, string2candidate, last_layer)
extend_string2candidate(cost_2_binary_transformed, string2candidate, last_layer)
if load_combination:
	extend_string2candidate(cost_2_combination, string2candidate, last_layer)
extend_string2candidate(cost_2_dropped_evaluated_candidates, string2candidate, last_layer)

#print('(nanstd(num_dependents) GroupyBy purpose)')
#print(string2candidate['(nanstd(num_dependents) GroupyBy purpose)'].runtime_properties['score'])

#find features that destroy monotonicity
count_violations = 0

count_violations_per_transformation = {}

for c in string2candidate.values():
	if c.get_complexity() >= 3:
		#print('' + str(c))
		parents = list(c.parents)
		#print('\t' + str(parents))
		id = np.argmax(np.array([p.runtime_properties['score']for p in parents]))
		if parents[id].runtime_properties['score'] < c.runtime_properties['score']:
			parent_parents = list(parents[id].parents)
			if len(parent_parents) >= 1:
				#print('\t\t' + str(parent_parents))
				new_id = np.argmax(np.array([p.runtime_properties['score'] for p in parent_parents]))
				if parent_parents[new_id].runtime_properties['score'] < c.runtime_properties['score'] and parent_parents[new_id].runtime_properties['score'] > parents[id].runtime_properties['score']:
					print(c)
					print(str(c) + ': ' + str(c.runtime_properties['score']))
					print('\t' + str(parents[id]) + ': ' + str(parents[id].runtime_properties['score']))
					print('\t\t' + str(parent_parents[new_id]) + ': ' + str(parent_parents[new_id].runtime_properties['score']))
					print('')
					count_violations +=1
					if not c.transformation.name in count_violations_per_transformation:
						count_violations_per_transformation[c.transformation.name] = 0
					count_violations_per_transformation[c.transformation.name] += 1

print(count_violations_per_transformation)

print("violations: " + str(count_violations) + " of " + str(len(string2candidate)) + ' representations')


import numpy as np
import streamlit as st
import tensorflow as tf
from PIL import Image, ImageOps
import PIL

"""## Loading Trained Model"""
# Recreate the exact same model, including its weights and the optimizer
model = tf.keras.models.load_model('colormodel_trained_90.h5')

"""## Initializing Color Classes for Prediction"""

# Mapping the Color Index with the respective 11 Classes (More Explained in RGB Color Classifier ML Model jupyter notebook)
color_dict={
    0 : 'Red',
    1 : 'Green',
    2 : 'Blue',
    3 : 'Yellow',
    4 : 'Orange',
    5 : 'Pink',
    6 : 'Purple',
    7 : 'Brown',
    8 : 'Grey',
    9 : 'Black',
    10 : 'White'
}

#predicting from loaded trained_model
def predict_color(Red, Green, Blue):
    rgb = np.asarray((Red, Green, Blue)) #rgb tuple to numpy array
    input_rgb = np.reshape(rgb, (-1,3)) #reshaping as per input to ANN model
    color_class_confidence = model.predict(input_rgb) # Output of layer is in terms of Confidence of the 11 classes
    color_index = np.argmax(color_class_confidence, axis=1) #finding the color_class index from confidence
    color = color_dict[int(color_index)]
    return color

# display image with the size and rgb color
def display_image():
    img = Image.new("RGB", (200, 200), color=(Red,Green,Blue))
    img = ImageOps.expand(img, border=1, fill='black')  # border to the img
    st.image(img, caption='RGB Color')

st.header("Select RGB values")

Red = st.slider( label="RED value: ", min_value=0, max_value=255, value=0, key="red")
Green = st.slider(label="GREEN value: ", min_value=0, max_value=255, value=0, key="green")
Blue = st.slider(label="BLUE value: ", min_value=0, max_value=255, value=0, key="blue")

st.write('Red: {}, Green: {}, Blue: {}'.format(Red, Green, Blue))
display_image()
result = ""
if st.button("Predict"):
    result = predict_color(Red, Green, Blue)
    st.success('The Color is {}!'.format(result))

#st.markdown(hide_st_style, unsafe_allow_html=True)

st.sidebar.title("About")
st.sidebar.info(
        "**RGB Color Classifier** can Predict upto 11 Distinct Color Classes based on the RGB input by User from the sliders\n\n"
        "The 11 Classes are *Red, Green, Blue, Yellow, Orange, Pink, Purple, Brown, Grey, Black and White*\n\n"
        "This app is created and maintained by "
    )
st.sidebar.title("Contribute")
st.sidebar.info(
    "You are very **Welcome** to contribute your awesome comments, questions or suggestions ")
#st.title("RGB Color Classifier")


import subprocess
from pypln.backend.celery_task import PyPLNTask

class Lemmatizer(PyPLNTask):
    """Lemmatizer"""

    def process(self, document):
        if not document['palavras_raw_ran']:
            # If palavras didn't run, just ignore this document
            return {}

        lines = document['palavras_raw'].split('\n')
        lemmas = []
        for line in lines:
            if line.startswith('$'): # punctuation
                lemmas.append(line.split('#')[0].split('$')[1].strip())
            else: # other tokens
                data = line.split('[')
                if len(data) > 1: # if it is a real token
                    lemmas.append(line.split('[')[1].split(']')[0])

        return {'lemmas': lemmas}


# a function for train inference linking (R^3).
from math import floor
import cv2
import imageio
import numpy as np
from svox2 import Rays
import torch
import svox2
import os
import json
from tqdm import tqdm
# from opt.util.nerf_dataset import NeRFDataset

from util.dataset import datasets, NSVFDataset, NeRFDataset
from util import config_util
from exps.arguments import produce_args
from icecream import ic

def cos_dist(vec_a, vec_b):
    return torch.nn.functional.cosine_similarity(vec_a, vec_b, dim=0)

args = produce_args()
# post-assign args
data_dir = args.data_dir

# load json file.
with open(os.path.join(data_dir, "data_config.json")) as fp:
    style_dict = json.load(fp)

args.color_pre      = style_dict["color_pre"]
args.dataset_type   = style_dict["dataset_type"]
args.scene_name     = style_dict["scene_name"]
args.style_img      = style_dict["style_img"]
args.style_name     = style_dict["style_name"]
args.tmpl_idx_test  = style_dict["tmpl_idx_test"]
args.tmpl_idx_train = style_dict["tmpl_idx_train"]
args.data_dir       = "./data/{}/{}".format(args.dataset_type, args.scene_name)
args.out_dir        = os.path.join(args.out_dir, args.style_name)

if args.tmpl_idx_train is not None:
    if not isinstance(args.tmpl_idx_train, list):
        args.tmpl_idx_train = [args.tmpl_idx_train]
elif not isinstance(args.tmpl_idx_test, list):
    args.tmpl_idx_test = [args.tmpl_idx_test]

os.makedirs(args.out_dir, exist_ok=True)

ic("Start ray registeration step")
if os.path.exists(os.path.join(args.out_dir, "color_corr.pt")):
    ic("preload the correspondence, goto the next step")
    PRELOAD=True
    exit()
ic(style_dict)

pretrained_svox2 = "./exps/base_pr/ckpt_svox2/{}/{}/ckpt.npz".format(args.dataset_type, args.scene_name)
device = "cuda" if torch.cuda.is_available() else "cpu"

# for multiple reference.
if isinstance(args.style_img, str):
    args.style_img = [args.style_img]
style_imgs = [cv2.cvtColor(cv2.imread(args.style_img[i] , 1), cv2.COLOR_BGR2RGB)/255.0 for i in range(len(args.style_img))]

grid = svox2.SparseGrid.load(pretrained_svox2, device=device).eval()
ic("Loaded ckpt: ", pretrained_svox2)
dset = datasets['auto'](args.data_dir, split="train",
                        **config_util.build_data_options(args))

for i in range(len(style_imgs)):
    style_imgs[i] = cv2.resize(style_imgs[i], (dset.w, dset.h), interpolation=cv2.INTER_CUBIC)

# two options: for llff we can use the validation view for an easier index match.
tmpl_cams = []
if args.tmpl_idx_train is not None:
    with torch.no_grad():
        for idx_train in args.tmpl_idx_train:
            tmpl_cam = svox2.Camera(dset.c2w[idx_train].to(device=device),
                            dset.intrins.get('fx', idx_train),
                            dset.intrins.get('fy', idx_train),
                            dset.intrins.get('cx', idx_train),
                            dset.intrins.get('cy', idx_train),
                            dset.w, dset.h,
                            ndc_coeffs=dset.ndc_coeffs)
            im = grid.volume_render_image(tmpl_cam, use_kernel=True, return_raylen=args.ray_len)
            tmpl_cams += [tmpl_cam]

    tmpl_ids = args.tmpl_idx_train

elif args.tmpl_idx_test is not None:
    dset_val = datasets['auto'](
        args.data_dir,
        split="test",
        device=device,
        **config_util.build_data_options(args),
    )
    with torch.no_grad():
        for idx_test in args.tmpl_idx_test:
            tmpl_cam = svox2.Camera(
                dset_val.render_c2w[idx_test].to(device=device),
                dset_val.intrins.get("fx", idx_test),
                dset_val.intrins.get("fy", idx_test),
                dset_val.intrins.get("cx", idx_test),
                dset_val.intrins.get("cy", idx_test),
                dset.w, dset.h,
                ndc_coeffs=dset_val.ndc_coeffs,
            )
            tmpl_cams += [tmpl_cam]
            im = grid.volume_render_image(tmpl_cam, use_kernel=True, return_raylen=args.ray_len)

    tmpl_ids = args.tmpl_idx_test

else:
    ic("You should specify a idx, program exit")
    exit()

# Here, what we want to do is establish a fine lookup table between
# the training data and the stylized templates. This can be divided into the following three steps:

# Step A: First, pre-store all the information we need: depth, position, and position range.
eps = 1e-5

sigma_thresh = 1e-8
if isinstance(dset, NSVFDataset):
    sigma_thresh = 100
ic(sigma_thresh)

depths = []
xyzs = []
xyz_max = torch.zeros(3).cuda()
xyz_min = torch.ones(3).cuda()

for n in tqdm(range(dset.n_images)):
    cam = svox2.Camera(dset.c2w[n].to(device=device),
                    dset.intrins.get('fx', n),
                    dset.intrins.get('fy', n),
                    dset.intrins.get('cx', n),
                    dset.intrins.get('cy', n),
                    dset.w, dset.h,
                    ndc_coeffs=dset.ndc_coeffs)
    rays = cam.gen_rays()
    depth_img = grid.volume_render_depth_image(cam, sigma_thresh=sigma_thresh)[..., None]
    depth_rep = depth_img.repeat(1, 1, 3)
    xyz_pos = rays.origins.view(cam.height, cam.width, 3) + \
            rays.dirs.view(cam.height, cam.width, 3)*depth_rep
    xyz_min = torch.minimum(xyz_min, torch.min(xyz_pos[depth_rep!=0].reshape(-1, 3), dim=0)[0])
    xyz_max = torch.maximum(xyz_max, torch.max(xyz_pos[depth_rep!=0].reshape(-1, 3), dim=0)[0])
    xyz_pos[depth_rep==0] = 0
    depths += depth_img.unsqueeze(0)
    xyzs += xyz_pos.unsqueeze(0)

depths = torch.cat(depths).cpu().numpy().reshape(dset.n_images, dset.w, dset.h)
xyzs = torch.cat(xyzs).cpu().numpy().reshape(dset.n_images, dset.w, dset.h, -1)
aabb = torch.cat((xyz_min, xyz_max)).cpu().numpy()
ic(aabb)

# Step B. For each point, we can find its corresponding geometric position,
# and store template information
# (xyz + direction, somewhat similar to the approach used in visualization tools) in a 3D grid (256^3).
n_grid = 512
grid_unit = 1.0 / n_grid
grid_offset = 1.0 / n_grid * 0.5
eps = 1e-5

xyz_min = aabb[:3]
xyz_max = aabb[3:]

position_dict = (torch.ones((n_grid, n_grid, n_grid, 3))*-2).cuda()
direction_dict = (torch.ones((n_grid, n_grid, n_grid, 3))*-2).cuda()
id_dict = (torch.ones((n_grid, n_grid, n_grid))*-2).cuda().long()
position_counts = torch.zeros((n_grid, n_grid, n_grid)).long()

xyzs = (xyzs - xyz_min) / (xyz_max - xyz_min + eps)
dirs = dset.rays.dirs.reshape(dset.n_images, -1, 3).cuda()
tmpl_xyzs = []
tmpl_depths = []
tmpl_dirs = []
tmpl_ignore = []
for i, tmpl_id in enumerate(tmpl_ids):
    if args.tmpl_idx_train is not None:
        tmpl_xyzs += [xyzs[tmpl_id].reshape(-1, 3)]
        depth_img = depths[tmpl_id].reshape(-1)
        tmpl_depths += [depth_img]
        tmpl_dirs += [dirs[tmpl_id]]
    else:
        # with the test dataset.
        rays = tmpl_cam.gen_rays()
        depth_img = grid.volume_render_depth_image(tmpl_cam, sigma_thresh=sigma_thresh)[..., None]
        depth_rep = depth_img.repeat(1, 1, 3)
        depth_img = depth_img.reshape(-1).cpu().numpy()
        tmpl_xyz = (rays.origins.view(tmpl_cam.height, tmpl_cam.width, 3) + \
                    rays.dirs.view(tmpl_cam.height, tmpl_cam.width, 3)*depth_rep).cpu().numpy()
        tmpl_xyz = (tmpl_xyz - xyz_min) / (xyz_max - xyz_min + eps)

        tmpl_dirs += (rays.dirs.reshape(-1, 3))
        tmpl_depths += [depth_img]
        tmpl_xyzs += [tmpl_xyz.reshape(-1, 3)]

    # trick：ignore boundary with a mask.
    border_ignore_mask = depth_img.reshape(dset.h, dset.w)
    if isinstance(dset, NeRFDataset):
        border_ignore_mask[border_ignore_mask != 0] = 1
        border_ignore_mask = cv2.erode(border_ignore_mask, np.ones((3, 3)), iterations=7)
    tmpl_ignore += [border_ignore_mask.reshape(-1)]

tmpl_xyz = np.concatenate(tmpl_xyzs, axis=0)
tmpl_depth = np.concatenate(tmpl_depths, axis=0)
tmpl_dir = torch.concat(tmpl_dirs, dim=0)
if len(tmpl_dir.shape) == 1:
    tmpl_dir = tmpl_dir.view(-1, 3)
tmpl_ignore = np.concatenate(tmpl_ignore, axis=0)
ic(tmpl_xyz.shape, tmpl_depth.shape, tmpl_dir.shape, tmpl_ignore.shape)

preload = False
tmpl_xyz = torch.from_numpy(tmpl_xyz).cuda()

# TODO: accelerate here. We use a denser voxels and deprecate the density. 512^3 = 256^3*8
ray_batch_size = 20000
h = dset.h
w = dset.w

for i in tqdm(range((len(tmpl_xyz))//ray_batch_size + (int)((len(tmpl_xyz))%ray_batch_size!=0))):

    xyz_batch = tmpl_xyz[i*ray_batch_size:i*ray_batch_size + ray_batch_size]
    ref_dir_batch = tmpl_dir[i*ray_batch_size:i*ray_batch_size + ray_batch_size]
    id_batch = torch.tensor([m for m in range(i*ray_batch_size, min((i+1)*ray_batch_size, len(tmpl_xyz)))]).long().cuda()
    index_int = (xyz_batch*n_grid).long()
    position_dict[index_int[:, 0], index_int[:, 1], index_int[:, 2]] = xyz_batch
    direction_dict[index_int[:, 0], index_int[:, 1], index_int[:, 2]] = ref_dir_batch
    id_dict[index_int[:, 0], index_int[:, 1], index_int[:, 2]] = id_batch

torch.cuda.empty_cache()

# Step C. Next, in the training rays, find the top K values (currently, k=3)
# or index values using nearest neighbor search, and use them as the corresponding ray results
# (Verification: A simple verification can be done using rendering and pixel replacement).

res_dict = (torch.ones((dset.n_images, w*h, 3))*-1).cuda()
for test_idx in tqdm(range(dset.n_images)):
    with torch.no_grad():
        cam_ref = svox2.Camera(dset.c2w[test_idx].to(device=device),
                            dset.intrins.get('fx', test_idx),
                            dset.intrins.get('fy', test_idx),
                            dset.intrins.get('cx', test_idx),
                            dset.intrins.get('cy', test_idx),
                            dset.w, dset.h,
                            ndc_coeffs=dset.ndc_coeffs)
        im = grid.volume_render_image(cam_ref, use_kernel=True, return_raylen=args.ray_len)
    rays = cam_ref.gen_rays()

    ref_xyz = torch.from_numpy(xyzs[test_idx].reshape(-1, 3)).cuda()
    ref_depth =  torch.from_numpy(depths[test_idx].reshape(-1)).cuda()
    ref_dir = dirs[test_idx]

    ref_img = dset.rays.gt.reshape(-1, h*w, 3)[test_idx].cuda()
    style_tmpl = torch.from_numpy(np.concatenate([m.reshape(-1, 3) for m in style_imgs], axis=0)).cuda()
    # ic(style_tmpl.shape)
    ray_batch_size = 20000

    for i in range((h*w)//ray_batch_size + (int)((h*w)%ray_batch_size!=0)):
        xyz_batch = ref_xyz[i*ray_batch_size:i*ray_batch_size + ray_batch_size]
        ref_dir_batch = ref_dir[i*ray_batch_size:i*ray_batch_size + ray_batch_size]

        index_int = (xyz_batch*n_grid).long()
        grid_pos = position_dict[index_int[:,0], index_int[:,1], index_int[:,2]]
        grid_dir = direction_dict[index_int[:,0], index_int[:,1], index_int[:,2]]
        grid_idx = id_dict[index_int[:,0], index_int[:,1], index_int[:,2]]
        cur_dist = torch.sum((xyz_batch - grid_pos)**2, dim=1)
        # mask with a direction distance restriction.
        dir_dist = torch.nn.functional.cosine_similarity(ref_dir_batch, grid_dir, dim=1)
        cur_dist[dir_dist < 0.3] = 100

        res_dict[test_idx][i*ray_batch_size:i*ray_batch_size + ray_batch_size] = style_tmpl[grid_idx]
        res_dict[test_idx][i*ray_batch_size:i*ray_batch_size + ray_batch_size][cur_dist > 0.1] = -1

# Save the dictionary.
# TODO: efficient data structure to save memory (save as PNG?)
torch.save(res_dict.cpu(), os.path.join(args.out_dir, 'color_corr.pt'))
# DONE


import scrapy

class UueduudisedSpider(scrapy.Spider):
    name = 'uueduudised'
    #allowed_domains = ['uueduudised.ee/arhiiv']
    start_urls = ['https://uueduudised.ee/rubriik/arvamus/','https://uueduudised.ee/rubriik/uudis/eesti/', 'https://uueduudised.ee/rubriik/uudis/maailm/', 'https://uueduudised.ee/rubriik/majandus/']

    def parse(self, response):
        HL_SELECTOR = '.news_box_item_content'
        for news in response.css(HL_SELECTOR):
            LINK_SELECTOR = 'h3 a ::attr(href)'
            yield {
                'link': news.css(LINK_SELECTOR).extract_first(),
            }
        #next_page = response.css('.next page-numbers a ::attr(href)').extract_first()
        next_page = response.xpath('.//a[@class="next page-numbers"]/@href').extract_first()
        print("Järgmine lehekülg on: ", next_page)
        #print("URL " + response.urljoin(next_page))

        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)


# -*- coding: utf-8 -*-
__author__ = 'dkold_000'

from django.db import models
from django.contrib import admin

from basis.widgets import ImageWidget
from contacts.models import Contact

class ContactAdmin(admin.ModelAdmin):

    fieldsets = [
        (None,          {'fields':  ['image', 'text']}),
        (u'Координаты', {'fields':  ['coord', 'coord_popup']}),
        ('Admin',       {'fields':  ['_created', '_updated', '_active', '_comment'],
                         'classes': ['collapse']}),
    ]

    formfield_overrides = {
        models.ImageField:  {'widget':  ImageWidget()}
    }

    readonly_fields = ['_created', '_updated']

admin.site.register(Contact, ContactAdmin)


from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from scipy.sparse import coo_matrix

#Function for sorting tf_idf in descending order
def sort_coo(coo_matrix):
    tuples = zip(coo_matrix.col, coo_matrix.data)
    return sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)

def extract_topn_from_vector(feature_names, sorted_items, topn=10):
    """get the feature names and tf-idf score of top n items"""

    #use only topn items from vector
    sorted_items = sorted_items[:topn]
    score_vals = []
    feature_vals = []

    # word index and corresponding tf-idf score
    for idx, score in sorted_items:

        #keep track of feature name and its corresponding score
        score_vals.append(round(score, 3))
        feature_vals.append(feature_names[idx])

    #create a tuples of feature,score
    #results = zip(feature_vals,score_vals)
    results= {}
    for idx in range(len(feature_vals)):
        results[feature_vals[idx]]=score_vals[idx]

    return results

def get_top_phrase(corpus, n=None):
    vec1 = CountVectorizer(ngram_range=(2,3),
            max_features=2000).fit([corpus])
    bag_of_words = vec1.transform([corpus])
    sum_words = bag_of_words.sum(axis=0)
    words_freq = [(word, sum_words[0, idx]) for word, idx in
                  vec1.vocabulary_.items()]
    words_freq =sorted(words_freq, key = lambda x: x[1],
                reverse=True)
    return words_freq[:n]


# August 20, 2020
# Permutations: given a collection of distinct integers, return all possible permutations

# Backtracking:
# - Base case: stop once the current perm length == length of nums array
# - Backtracking fundamentals
#   1. Make the change: perm + [i]
#   2. Recurse: call gen(...)
#   3. Undo the change: implicit here. Perm isn't changed before the gen(...) call, so when you return from the gen(...)
#      call, perm is as if the change never happened
#   Alternate solution:
#       perm.append(i)
#       gen(nums, perm, ans)
#       perm.pop()
def permute(self, nums: List[int]) -> List[List[int]]:
    if not nums:
        return nums

    def gen(nums, perm, ans):
        if len(nums) == len(perm):
            ans.append(perm)

        for i in nums:
            if i not in perm:
                perm.append
                gen(nums, perm + [i], ans)

    ans = []
    gen(nums, [], ans)
    return ans


# Helper class for text generation, contacts OpenAI's API
# three models will be available:
# 1. A finetuned davinci model
# 2. GPT-3.5-turbo
# 3. GPT-4

import os

from openai import OpenAI

from dotenv import load_dotenv
from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential,
)  # for exponential backoff

load_dotenv()

FINETUNED_MODEL_NAME = os.getenv("MODEL_NAME")

BASE_TEMPERATURE = float(os.getenv("BASE_TEMPERATURE"))

CHEAP_CHAT_MODEL_NAME = 'gpt-3.5-turbo'

EXPENSIVE_CHAT_MODEL_NAME = 'gpt-4-1106-preview'
# EXPENSIVE_CHAT_MODEL_NAME = 'gpt-4'

# Queries a chatGPT model with messages using OpenAI's api
async def query_chat_model(client, messages: list, chat_model_name: str, temperature: float = BASE_TEMPERATURE):
    if chat_model_name == 'gpt-4-1106-preview':
        response = await query_openai_chatgpt_model_with_backoff(
            client=client,
            model=chat_model_name,
            messages=messages,
            temperature=temperature,
            response_format={"type": "json_object"}
        )
    else:
        response = await query_openai_chatgpt_model_with_backoff(
            client=client,
            model=chat_model_name,
            messages=messages,
            temperature=temperature,
        )
    # get the first result
    text = response.choices[0].message.content
    return text

# Directly queries the finetuned model using OpenAI's api
async def query_finetuned_openai_model(client, prompt_with_items: str, temperature: float = BASE_TEMPERATURE):
    response = await query_openai_model_with_backoff(
        client=client,
        model=FINETUNED_MODEL_NAME,
        prompt=prompt_with_items,
        max_tokens=500,
        temperature=temperature,
        stop=[" END"]
    )
    # get the first result
    text = response.choices[0].text
    # remove empty space at the beginning
    processed_text = text[1:]
    return processed_text

# API methods
@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
async def query_openai_model_with_backoff(client, **kwargs):
    response = await client.completions.create(**kwargs)
    return response

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
async def query_openai_chatgpt_model_with_backoff(client, **kwargs):
    response = await client.chat.completions.create(**kwargs)
    return response

def get_messages_from_system_and_user_prompts(system_prompts: list, user_prompts: list):
    messages = []
    for i in range(len(system_prompts)):
        messages.append({
            "role": "system",
            "content": system_prompts[i]
        })
    for i in range(len(user_prompts)):
        messages.append({
            "role": "user",
            "content": user_prompts[i]
        })
    return messages

# Adds model termination string to the prompt
def request_text_to_prompt(text: str):
    return text + "###"


#!/usr/bin/env python3

'''Combine the output of compute_rows.py into a pickle file for clustering.py'''

import pickle, sys, collections
import numpy as np

target_names = []
targets = dict() # name to index
values = collections.defaultdict(dict) # indexed by row name, col name

for fname in sys.argv[1:]:
    for line in open(fname):
        (t1,t2,dist,lsim) = line.split()
        dist = float(dist)
        if t2 not in targets:
            targets[t2] = len(target_names)
            target_names.append(t2)
        values[t1][t2] = (dist,lsim)

#must have fully filled out matrix
l = len(target_names)
m = np.empty((l,l))
lm = np.empty((l,l))
m[:] = np.NAN
lm[:] = np.NAN

for t1 in values.keys():
    for t2 in values[t1].keys():
        i = targets[t1]
        j = targets[t2]
        m[i][j] = values[t1][t2][0]
        lm[i][j] = values[t1][t2][1]

#check throws a key error if a key is missing in targets
#      or prints the sentence if NAN is present
for i in range(l):
    for j in range(l):
        if not np.isfinite(m[i][j]):
            print("Missing distance for",targets[i],targets[j])

        if not np.isfinite(lm[i][j]):
            print("Missing ligand_sim for",targets[i],targets[j])

pickle.dump((m, target_names, lm), open('matrix.pickle','wb'),-1)


class Node:
  def __init__(self, nombre, apellido, num, email):
    self.num=num
    self.nombre=nombre
    self.apellido=apellido
    self.email=email
    self.next=None
  def getnum(self):
    return self.num
  def getnombre(self):
    return self.nombre
  def getap(self):
    return self.apellido
  def getemail(self):
    return self.email

class Hashi:
  def __init__(self, size):
    self.list=[None]*size
    self.size=size

  def str2num(self, word):
    return(sum(ord(c) for c in word)-96)
  def hash_id(self, apellido):
    return abs(int(self.str2num(apellido)/10))

  def agregar_ordenado(self, nombre, apellido, numero, email):
    node = Node(nombre,apellido,numero,email)
    pos=self.hash_id(apellido)
    #print(pos)
    if self.list[pos] is None:
      self.list[pos]=node
      return

    while self.list[pos] is not None:
      if (self.list[pos].nombre==nombre and self.list[pos].apellido==apellido):
        self.list[pos]=node
        return
      else:
        pos=pos+1
    self.list[pos]=node
    return

  def buscar(self, apellido):
    print("Buscando contacto...")
    print("")
    pos=self.hash_id(apellido)
    if self.list[pos] is None:
      print("No existe el contacto")
      return
    while self.list[pos] is not None:
      if (self.list[pos].apellido==apellido):
        print("numero: ", self.list[pos].num, " email: ", self.list[pos].email)
        return
      pos=pos+1
    print("No existe el contacto")
    return

  def borrar(self, nombre, apellido):
    print("Eliminando a:", nombre, apellido)
    print("")
    pos=self.hash_id(apellido)
    if self.list[pos] is None:
      print("No existe el contacto")
      return
    while self.list[pos] is not None:
      if (self.list[pos].nombre==nombre and self.list[pos].apellido==apellido):
        self.list[pos]=None
        print("Borrado.")
        print("-------------")
        return
      pos=pos+1
    print("No existe el contacto")
    print("")
    return

  def imprimir(self):
    aux=0
    while aux<400:
      if(self.list[aux] is None):
        aux=aux+1
      else:
        print(self.list[aux].nombre, self.list[aux].apellido,  ", numero: ", self.list[aux].num, ", email: ",self.list[aux].email)
        print("")
        aux=aux+1
    print("----------")
    return

a = int(400)
b1 = Hashi(a)


from . import __version__ as app_version

app_name = "hoox"
app_title = "Hoox"
app_publisher = "jango_blockchained"
app_description = (
    "An API Gateway to handle Tradingview Alerts and execute trades using ccxt."
)
app_icon = "fa fa-line-chart"
app_color = "orange"
app_email = "info@cryptolinx.de"
app_license = "MIT"

# Includes in <head>
# ------------------

# include js, css files in header of desk.html
app_include_css = ["/assets/hoox/css/copy_icon.css"]
#    "/assets/js/lightweight-charts.min.js"]
app_include_js = ["/assets/hoox/js/hoox.js"]

# include js, css files in header of web template
# web_include_css = "/assets/hoox/css/hoox.css"
web_include_js = "/assets/hoox/js/hoox_web.js"

# include custom scss in every website theme (without file extension ".scss")
# website_theme_scss = "hoox/public/scss/website"

# include js, css files in header of web form
# webform_include_js = {"doctype": "public/js/doctype.js"}
# webform_include_css = {"doctype": "public/css/doctype.css"}

# include js in page
# page_js = {"page" : "public/js/file.js"}

# include js in doctype views
# doctype_js = {"Trade": "public/js/lightweight-charts.js"}
# doctype_list_js = {"doctype" : "public/js/doctype_list.js"}
# doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"}
# doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"}

# Home Pages
# ----------

# application home page (will override Website Settings)
# home_page = "login"

# website user home page (by Role)
# role_home_page = {
# 	"Role": "home_page"
# }

# Generators
# ----------

# automatically create page for each record of this doctype
# website_generators = ["Web Page"]

# Installation
# ------------

# before_install = "hoox.install.before_install"
# after_install = "hoox.install.after_install"

# Uninstallation
# ------------

# before_uninstall = "hoox.uninstall.before_uninstall"
# after_uninstall = "hoox.uninstall.after_uninstall"

# Desk Notifications
# ------------------
# See frappe.core.notifications.get_notification_config

# notification_config = "hoox.notifications.get_notification_config"

# Permissions
# -----------
# Permissions evaluated in scripted ways

# permission_query_conditions = {
# 	"Event": "frappe.desk.doctype.event.event.get_permission_query_conditions",
# }
#
# has_permission = {
# 	"Event": "frappe.desk.doctype.event.event.has_permission",
# }

# DocType Class
# ---------------
# Override standard doctype classes

# override_doctype_class = {
# 	"ToDo": "custom_app.overrides.CustomToDo"
# }

# Document Events
# ---------------
# Hook on document methods and events

# doc_events = {
#     "*": {
#         "on_update": "method",
#         "on_cancel": "method",
#         "on_trash": "method"
#     }
# }

# Scheduled Tasks
# ---------------

# scheduler_events = {
# 	"all": [
# 		"hoox.tasks.all"
# 	],
# 	"daily": [
# 		"hoox.tasks.daily"
# 	],
# 	"hourly": [
# 		"hoox.tasks.hourly"
# 	],
# 	"weekly": [
# 		"hoox.tasks.weekly"
# 	]
# 	"monthly": [
# 		"hoox.tasks.monthly"
# 	]
# }
scheduler_events = {
    "cron": {
        # This will run every minute
        "*/3 * * * *": [
            "hoox.hoox.doctype.outgoing_request.outgoing_request.check_and_update_status",
            "hoox.hoox.doctype.incoming_response.incoming_response.check_and_update_status",
            "hoox.hoox.doctype.trade.trade.check_and_update_status"],
        "* * * * *": [
            "hoox.hoox.doctype."
        ]
    }
}

# Testing
# -------

# before_tests = "hoox.install.before_tests"

# Overriding Methods
# ------------------------------
#
# override_whitelisted_methods = {
# 	"frappe.desk.doctype.event.event.get_events": "hoox.event.get_events"
# }
#
# each overriding function accepts a `data` argument;
# generated from the base implementation of the doctype dashboard,
# along with any modifications made in other Frappe apps
# override_doctype_dashboards = {
# 	"Task": "hoox.task.get_dashboard_data"
# }

# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]

# Request Events
# ----------------
# before_request = ["hoox.utils.before_request"]
# after_request = ["hoox.utils.after_request"]

# Job Events
# ----------
# before_job = ["hoox.utils.before_job"]
# after_job = ["hoox.utils.after_job"]

# User Data Protection
# --------------------

user_data_fields = [
    {
        "doctype": "{doctype_1}",
        "filter_by": "{filter_by}",
        "redact_fields": ["{field_1}", "{field_2}"],
        "partial": 1,
    },
    {
        "doctype": "{doctype_2}",
        "filter_by": "{filter_by}",
        "partial": 1,
    },
    {
        "doctype": "{doctype_3}",
        "strict": False,
    },
    {"doctype": "{doctype_4}"},
]

# Authentication and authorization
# --------------------------------

# auth_hooks = [
#     "hoox.user.auth"
# ]

# Fixtures
# --------

fixtures = ['Signal Provider', 'Market Type',
            'Hoox Settings', 'IP Whitelist','Timeframe']

# def set_cors_headers(response):
#     response.headers['Access-Control-Allow-Origin'] = '*'
#     response.headers['Access-Control-Allow-Credentials'] = 'true'
#     response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
#     response.headers['Access-Control-Allow-Headers'] = 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'
#     return response

# after_request = [set_cors_headers]

# Python Dependencies
# -------------------

install_requires=[
    'frappe',
    'frappe_telegram'
]


"""
1229. Meeting Scheduler
Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration 'duration', return the earliest time slot that works for both of them and is of duration duration.

If there is no common time slot that satisfies the requirements, return an empty array.

The format of a time slot is an array of two elements [start, end] representing an inclusive time range from start to end.

It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots [start1, end1] and [start2, end2] of the same person, either start1 > end2 or start2 > end1.

Example1:
Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8
Output: [60,68]

Example2:
Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12
Output: []

Constraints:
1 <= slots1.length, slots2.length <= 10^4
slots1[i].length, slots2[i].length == 2
slots1[i][0] < slots1[i][1]
slots2[i][0] < slots2[i][1]
0 <= slots[i][j], slots2[i][j] <= 10^9
1 <= duration <= 10^6
"""

"""
Notes:
1. Two Pointers: O(nlogn+mlogm) time | O(n+m) space
2. Line Sweep: O((n+m)log(n+m)) time | O(n+m) space
"""
import collections
from typing import List
class Solution:
    def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
        def intersect(slot1, slot2) -> List[int]:
            start, end = max(slot1[0], slot2[0]), min(slot1[1], slot2[1])
            return [start, end] if start < end else [0,0]

        idx1 = idx2 = 0
        slots1.sort(key=lambda x: x[0])
        slots2.sort(key=lambda x: x[0])
        while idx1 < len(slots1) and idx2 < len(slots2):
            slot1 = slots1[idx1]
            slot2 = slots2[idx2]
            intersectSlot = intersect(slot1, slot2)
            if (intersectSlot[1]-intersectSlot[0]) >= duration:
                return [intersectSlot[0], intersectSlot[0]+duration]
            elif slot1[1] < slot2[1]:
                idx1 += 1
            else:
                idx2 += 1
        return []

    def minAvailableDuration2(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
        timeIncreasePeople = collections.defaultdict(int)
        for start, end in slots1+slots2:
            timeIncreasePeople[start] += 1
            timeIncreasePeople[end] -= 1

        peopleCount = 0
        validStart = -1
        for time in sorted(timeIncreasePeople.keys()):
            peopleCount += timeIncreasePeople[time]

            if validStart != -1 and time - validStart >= duration:
                return [validStart, validStart+duration]

            if peopleCount < 2:
                validStart = -1
            else:
                validStart = time
        return []

# Unit Tests
import unittest
funcs = [Solution().minAvailableDuration, Solution().minAvailableDuration2]

class TestMinAvailableDuration(unittest.TestCase):
    def testMinAvailableDuration1(self):
        for func in funcs:
            slots1 = [[10,50],[60,120],[140,210]]
            slots2 = [[0,15],[60,70]]
            duration = 8
            self.assertEqual(func(slots1=slots1, slots2=slots2, duration=duration), [60,68])

    def testMinAvailableDuration2(self):
        for func in funcs:
            slots1 = [[10,50],[60,120],[140,210]]
            slots2 = [[0,15],[60,70]]
            duration = 12
            self.assertEqual(func(slots1=slots1, slots2=slots2, duration=duration), [])

    def testMinAvailableDuration3(self):
        for func in funcs:
            slots1 = [[10,60]]
            slots2 = [[12,17],[21,50]]
            duration = 8
            self.assertEqual(func(slots1=slots1, slots2=slots2, duration=duration), [21, 29])

    def testMinAvailableDuration4(self):
        for func in funcs:
            slots1 = [[216397070,363167701],[98730764,158208909],[441003187,466254040],[558239978,678368334],[683942980,717766451]]
            slots2 = [[50490609,222653186],[512711631,670791418],[730229023,802410205],[812553104,891266775],[230032010,399152578]]
            duration = 456085
            self.assertEqual(func(slots1=slots1, slots2=slots2, duration=duration), [98730764,99186849])

456085
if __name__ == "__main__":
    unittest.main()


import RPi.GPIO as GPIO
import time
from readchar import readchar
from gpiozero import Robot
import numpy as np

#GPIO.cleanup()

GPIO.setmode(GPIO.BCM)                     #Set GPIO pin numbering

bit_a = 22
bit_b = 27
bit_c = 17
rf_pin = 15

GPIO.setup(bit_a, GPIO.OUT)
GPIO.setup(bit_b, GPIO.OUT)
GPIO.setup(bit_c, GPIO.OUT)
GPIO.setup(rf_pin,GPIO.OUT)

leftPins_x = (12, 16)
rightPins_x = (20, 21)

leftPins_y = (26, 19)
rightPins_y = (13, 6)

robot_x = Robot(left = leftPins_x, right = rightPins_x)
robot_y = Robot(left = leftPins_y, right = rightPins_y)

def robot_con(xl, xr, yl, yr):
    robot_x.value = (xl, xr)
    robot_y.value = (yl, yr)

def robot_con2(x, y):
    robot_x.value = (x, x)
    robot_y.value = (y, y)

def multiplex(code):

    if len(code) == 3:

        GPIO.output(bit_a, int(code[2]))
        GPIO.output(bit_b, int(code[1]))
        GPIO.output(bit_c, int(code[0]))
        time.sleep(0.00001)

    else:
        print("multiplex fail")

def distancesen(echo_pin, trig_pin):

    GPIO.setup(trig_pin,GPIO.OUT)                  #Set pin as GPIO out
    GPIO.setup(echo_pin,GPIO.IN)                   #Set pin as GPIO in

    GPIO.output(trig_pin, False)                 #Set TRIG as LOW
    GPIO.output(rf_pin, False)                  #rf is active low
    time.sleep(0.05)

    GPIO.output(trig_pin, True)                  #Set TRIG as HIGH
    time.sleep(0.00001)                      #Delay of 0.00001 seconds
    GPIO.output(trig_pin, False)                 #Set TRIG as LOW

    pulse_start = time.time()

    while GPIO.input(echo_pin)==0:               #Check whether the ECHO is LOW
        pulse_start = time.time()              #Saves the last known time of LOW pulse

    GPIO.output(rf_pin, True)

    pulse_end = time.time()

    while GPIO.input(echo_pin)==1:               #Check whether the ECHO is HIGH
        pulse_end = time.time()                #Saves the last known time of HIGH pulse

    pulse_duration = pulse_end - pulse_start #Get pulse duration to avariable
    distance = (pulse_duration-0.05) * 34030    #Multiply pulse duration by 17150 to get distance

    time.sleep(0.2)

    return round(distance, 2)            #Round to two decimal points

def distancesen_all(echo_pin, trig_pin):

    out_of_range = 1000

    GPIO.setup(trig_pin,GPIO.OUT)                  #Set pin as GPIO out
    GPIO.setup(echo_pin,GPIO.IN)                   #Set pin as GPIO in

    dist_list = [0] * 8

    GPIO.output(trig_pin, False)                 #Set TRIG as LOW
    GPIO.output(rf_pin, False)                  #rf is active low
    time.sleep(0.05)
    GPIO.output(rf_pin, True)

    GPIO.output(trig_pin, True)                  #Set TRIG as HIGH
    time.sleep(0.00001)                      #Delay of 0.00001 seconds
    GPIO.output(trig_pin, False)                 #Set TRIG as LOW

    pulse_start = time.time()

    time.sleep(0.01)

    while time.time() < pulse_start + 0.5:
        for i in range(0,len(dist_list)):
            #print(i)
            ultra_2(i+1)
            if GPIO.input(echo_pin)==1:
                dist_list[i] = time.time()

    for i in range(0,len(dist_list)):
        if (dist_list[i]-pulse_start) > 0.1:
            dist_list[i] = out_of_range
        else:
            dist_list[i] = (dist_list[i]-pulse_start - 0.05) *34030

    #return dist_list

    dist = min(dist_list)

    if dist == out_of_range:
        module = None
        dist = None

        return(module, dist)

    else:
        module = dist_list.index(dist)+1
        return(module, dist)

def multi_ultra(string, echo_pin, trig_pin):
    multiplex(string)
    return distancesen(echo_pin, trig_pin)

def ultra(element):
    if element == 1:
        return multi_ultra('000', 23, 24)
    elif element == 2:
        return multi_ultra('001', 23, 24)
    elif element == 3:
        return multi_ultra('010', 23, 24)
    elif element == 4:
        return multi_ultra('011', 23, 24)
    elif element == 5:
        return multi_ultra('100', 23, 24)
    elif element == 6:
        return multi_ultra('101', 23, 24)
    elif element == 7:
        return multi_ultra('110', 23, 24)
    elif element == 8:
        return multi_ultra('111', 23, 24)
    else:
        print("ultra fail")
        return None

def ultra_2(element):
    if element == 1:
        return multiplex('000')
    elif element == 2:
        return multiplex('001')
    elif element == 3:
        return multiplex('010')
    elif element == 4:
        return multiplex('011')
    elif element == 5:
        return multiplex('100')
    elif element == 6:
        return multiplex('101')
    elif element == 7:
        return multiplex('110')
    elif element == 8:
        return multiplex('111')
    else:
        print("ultra fail")
        return None

def valid_dist(value):

    #print("check valid")
    attempts = 5
    out_of_range2 = 600

    for i in range(1,attempts +1):
        dist = ultra(value)
        #print(dist)
        if (0 < dist < out_of_range2):
            #i = attempts+10
            break
        else:
            #dist = None
            dist = 10000

    return dist

def adj(module):
    if module == 1:
        list_module=[8,1,2]
    elif module == 2:
        list_module=[1,2,3]
    elif module == 3:
        list_module=[2,3,4]
    elif module == 4:
        list_module=[3,4,5]
    elif module == 5:
        list_module=[4,5,6]
    elif module == 6:
        list_module=[5,6,7]
    elif module == 7:
        list_module=[6,7,8]
    elif module == 8:
        list_module=[7,8,1]
    else:
        return None

    print(list_module)

    return list_module

def smart_al(module):
    #scan module

    #scan  adjacent
    adj_list = adj(module)
    #print(adj_list)
    dist_list = [0] * 3
    #print dist
    min_module = 5

    for i in range (0, len(adj_list)):
        #print(i, adj_list[i])
        dist_list[i] = valid_dist(adj_list[i])

    #print(dist_list)
    dist = min(dist_list)
    module = adj_list[dist_list.index(dist)]

    #if timeout, scan module 1

    return(module, dist)

def get_cartesian(module, dist):
    #get angle
    angle = (90 + (module - 1)*45) % 360

    x = dist * np.cos(np.radians(angle))
    y = dist * np.sin(np.radians(angle))

    return(x,y)

def module_forward(module):

    speed = 0.4

    print(module)

    if module == 1:
        return (speed, speed, 0, 0)
    elif module == 2:
        return (speed, speed, -speed, -speed)
    elif module == 3:
        return (0, 0, -speed, -speed)
    elif module == 4:
        return (-speed, -speed, -speed, -speed)
    elif module == 5:
        return (-speed, -speed, 0, 0)
    elif module == 6:
        return (-speed, -speed, speed, speed)
    elif module == 7:
        return (0, 0, speed, speed)
    elif module == 8:
        return (speed, speed, speed, speed)
    else:
        pass

multiplex('000')

print("***Starting***")

multiplex('000')

module = 1

while True:

    lower_lim = 100
    upper_lim = 200
    out_of_range = 400

    module,dist = distancesen_all(23,24)

    print (module,dist)

    if dist != None:
        if upper_lim < dist < out_of_range:
            #forward
            print("forward")
            command = module_forward(module)
            print(command)
            robot_con(command[0],command[1],command[2],command[3])
            #time.sleep(1)
            #robot_con(0, 0, 0, 0)
        elif dist < lower_lim:
            #pass
            #backward
            print("backward")
            command = module_forward(module)
            print(command)
            robot_con(-command[0],-command[1],-command[2],-command[3])
            #time.sleep(1)
            #robot_con(0, 0, 0, 0)
        else:
            #stop
            print("stop")
            robot_con(0, 0, 0, 0)
    else:
        print("stop, no distance")
        #module =  prev_module
        #print("after: ", module)
        robot_con(0, 0, 0, 0)

    #apply to each half of robot


#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import pytest

import disdat.api as api

TEST_CONTEXT = '___test_context___'

@pytest.fixture(autouse=True)
def run_test():
    # Remove test context before running test
    setup()
    yield
    api.delete_context(context_name=TEST_CONTEXT)

def setup():
    if TEST_CONTEXT in api.ls_contexts():
        api.delete_context(context_name=TEST_CONTEXT)

    api.context(context_name=TEST_CONTEXT)