import gym
import tensorflow as tf
from tensorflow import keras
import random
import numpy as np
import datetime as dt
import imageio
import os

#
# conda activate tf
# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/
# conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0
# o pip install tensorflow
# pip install tensorflow-gpu
# o pip install gym
# o pip install gym[atari]
# o pip install autorom[accept-rom-license]
# pip install keras
# pip install keras-rl2
# o pip install imageio

# https://adventuresinmachinelearning.com/atari-space-invaders-dueling-q/
#
# uses PERSI to make training more efficient (take this out?)

# Fix for weird thing
# https://stackoverflow.com/questions/68614547/tensorflow-libdevice-not-found-why-is-it-not-found-in-the-searched-path
# export XLA_FLAGS=--xla_gpu_cuda_data_dir=/home/kali/.local/lib/python3.8/site-packages/jaxlib/cuda

#Use xming X server for windows
#run using
#echo "export DISPLAY=localhost:0.0" >> ~/.bashrc
#. ~/.bashrc
# export DISPLAY=[IP]:0.0

STORE_PATH = "tensorboard"  # Path to where tensorboard logs are stored
MAX_EPSILON = 1  # Maximum probability of choosing a random action in epsilon-greedy algorithm
MIN_EPSILON = 0.1  # Minimum probability of choosing a random action in epsilon-greedy algorithm
EPSILON_MIN_ITER = 500000  # Number of iterations after which epsilon will have decreased from MAX_EPSILON to MIN_EPSILON
GAMMA = 0.99  # Discount factor in reinforcement learning
BATCH_SIZE = 32  # Number of samples used in each iteration of training
TAU = 0.08  # Hyperparameter for soft updating of the target network
POST_PROCESS_IMAGE_SIZE = (105, 80, 1)  # Size of processed images used as input to the neural network
DELAY_TRAINING = 50000  # Number of time steps to wait before starting training
BETA_DECAY_ITERS = 500000  # Number of iterations after which beta will have decayed from MAX_BETA to MIN_BETA
MIN_BETA = 0.4  # Minimum value of beta parameter
MAX_BETA = 1.0  # Maximum value of beta parameter
NUM_FRAMES = 4  # Number of frames stacked together as input to the neural network
GIF_RECORDING_FREQ = 100  # Frequency with which GIFs are recorded during training
MODEL_SAVE_FREQ = 100  # Frequency with which the trained model is saved

# Create an environment for the Space Invaders game, using the RGB array render mode
env = gym.make("SpaceInvaders-v0", render_mode="rgb_array")

# Get the number of possible actions in the game
num_actions = env.action_space.n

class DQModel(keras.Model):
    def __init__(self, hidden_size: int, num_actions: int, dueling: bool):
        # Initialize the model using the parent's constructor
        super(DQModel, self).__init__()
        # Save whether the model uses the dueling architecture
        self.dueling = dueling
        # Create the first convolutional layer with 16 filters, each of size 8x8, using a stride of 4
        self.conv1 = keras.layers.Conv2D(16, (8, 8), (4, 4), activation='relu')
        # Create the second convolutional layer with 32 filters, each of size 4x4, using a stride of 2
        self.conv2 = keras.layers.Conv2D(32, (4, 4), (2, 2), activation='relu')
        # Create a flatten layer to flatten the output of the second convolutional layer
        self.flatten = keras.layers.Flatten()
        # Create a dense layer with the specified hidden size, using the He normal kernel initializer
        self.adv_dense = keras.layers.Dense(hidden_size, activation='relu',
                                         kernel_initializer=keras.initializers.he_normal())
        # Create a dense layer with the specified number of actions, using the He normal kernel initializer
        self.adv_out = keras.layers.Dense(num_actions,
                                          kernel_initializer=keras.initializers.he_normal())
        # If the model uses the dueling architecture
        if dueling:
            # Create a dense layer with the specified hidden size, using the He normal kernel initializer
            self.v_dense = keras.layers.Dense(hidden_size, activation='relu',
                                         kernel_initializer=keras.initializers.he_normal())
            # Create a dense layer with a single output, using the He normal kernel initializer
            self.v_out = keras.layers.Dense(1, kernel_initializer=keras.initializers.he_normal())
            # Create a lambda layer to subtract the mean from the outputs of the advantage layer
            self.lambda_layer = keras.layers.Lambda(lambda x: x - tf.reduce_mean(x))
            # Create an Add layer to combine the value and advantage outputs
            self.combine = keras.layers.Add()

    # Define the forward pass of the model
    def call(self, input):
        # Pass the input through the first convolutional layer and apply ReLU activation
        x = self.conv1(input)
        # Pass the output of the first convolutional layer through the second convolutional layer and apply ReLU activation
        x = self.conv2(x)
        # Flatten the output of the second convolutional layer
        x = self.flatten(x)
        # Pass the output of the flatten layer through the advantage dense layer and apply ReLU activation
        adv = self.adv_dense(x)
        # Pass the output of the advantage dense layer through the advantage output layer
        adv = self.adv_out(adv)
        # If the model uses the dueling architecture
        if self.dueling:
            # Pass the output of the flatten layer through the value dense layer and apply ReLU activation
            v = self.v_dense(x)
            # Pass the output of the value dense layer through the value output layer
            v = self.v_out(v)
            # Pass the output of the advantage output layer through the lambda layer to subtract the mean
            norm_adv = self.lambda_layer(adv)
            # Pass the value and advantage outputs through the Add layer to combine them
            combined = self.combine([v, norm_adv])
            # Return the combined output
            return combined
        # If the model doesn't use the dueling architecture, return the advantage output
        return adv

def huber_loss(loss):
    return 0.5 * loss ** 2 if abs(loss) < 1.0 else abs(loss) - 0.5
# The Huber loss function is a loss function that is more robust
# than the mean squared error loss function. It is defined as the
# mean squared error loss function for small values of the error,
# but becomes a mean absolute error loss function for larger values of the error.
# This makes it more resilient to the effects of outliers, since the loss for these points
# is not squared and therefore not disproportionately large compared to the rest of the data.
# Was experimenting with this, but tf.keras.losses.Huber() is more efficient.

primary_network = DQModel(256, num_actions, True)
target_network = DQModel(256, num_actions, True)
# each model has 256 hidden units.

primary_network.compile(optimizer=keras.optimizers.Adam(), loss=tf.keras.losses.Huber())
# make target_network = primary_network
for t, e in zip(target_network.trainable_variables, primary_network.trainable_variables):
    t.assign(e)

class Node:
    def __init__(self, left, right, is_leaf: bool = False, idx = None):
        self.left = left
        self.right = right
        self.is_leaf = is_leaf
        self.value = sum(n.value for n in (left, right) if n is not None)
        self.parent = None
        self.idx = idx  # this value is only set for leaf nodes
        if left is not None:
            left.parent = self
        if right is not None:
            right.parent = self

    @classmethod
    def create_leaf(cls, value, idx):
        leaf = cls(None, None, is_leaf=True, idx=idx)
        leaf.value = value
        return leaf

# This code defines a basic class for a Node in a tree data structure.
# The Node class has several attributes, including left and right for
# the left and right child nodes, is_leaf for whether the node is a leaf node,
# value for the value of the node, parent for the parent node, and idx for the index of the node.
# The __init__ method is used to initialize a new Node object, and takes several arguments
# including left, right, is_leaf, and idx. The value attribute is set to the sum of
# the values of the left and right child nodes, and the parent attributes of the left and
# right child nodes are set to the new Node object. The create_leaf class method can be used
# to create a new leaf Node with a given value and index.

def create_tree(input: list):
    nodes = [Node.create_leaf(v, i) for i, v in enumerate(input)]
    leaf_nodes = nodes
    while len(nodes) > 1:
        inodes = iter(nodes)
        nodes = [Node(*pair) for pair in zip(inodes, inodes)]

    return nodes[0], leaf_nodes

# This code defines a method to create a tree of nodes

def retrieve(value: float, node: Node):
    if node.is_leaf:
        return node

    if node.left.value >= value:
        return retrieve(value, node.left)
    else:
        return retrieve(value - node.left.value, node.right)

# This code defines a method to create a tree of nodes

def update(node: Node, new_value: float):
    change = new_value - node.value

    node.value = new_value
    propagate_changes(change, node.parent)

def propagate_changes(change: float, node: Node):
    node.value += change

    if node.parent is not None:
        propagate_changes(change, node.parent)

class Memory(object):
    def __init__(self, size: int):
        self.size = size
        self.curr_write_idx = 0
        self.available_samples = 0
        self.buffer = [(np.zeros((POST_PROCESS_IMAGE_SIZE[0], POST_PROCESS_IMAGE_SIZE[1]), dtype=np.float32), 0.0, 0.0, 0.0) for i in range(self.size)]
        self.base_node, self.leaf_nodes = create_tree([0 for i in range(self.size)])
        self.frame_idx = 0
        self.action_idx = 1
        self.reward_idx = 2
        self.terminal_idx = 3
        self.beta = 0.4
        self.alpha = 0.6
        self.min_priority = 0.01

    def append(self, experience: tuple, priority: float):
        self.buffer[self.curr_write_idx] = experience
        self.update(self.curr_write_idx, priority)
        self.curr_write_idx += 1
        # reset the current writer position index if creater than the allowed size
        if self.curr_write_idx >= self.size:
            self.curr_write_idx = 0
        # max out available samples at the memory buffer size
        if self.available_samples + 1 < self.size:
            self.available_samples += 1
        else:
            self.available_samples = self.size - 1

    def update(self, idx: int, priority: float):
        update(self.leaf_nodes[idx], self.adjust_priority(priority))

    def adjust_priority(self, priority: float):
        return np.power(priority + self.min_priority, self.alpha)

    def sample(self, num_samples: int):
        sampled_idxs = []
        is_weights = []
        sample_no = 0
        while sample_no < num_samples:
            sample_val = np.random.uniform(0, self.base_node.value)
            samp_node = retrieve(sample_val, self.base_node)
            if NUM_FRAMES - 1 < samp_node.idx < self.available_samples - 1:
                sampled_idxs.append(samp_node.idx)
                p = samp_node.value / self.base_node.value
                is_weights.append((self.available_samples + 1) * p)
                sample_no += 1
        # apply the beta factor and normalise so that the maximum is_weight < 1
        is_weights = np.array(is_weights)
        is_weights = np.power(is_weights, -self.beta)
        is_weights = is_weights / np.max(is_weights)
        # now load up the state and next state variables according to sampled idxs
        states = np.zeros((num_samples, POST_PROCESS_IMAGE_SIZE[0], POST_PROCESS_IMAGE_SIZE[1], NUM_FRAMES),
                             dtype=np.float32)
        next_states = np.zeros((num_samples, POST_PROCESS_IMAGE_SIZE[0], POST_PROCESS_IMAGE_SIZE[1], NUM_FRAMES),
                            dtype=np.float32)
        actions, rewards, terminal = [], [], []
        for i, idx in enumerate(sampled_idxs):
            for j in range(NUM_FRAMES):
                states[i, :, :, j] = self.buffer[idx + j - NUM_FRAMES + 1][self.frame_idx][:, :, 0]
                next_states[i, :, :, j] = self.buffer[idx + j - NUM_FRAMES + 2][self.frame_idx][:, :, 0]
            actions.append(self.buffer[idx][self.action_idx])
            rewards.append(self.buffer[idx][self.reward_idx])
            terminal.append(self.buffer[idx][self.terminal_idx])
        return states, np.array(actions), np.array(rewards), next_states, np.array(terminal), sampled_idxs, is_weights

# The Memory class is used to store past experiences from the environment in a replay buffer,
# which is then used to train the reinforcement learning model. The Memory class uses a priority
# queue implemented as a sum tree data structure to prioritize experiences in the replay buffer
# according to their importance, with more important experiences being more likely to be sampled for training.

memory = Memory(200000)

# preprocesses an image to be inputted into the network
def image_preprocess(image, new_size=(105, 80)):
    # convert to greyscale, resize and normalize the image
    # image = image[0]
    #print(image)
    image = tf.image.rgb_to_grayscale(image)
    image = tf.image.resize(image, new_size)
    image = image / 255
    return image

# chooses an action (epsilon greedy function)
def choose_action(state, primary_network, eps, step):
    if step < DELAY_TRAINING:
        return random.randint(0, num_actions - 1)
    else:
        if random.random() < eps:
            return random.randint(0, num_actions - 1)
        else:
            return np.argmax(primary_network(tf.reshape(state, (1, POST_PROCESS_IMAGE_SIZE[0],
                                                           POST_PROCESS_IMAGE_SIZE[1], NUM_FRAMES)).numpy()))

# Updates from primary network
def update_network(primary_network, target_network):
    for t, e in zip(target_network.trainable_variables, primary_network.trainable_variables):
        t.assign(t * (1 - TAU) + e * TAU)

# Processes the state stack.
def process_state_stack(state_stack, state):
    for i in range(1, state_stack.shape[-1]):
        state_stack[:, :, i - 1].assign(state_stack[:, :, i])
    state_stack[:, :, -1].assign(state[:, :, 0])
    return state_stack

# Records a gif replay of the entire game using imageio.
def record_gif(frame_list, episode, fps=50):
    if(len(frame_list) > 50):
        imageio.mimsave(STORE_PATH + "\\SPACE_INVADERS_EPISODE-eps{}-r{}.gif".format(episode, reward), frame_list, fps=fps) #duration=duration_per_frame)ation_per_frame)

def get_per_error(states, actions, rewards, next_states, terminal, primary_network, target_network):
    # predict Q(s,a) given the batch of states
    prim_qt = primary_network(states)
    # predict Q(s',a') from the evaluation network
    prim_qtp1 = primary_network(next_states)
    # copy the prim_qt tensor into the target_q tensor - we then will update one index corresponding to the max action
    target_q = prim_qt.numpy()
    # the action selection from the primary / online network
    prim_action_tp1 = np.argmax(prim_qtp1.numpy(), axis=1)
    # the q value for the prim_action_tp1 from the target network
    q_from_target = target_network(next_states)
    updates = rewards + (1 - terminal) * GAMMA * q_from_target.numpy()[:, prim_action_tp1]
    target_q[:, actions] = updates
    # calculate the loss / error to update priorites
    error = [huber_loss(target_q[i, actions[i]] - prim_qt.numpy()[i, actions[i]]) for i in range(states.shape[0])]
    return target_q, error

def train(primary_network, memory, target_network):
    states, actions, rewards, next_states, terminal, idxs, is_weights = memory.sample(BATCH_SIZE)
    target_q, error = get_per_error(states, actions, rewards, next_states, terminal, primary_network, target_network)
    for i in range(len(idxs)):
        memory.update(idxs[i], error[i])
    loss = primary_network.train_on_batch(states, target_q, is_weights)
    return loss

num_episodes = 1501
# In practice, model weights are saved as multiples of 100. Therefore, set num_episodes to be a multiple of 100 + 1 (0 counts as an episode)
eps = MAX_EPSILON
render = False # If true, will show bot working in real time. Set false to save on graphics power.
train_writer = tf.summary.create_file_writer(STORE_PATH + "/DuelingQPERSI_{}".format(dt.datetime.now().strftime('%d%m%Y%H%M')))
steps = 0
for i in range(num_episodes):
    state = env.reset()
    state = image_preprocess(state[0])
    state_stack = tf.Variable(np.repeat(state.numpy(), NUM_FRAMES).reshape((POST_PROCESS_IMAGE_SIZE[0],
                                                                            POST_PROCESS_IMAGE_SIZE[1],
                                                                            NUM_FRAMES)))
    cnt = 1
    avg_loss = 0
    tot_reward = 0
    if i % GIF_RECORDING_FREQ == 0:
        frame_list = []
    while True:
        if render:
            env.render()
        action = choose_action(state_stack, primary_network, eps, steps)
        next_state, reward, terminated, truncated, info = env.step(action)
        done = terminated or truncated
        tot_reward += reward
        if i % GIF_RECORDING_FREQ == 0:
            frame_list.append(tf.cast(tf.image.resize(next_state, (480, 320)), tf.uint8).numpy())
        next_state = image_preprocess(next_state)
        old_state_stack = state_stack
        state_stack = process_state_stack(state_stack, next_state)

        if steps > DELAY_TRAINING:
            loss = train(primary_network, memory, target_network)
            update_network(primary_network, target_network)
            _, error = get_per_error(tf.reshape(old_state_stack, (1, POST_PROCESS_IMAGE_SIZE[0], POST_PROCESS_IMAGE_SIZE[1], NUM_FRAMES)), np.array([action]), np.array([reward]), tf.reshape(state_stack, (1, POST_PROCESS_IMAGE_SIZE[0], POST_PROCESS_IMAGE_SIZE[1], NUM_FRAMES)), np.array([done]), primary_network, target_network)
            # store in memory
            memory.append((next_state, action, reward, done), error[0])
        else:
            loss = -1
            # store in memory - default the priority to the reward
            memory.append((next_state, action, reward, done), reward)
        avg_loss += loss

        # linearly decay the eps and PER beta values
        if steps > DELAY_TRAINING:
            eps = MAX_EPSILON - ((steps - DELAY_TRAINING) / EPSILON_MIN_ITER) * \
                  (MAX_EPSILON - MIN_EPSILON) if steps < EPSILON_MIN_ITER else \
                MIN_EPSILON
            beta = MIN_BETA + ((steps - DELAY_TRAINING) / BETA_DECAY_ITERS) * \
                  (MAX_BETA - MIN_BETA) if steps < BETA_DECAY_ITERS else \
                MAX_BETA
            memory.beta = beta
        steps += 1

        if done:
            if steps > DELAY_TRAINING:
                avg_loss /= cnt
                print("Episode: {}, Reward: {}, avg loss: {:.5f}, eps: {:.3f}".format(i, tot_reward, avg_loss, eps))
                with train_writer.as_default():
                    tf.summary.scalar('reward', tot_reward, step=i)
                    tf.summary.scalar('avg loss', avg_loss, step=i)
            else:
                print("Pre-training...Episode: {}".format(i))
            if i % GIF_RECORDING_FREQ == 0:
                record_gif(frame_list, i, tot_reward)
            break

        cnt += 1
    if i % MODEL_SAVE_FREQ == 0: # and i != 0:
        primary_network.save_weights(STORE_PATH + "/checkpoints/cp_primary_network_episode_{}.ckpt".format(i))
        target_network.save_weights(STORE_PATH + "/checkpoints/cp_target_network_episode_{}.ckpt".format(i))

#primary_network
#target_network

#primary_network = DQModel(256, num_actions, True)
#target_network = DQModel(256, num_actions, True)
# primary_network.load_weights(STORE_PATH + "/checkpoints/cp_primary_network_episode_1000.ckpt")
# target_network.load_weights(STORE_PATH + "/checkpoints/cp_target_network_episode_1000.ckpt")

# env = gym.make("SpaceInvaders-v0", render_mode="human")
# render = True

# for i in range(1):
#     state = env.reset()
#     state = image_preprocess(state[0])
#     state_stack = tf.Variable(np.repeat(state.numpy(), NUM_FRAMES).reshape((POST_PROCESS_IMAGE_SIZE[0],
#                                                                             POST_PROCESS_IMAGE_SIZE[1],
#                                                                             NUM_FRAMES)))
#     cnt = 1
#     avg_loss = 0
#     tot_reward = 0
#     if i % GIF_RECORDING_FREQ == 0:
#         frame_list = []
#     while True:
#         if render:
#             env.render()
#         action = choose_action(state_stack, primary_network, 0, 51000) # guarantees primary network is chosen
#         next_state, reward, terminated, truncated, info = env.step(action)
#         done = terminated or truncated
#         tot_reward += reward
#         #if i % GIF_RECORDING_FREQ == 0:
#         #    frame_list.append(tf.cast(tf.image.resize(next_state, (480, 320)), tf.uint8).numpy())
#         next_state = image_preprocess(next_state)
#         old_state_stack = state_stack
#         state_stack = process_state_stack(state_stack, next_state)


from typing import Tuple

import jax
import jax.numpy as jnp
import jax.scipy.linalg as linalg
from numpy.typing import ArrayLike

def transition_function(F: jnp.array, u: jnp.array, L: jnp.array, h: float, n_linspace=10000) -> Tuple[
    ArrayLike, ArrayLike,
    ArrayLike]:
    r"""
    A prior of the form
        \mathrm{d}X(t) = (FX(t) + u)\mathrm{d}t + L \mathrm{d}W_t,
    has the following strong solution:
        X(t+h) = \exp{Fh}(X(t) + \int_0^h \exp{-Fs}L \mathrm{d}W_s),
    where
        X(t+h) \mid X(t) ~ \mathcal{N}(A(h)X(t) + \xi(h), Q(h)).
    ----------------------------
    Return \xi(h), Q(h), A(h).
    """
    linspace = jnp.linspace(0, h, n_linspace)
    A = linalg.expm(F * h)

    @jax.vmap
    def integrand_xi(s):
        return linalg.expm(F * s) @ u

    integrand_xi_values = integrand_xi(linspace)
    xi = jnp.trapz(integrand_xi_values, linspace, axis=0)

    @jax.vmap
    def integrand_Q(s):
        B = linalg.expm(F * s) @ L
        return B @ B.T

    integrand_Q_values = integrand_Q(linspace)
    Q = jnp.trapz(integrand_Q_values, linspace, axis=0)

    return xi, Q, A


import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
no_resBlocks = 16
HR_shape = 96
train_data_path = '../data/train'
val_data_path = '../data/val'
advLossFactor = 0.001
VGGLossFactor = 0.006
mse_lr = 0.0001
mse_epochs = 700
initial_lr = 0.0001
second_lr = 0.00001
gan_epochs = 140
batch_size = 16
images_to_eval = 10
no_workers = 8


class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

root = Node(10)

tempNode = root

import numpy as np
for i in np.random.randint(0,100,[10]):
    tempNode.next = Node(i)
    tempNode = tempNode.next
    print(i)
stack = []

print("")

while root:
    stack.append(root)
    root = root.next

while stack:
    res = stack.pop()
    print(res.val)

剑指offer代码/数据结构/面试题6:从头到尾打印链表.py

面试题6:从头到尾打印链表.py


from math import exp

def Newton2(f, dfdx, x0, max_it=20, tol= 1e-3):
    f0 = f(x0)
    iter = 0
    while abs(f0) > tol and iter < max_it:
        x1 = x0 - f0/dfdx(x0)
        x0 = x1
        f0 = f(x0)
        iter += 1

    converged = iter < max_it
    return x0, converged, iter

#call the method for f(x)= x**2-4*x+exp(-x)
f = lambda x: x**2-4*x+exp(-x)
dfdx = lambda x: 2*x-4-exp(-x)

sol, converged, iter = Newton2(f,dfdx,0,tol=1e-3)
if converged:
    print(f'Newtons method converged in {iter} iterations')
    print(f'The approximate root is {sol:g}')
else:
    print(f'The method did not converge')


# https://www.hackerrank.com/challenges/py-the-captains-room/problem

k = int(input())
array = list(map(int, input().split()))

frequencies = dict()

for element in array:
    frequencies[element] = (frequencies[element] if element in frequencies else 0) + 1

for key in frequencies:
    if frequencies[key] == 1:
        print(key)
        break


load("@bazel_tools//tools/cpp:windows_cc_configure.bzl", "find_vc_path", "setup_vc_env_vars")
load("@bazel_tools//tools/cpp:cc_configure.bzl", "MSVC_ENVVARS")

# Keys: target architecture, as in <Windows-SDK-path>/<target-architecture>/bin/rc.exe
# Values: corresponding Bazel CPU value under @platforms//cpu:*
_TARGET_ARCH = {
    "arm": "arm",
    "arm64": "aarch64",
    "x64": "x86_64",
    "x86": "x86_32",
}

def _find_rc_exes(root):
    result = {}
    for a in _TARGET_ARCH:
        exe = root.get_child(a).get_child("rc.exe")
        if exe.exists:
            result[a] = str(exe)
    return result

def _find_all_rc_exe(repository_ctx):
    if not repository_ctx.os.name.startswith("windows"):
        return {}

    vc = find_vc_path(repository_ctx)
    if vc:
        env = setup_vc_env_vars(
            repository_ctx,
            vc,
            envvars = [
                "WindowsSdkDir",
                "WindowsSdkVerBinPath",
            ],
            allow_empty = True,
            escape = False,
        )

        # Try the versioned directory.
        sdk = env.get("WindowsSdkVerBinPath")
        if sdk:
            archs = _find_rc_exes(repository_ctx.path(sdk))
            if archs:
                return archs

        # Try the unversioned directory (typically Windows 8.1 SDK).
        sdk = env.get("WindowsSdkDir")
        if sdk:
            archs = _find_rc_exes(repository_ctx.path(sdk).get_child("bin"))
            if archs:
                return archs
    return {}

def _toolchain_defs(repository_ctx, rc_exes):
    if not rc_exes:
        return ""

    result = ["""# Auto-generated by winsdk_configure.bzl
load(
    "@io_bazel//src/main/res:winsdk_toolchain.bzl",
    "WINDOWS_RESOURCE_COMPILER_TOOLCHAIN_TYPE",
    "windows_resource_compiler_toolchain",
)"""]

    for arch, rc_path in rc_exes.items():
        wrapper = "rc_%s.bat" % arch
        repository_ctx.file(
            wrapper,
            content = "@\"%s\" %%*" % rc_path,
            executable = True,
        )

        result.append(
            """
windows_resource_compiler_toolchain(
    name = "local_{arch}_tc",
    rc_exe = "{wrapper}",
)

toolchain(
    name = "local_{arch}",
    exec_compatible_with = [
        "@platforms//os:windows",
        "@platforms//cpu:x86_64",
    ],
    target_compatible_with = [
        "@platforms//os:windows",
        "@platforms//cpu:{cpu}",
    ],
    toolchain = ":local_{arch}_tc",
    toolchain_type = WINDOWS_RESOURCE_COMPILER_TOOLCHAIN_TYPE,
    visibility = ["//visibility:public"],
)
""".format(
                arch = arch,
                wrapper = wrapper,
                cpu = _TARGET_ARCH[arch],
            ),
        )

    return "\n".join(result)

def _toolchain_labels(repository_ctx, rc_exes):
    tc_labels = [
        "\"@{repo}//:local_{arch}\"".format(repo = repository_ctx.name, arch = arch)
        for arch in rc_exes
    ]
    if rc_exes:
        body = "native.register_toolchains(%s)" % ", ".join(tc_labels)
    else:
        body = "pass"

    return """# Auto-generated by winsdk_configure.bzl

def register_local_rc_exe_toolchains():
    {body}
""".format(body = body)

def _impl(repository_ctx):
    rc_exes = _find_all_rc_exe(repository_ctx)
    repository_ctx.file(
        "BUILD",
        content = _toolchain_defs(repository_ctx, rc_exes),
        executable = False,
    )

    repository_ctx.file(
        "toolchains.bzl",
        content = _toolchain_labels(repository_ctx, rc_exes),
        executable = False,
    )

winsdk_configure = repository_rule(
    implementation = _impl,
    local = True,
    environ = list(MSVC_ENVVARS),
)


def solution(word):
    seq = {'E': 1, 'I': 2, 'O': 3, 'U': 4}
    res = 0
    for i in range(len(word)):
        char = word[i]
        if char == 'A':
            res += 1
            continue
        for j in range(4, i, -1):
            res += (5 ** (j-i)) * seq[word[i]]
        res += seq[word[i]] + 1

    return res


count = 0

n = int(input())
for i in range(0,n):
    a, b, c = input().split()
    if int(a) + int(b) + int(c) >= 2:
        count += 1
    else:
        continue

print(count)


from fastapi import APIRouter, Header
from fastapi.exceptions import HTTPException

from client import get_ccxt_client

router = APIRouter()

@router.get("/info/")
async def list_markets(x_connection_id: str = Header()):
    try:
        client = get_ccxt_client(x_connection_id)
        return client.load_markets()

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/info/{symbol:path}/")
async def retrieve_markets(symbol: str, x_connection_id: str = Header()):
    try:
        markets = await list_markets(x_connection_id)

        if symbol not in markets:
            raise HTTPException(status_code=400, detail=f"symbol {symbol} not found")

        return markets[symbol]

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/info/sync/")
async def sync_markets(x_connection_id: str = Header()):
    try:
        client = get_ccxt_client(x_connection_id)
        return client.load_markets(reload=True)

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/ticker/")
async def list_ticker(x_connection_id: str = Header()):
    try:
        client = get_ccxt_client(x_connection_id)
        return client.fetch_tickers()

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/ticker/{symbol:path}/")
async def retrieve_ticker(symbol: str, x_connection_id: str = Header()):
    try:
        client = get_ccxt_client(x_connection_id)
        return client.fetch_ticker(symbol=symbol)

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/kline/{symbol:path}/interval/{interval:path}/")
async def retrieve_kline(symbol: str, interval: str, x_connection_id: str = Header()):
    try:
        client = get_ccxt_client(x_connection_id)
        client_properties = client.describe()

        if interval not in client_properties["timeframes"]:
            raise HTTPException(status_code=400, detail="invalid value for interval")

        return client.fetch_ohlcv(symbol=symbol, timeframe=interval)

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


import threading
import time
import PySimpleGUI as sg
import psutil
from pathlib import Path
import subprocess

def is_running(process_name):
    running = False
    for proc in psutil.process_iter():
        if process_name in proc.name():
            running = True
            break
    return running

def the_thread(window: sg.Window, logtext, values, gtav_exe, dll_name):
    injected = False
    while not injected:
        if is_running(gtav_exe):
            logtext += f"\n{gtav_exe} is running..."
            window["log"].update(logtext)
            delay = int(values["delay"])
            logtext += f"\nInjecting DLL in {delay} seconds..."
            window["log"].update(logtext)
            time.sleep(delay)
            inj_path = Path("Injector.exe").resolve()
            window["log"].update(logtext)
            inj_output = subprocess.run([inj_path, "--process-name", gtav_exe, "--inject", dll_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True)
            inj_output_out = inj_output.stdout.decode("UTF-8")
            logtext += f"\n{inj_output_out}"
            window["log"].update(logtext)
            injected = True
            window["start"].update(disabled=False)

def main():
    delay = 10
    gta_path = ""
    dll_name = "GTAO_Booster.dll"
    gtav_exe = "GTA5.exe"
    play_gta = "PlayGTAV.exe"

    if Path.exists(Path("settings.ini")):
        with open("settings.ini", 'r') as file:
            content = file.readlines()
            for line in content:
                if "[GTA5_LOC]=" in line:
                    gta_path = line.split("=")[1]
                if "[DELAY]=" in line:
                    delay = int(line.split("=")[1])
                if "[DLL]=" in line:
                    dll_name = line.split("=")[1]

    sg.theme('Dark')
    layout = [
        [sg.Text('Select PlayGTAV.exe:', size=(16,1)), sg.Input(gta_path, key="gta_exe"), sg.FileBrowse(file_types=((play_gta, play_gta),))],
        [sg.Text('Select DLL:', size=(16,1)), sg.Input(dll_name, key="dll"), sg.FileBrowse(file_types=(("", "*.dll"),))],
        [sg.Text('Injection Delay:', size=(16,1), tooltip="Delay to allow GTA to start & decrypt memory. Depending on PC performance and storage media you can decrease/increase this value."), sg.Input(delay, size=(5, 1), enable_events=True, tooltip="Delay to allow GTA to start & decrypt memory. Depending on PC performance and storage media you can decrease/increase this value.", key="delay")],
        [sg.Multiline(size=(70, 12), enable_events=True, key="log", autoscroll=True, disabled=True)],
        [sg.Button('START GTAV & Inject DLL', key="start", disabled=False), sg.Button('EXIT', key="exit", button_color=("white", "red"))],
        [sg.Text('© ThatOldGrumpyMan', size=(16, 1))],
    ]

    window = sg.Window('GTAV Auto DLL Injector', layout, finalize=True)

    if not Path.exists(Path("Injector.exe")):
        logtext = "Injector.exe is missing! Place it in the same directory as this file!\nInjector.exe is required to inject DLL in process.\nGet it here: https://github.com/nefarius/Injector\nRestart application when done."
        window["log"].update(logtext)
        window["start"].update(disabled=True)

    if is_running(gtav_exe):
        logtext = "GTA V is already running! Close it and restart this application!"
        window["log"].update(logtext)
        window["start"].update(disabled=True)

    while True:
        event, values = window.read()

        try:
            delay = str(values["delay"])
        except TypeError:
            delay = str(delay)
        if len(delay) > 0 and delay[0] not in ('123456789'):
            window["delay"].update(values["delay"][:-1])
        if len(delay) > 0 and delay[-1] not in ('0123456789'):
            window["delay"].update(values["delay"][:-1])
        if len(delay) > 2:
            window["delay"].update(values["delay"][:-1])

        if event == "start":
            logtext = ""
            window["log"].update(logtext)
            window["start"].update(disabled=True)
            gta_path = Path(str(values["gta_exe"]).strip("\n")).resolve()

            try:
                logtext = "Starting GTA V..."
                window["log"].update(logtext)
                subprocess.Popen([gta_path])
            except WindowsError:
                logtext += "\nInvalid GTA Path!"
                window["log"].update(logtext)
                window["start"].update(disabled=False)
                continue

            with open("settings.ini", 'w') as file:
                file.write("[GTA5_LOC]=" + str(values["gta_exe"]) + "\n" + "[DELAY]=" + str(values["delay"]) + "\n" + "[DLL]=" + str(values["dll"]))

            logtext += "\nWaiting for GTA V to start..."
            window["log"].update(logtext)

            dll_name = Path(str(values["dll"]).strip("\n")).resolve()

            threading.Thread(target=the_thread, args=(window, logtext, values, gtav_exe, dll_name), daemon=True).start()

        if event == "exit" or event == sg.WIN_CLOSED:
            break
    window.close()

if __name__ == '__main__':
    main()


import rosbag
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import csv
import glob
import os
from tf.transformations import euler_from_quaternion
from scipy.interpolate import interp1d
from scipy.spatial.transform import Rotation as R
import numpy as np

if (len(sys.argv) > 1):
    filename = "../bag/" + sys.argv[1] + ".bag"
else:
    list_of_files = glob.glob('../bag/*')
    latest_file = max(list_of_files, key=os.path.getctime)
    filename = latest_file

def get_rpy(msg):

    roll, pitch, yaw = euler_from_quaternion([msg.pose.pose.orientation.x,
                                              msg.pose.pose.orientation.y,
                                              msg.pose.pose.orientation.z,
                                              msg.pose.pose.orientation.w])
    return roll, pitch, yaw

def diff_percent(a, b):
    if b != 0:
        return (a-b)/b * 100
    else:
        return (b-a)/a * 100

class topic_data:

    def __init__(self, topic_name, filename):
        self.topic_name = topic_name
        self.data = {
            "time": [],
            "r_x": [],
            "r_y": [],
            "r_z": [],
            "q_x": [],
            "q_y": [],
            "q_z": [],
            "q_w": [],
            "roll": [],
            "pitch": [],
            "yaw": [],
            "v_x": [],
            "v_y": [],
            "v_z": [],
            "omega_x": [],
            "omega_y": [],
            "omega_z": []
        }
        self.get_data_from_bag(filename)

    def get_data_from_bag(self, filename):
        with rosbag.Bag(filename) as bag:
            for topic, msg, t in bag.read_messages(topics=[self.topic_name]):
                self.data["time"].append(
                    msg.header.stamp.secs + msg.header.stamp.nsecs/1e9)
                self.data["r_x"].append(msg.pose.pose.position.x)
                self.data["r_y"].append(msg.pose.pose.position.y)
                self.data["r_z"].append(msg.pose.pose.position.z)
                self.data["q_x"].append(msg.pose.pose.orientation.x)
                self.data["q_y"].append(msg.pose.pose.orientation.y)
                self.data["q_z"].append(msg.pose.pose.orientation.z)
                self.data["q_w"].append(msg.pose.pose.orientation.w)
                self.data["roll"].append(get_rpy(msg)[0])
                self.data["pitch"].append(get_rpy(msg)[1])
                self.data["yaw"].append(get_rpy(msg)[2])
                self.data["v_x"].append(msg.twist.twist.linear.x)
                self.data["v_y"].append(msg.twist.twist.linear.y)
                self.data["v_z"].append(msg.twist.twist.linear.z)
                self.data["omega_x"].append(msg.twist.twist.angular.x)
                self.data["omega_y"].append(msg.twist.twist.angular.y)
                self.data["omega_z"].append(msg.twist.twist.angular.z)

    def calculate_velocities(self):
        self.data["v_x"] = []
        self.data["v_y"] = []
        self.data["v_z"] = []
        self.data["omega_x"] = []
        self.data["omega_y"] = []
        self.data["omega_z"] = []

        self.data["v_x"].append(0)
        self.data["v_y"].append(0)
        self.data["v_z"].append(0)
        self.data["omega_x"].append(0)
        self.data["omega_y"].append(0)
        self.data["omega_z"].append(0)

        for i in range(1, len(self.data["time"])):
            self.data["v_x"].append((self.data["r_x"][i] - self.data["r_x"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))
            self.data["v_y"].append((self.data["r_y"][i] - self.data["r_y"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))
            self.data["v_z"].append((self.data["r_z"][i] - self.data["r_z"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))
            # p = R.from_quat([self.data["q_x"][i]-1, self.data["q_y"][i-1], self.data["q_z"][i-1], self.data["q_w"][i-1]])
            # q = R.from_quat([self.data["q_x"][i], self.data["q_y"][i], self.data["q_z"][i], self.data["q_w"][i]])
            # r = np.matmul(p.as_dcm().transpose(), q.as_dcm())
            # r = p.as_dcm()-q.as_dcm()
            # print(r)

            self.data["omega_x"].append((self.data["roll"][i] - self.data["roll"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))
            self.data["omega_y"].append((self.data["pitch"][i] - self.data["pitch"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))
            self.data["omega_z"].append((self.data["yaw"][i] - self.data["yaw"][i-1]) / (self.data["time"][i] - self.data["time"][i-1]))

if __name__ == "__main__":

    truth = topic_data('/tag_box_pose_ground_truth', filename)
    detected = topic_data('/detected_object_state', filename)
    predicted = topic_data('/predicted_object_state', filename)
    ekf = topic_data('/updated_object_state', filename)

    detected.calculate_velocities()

    start_time = 3.12
    simulation_time = 0.79

    truth.data['time'] = [x - start_time for x in truth.data['time']]
    detected.data['time'] = [x - start_time for x in detected.data['time']]
    predicted.data['time'] = [x - start_time for x in predicted.data['time']]
    ekf.data['time'] = [x - start_time for x in ekf.data['time']]

    plot_trajectory = 0
    plot_error = 0
    plot_all = 0
    plot_group = 1
    plot_seperate = 0
    save_csv = 0
    plot_latency = 0

    def compare_plot(attr, include_detected):
        plt.plot(truth.data['time'], truth.data[attr],  'r.-', label='truth')
        if include_detected:
            plt.plot(detected.data['time'],
                    detected.data[attr], 'g.', label='detected')
        plt.plot(predicted.data['time'],
                predicted.data[attr], 'y.', label='predicted')
        plt.plot(ekf.data['time'], ekf.data[attr], 'b.', label='ekf')
        plt.title(attr)
        plt.legend()
        plt.xlim(2, 5)
        plt.show()
        plt.savefig(attr, dpi=400)
        plt.clf()

    def generate_plot(ax, attr, is_detection_estimation, y1=None, y2=None, title=None):

        ax.plot(truth.data['time'], truth.data[attr],  'r.-', label='ground truth', ms=3, lw=1)
        if is_detection_estimation:
            ax.plot(detected.data['time'], detected.data[attr], 'g.-', label='detected estimation')
        else:
            ax.plot(detected.data['time'], detected.data[attr], 'g.-', label='detected state')
        ax.plot(predicted.data['time'],  predicted.data[attr], 'y.-', label='predicted state')
        ax.plot(ekf.data['time'], ekf.data[attr], 'b.-', label='EKF estimation')
        ax.set_title(title if title else attr)
        ax.legend()
        ax.set_xlim(0, simulation_time)
        ax.set_ylim(y1, y2)
        ax.set_xlabel("time [s]")
        if attr == "r_x" or attr == "r_y" or attr == "r_z":
            ax.set_ylabel("position [m]")
        if attr == "roll" or attr == "pitch" or attr == "yaw":
            ax.set_ylabel("rotation [rad]")
        if attr == "v_x" or attr == "v_y" or attr == "v_z":
            ax.set_ylabel("linear velocity [m/s]")
        if attr == "omega_x" or attr == "omega_y" or attr == "omega_z":
            ax.set_ylabel("angular velocity [rad/s]")

    def error_plot(ax, attr):
        f = interp1d(truth.data['time'], truth.data[attr])
        ax.plot(ekf.data['time'], f(ekf.data['time']))
        ax.plot(ekf.data['time'], ekf.data[attr])
        err_det = []
        err_ekf = []
        for i in range(len(ekf.data['time'])):
            err_det.append(diff_percent(
                detected.data[attr][i], f(detected.data['time'][i])))
            err_ekf.append(diff_percent(ekf.data[attr][i], f(ekf.data['time'][i])))

        ax.plot(detected.data['time'], err_det, 'g.-', label='detected')
        ax.plot(ekf.data['time'], err_ekf, 'b.-', label='ekf')

        ax.set_title(attr)
        ax.legend()
        # ax.set_xlim()

    if plot_trajectory:
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.plot(truth.data["r_x"][300:390], truth.data["r_y"][300:390], truth.data["r_z"]
                [300:390], 'r.-', ms=6, lw=2, label='gournd truth trajectory')
        # ax.plot(predicted.data["r_x"][:-5], predicted.data["r_y"][:-5], predicted.data["r_z"][:-5],'y.-', ms=12, lw= 2,label='predicted trajectory')
        ax.plot(detected.data["r_x"][1:-5], detected.data["r_y"][1:-5], detected.data["r_z"][1:-5],'g.-', ms=12, lw= 2,label='detected trajectory')
        ax.plot(ekf.data["r_x"][:-5], ekf.data["r_y"][:-5], ekf.data["r_z"][:-5], 'b.-', ms=12, lw=2, label='ekf trajectory')
        ax.legend()
        ax.set_xlabel('X [m]')
        ax.set_ylabel('Y [m]')
        ax.set_zlabel('Z [m]')
        ax.set_xlim(ekf.data['r_x'][-1], ekf.data['r_x'][0])
        ax.set_ylim()
        ax.set_zlim()
        plt.figure(dpi=400)
        plt.show()

    if plot_error:
        plt.clf()
        fig, axs = plt.subplots(4, 3)
        error_plot(axs[0][0], 'r_x')
        error_plot(axs[0][1], 'r_y')
        error_plot(axs[0][2], 'r_z')
        error_plot(axs[1][0], 'roll')
        error_plot(axs[1][1], 'pitch')
        error_plot(axs[1][2], 'yaw')
        error_plot(axs[2][0], 'v_x')
        error_plot(axs[2][1], 'v_y')
        error_plot(axs[2][2], 'v_z')
        error_plot(axs[3][0], 'omega_x')
        error_plot(axs[3][1], 'omega_y')
        error_plot(axs[3][2], 'omega_z')
        plt.show()

    if plot_all:
        plt.clf()
        fig, axs = plt.subplots(4, 3)
        generate_plot(axs[0][0], 'r_x', False)
        generate_plot(axs[0][1], 'r_y', False)
        generate_plot(axs[0][2], 'r_z', False)
        generate_plot(axs[1][0], 'roll', False)
        generate_plot(axs[1][1], 'pitch', False)
        generate_plot(axs[1][2], 'yaw', False)
        generate_plot(axs[2][0], 'v_x', True)
        generate_plot(axs[2][1], 'v_y', True)
        generate_plot(axs[2][2], 'v_z', True)
        generate_plot(axs[3][0], 'omega_x', True)
        generate_plot(axs[3][1], 'omega_y', True)
        generate_plot(axs[3][2], 'omega_z', True)
        plt.show()

    if plot_group:
        # fig, axs = plt.subplots(1, 3, dpi=200, figsize=(14,4))
        # generate_plot(axs[0], 'r_x', False, title=r'$r_x$', y1=1.5, y2=5.5)
        # generate_plot(axs[1], 'r_y', False, title=r'$r_y$', y1=-2, y2=2)
        # generate_plot(axs[2], 'r_z', False, title=r'$r_z$', y1=-1, y2=3)
        # plt.savefig('/home/ziyou/Desktop/report/figures/s2_r_plot.png', dpi=400)
        # plt.show()
        # plt.clf()

        # fig, axs = plt.subplots(1, 3, dpi=200, figsize=(14,4))
        # generate_plot(axs[0], 'roll', False, title=r'$roll$', y1=-0.5, y2=1)
        # generate_plot(axs[1], 'pitch', False, title=r'$pitch$', y1=-0.4, y2=1.1)
        # generate_plot(axs[2], 'yaw', False, title=r'$yaw$', y1=-0.75, y2=0.75)
        # plt.savefig('/home/ziyou/Desktop/report/figures/s2_q_plot.png', dpi=400)
        # plt.show()
        # plt.clf()

        # fig, axs = plt.subplots(1, 3, dpi=200, figsize=(14,4))
        # generate_plot(axs[0], 'v_x', True, title=r'$v_x$', y1=-6, y2=4)
        # generate_plot(axs[1], 'v_y', True, title=r'$v_y$', y1=-4.5, y2=5.5)
        # generate_plot(axs[2], 'v_z', True, title=r'$v_z$', y1=-5, y2=5)
        # plt.savefig('/home/ziyou/Desktop/report/figures/s2_v_plot.png', dpi=400)
        # plt.show()
        # plt.clf()

        fig, axs = plt.subplots(1, 3, dpi=200, figsize=(14,4))
        generate_plot(axs[0], 'omega_x', True, title=r'$\omega_x$', y1=-15, y2=15)
        generate_plot(axs[1], 'omega_y', True, title=r'$\omega_y$', y1=-15, y2=15)
        generate_plot(axs[2], 'omega_z', True, title=r'$\omega_z$', y1=-15, y2=15)
        plt.savefig('/home/ziyou/Desktop/report/figures/s2_omega_plot.png', dpi=400)
        plt.show()
        plt.clf()

    if plot_seperate:
        compare_plot('r_x', True)
        compare_plot('r_y', True)
        compare_plot('r_z', True)
        compare_plot('q_x', True)
        compare_plot('q_y', True)
        compare_plot('q_z', True)
        compare_plot('q_w', True)
        compare_plot('roll', True)
        compare_plot('pitch', True)
        compare_plot('yaw', True)
        compare_plot('v_x', False)
        compare_plot('v_y', False)
        compare_plot('v_z', False)
        compare_plot('omega_x', False)
        compare_plot('omega_y', False)
        compare_plot('omega_z', False)

    if save_csv:
        # rows = [truth.time,
        #         truth.r_z,
        #         truth.roll,
        #         truth.v_z,
        #         truth.omega_x,
        #         predicted.time,
        #         predicted.r_z,
        #         predicted.roll,
        #         predicted.v_z,
        #         predicted.omega_x,
        #         detected.time,
        #         detected.r_z,
        #         detected.roll,
        #         detected.v_z,
        #         detected.omega_x,
        #         ekf.time,
        #         ekf.r_z,
        #         ekf.roll,
        #         ekf.v_z,
        #         ekf.omega_x]
        rows = []

        with open('analysis.csv', 'wb') as f:
            writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_ALL)
            for row in rows:
                writer.writerow(row)

    if plot_latency:
        latency = [20, 20, 20, 10, 20, 20, 20, 10, 20, 20, 30, 20, 20, 20, 20, 10, 10]
        seq = range(1, len(latency)+1)
        plt.clf()
        plt.bar(seq, latency)
        plt.xlabel("Image processing sequence")
        plt.ylabel("detected latency [ms]")
        plt.xticks(np.arange(1, len(latency)+1, step=1))
        plt.show()
        print(sum(latency) / len(latency))


# Isaiah Grace
# May 13 2020

import colorsys
import random
import rpi_ws281x
import threading

class StripDriver():
    def __init__(self, config):
        self.strip = rpi_ws281x.PixelStrip(
            config['COUNT'],
            config['PIN'],
            config['FREQ_HZ'],
            config['DMA'],
            config['INVERT'],
            config['BRIGHTNESS'],
            config['CHANNEL']
        )
        self.strip.begin()

        # This lock will hopefully help prevent white flashing
        self.strip_lock = threading.Lock()

        # This is the color that pixels will gravitate towards
        self.base_red = 0 # range 0 - 255
        self.base_blue = 0 # range 0 - 255
        self.base_green = 0 # range 0 - 255

        # Pixels can mutate to any color with +- the tolerance from the base
        # A tolerance of 0 means all pixels will be the base_color
        # A tolerance of 255 means pixels color will randomly span the entire color space
        self.tolerance = 0         # range 0 - 255

        # This is the % chance that a color value of a pixel has to mutate
        self.mutation_rate = 0     # range 0 - 100

        # A mutated color will change by this value, either + or -
        # increasing this will increase the speed that the colors change
        self.mutation_step = 2     # range 0 - 255

        # This offset is applied to the hue color wheel and will create a phase change from the valence mapping to the RGB mapping.
        # This website has a good demonstration of HSV color: http://aleto.ch/color-mixer/
        # A offset value of 0.66 would be equivelent of a Hue value of 240 on the above site.
        # Our mapping of the range 0 - 1 to the RGB color space is then represented by the circumpfrence of the HSV color wheel.
        # Note that this only allows mixing of two of the three colors, one will always be zero.
        # Thankfully our mutations will take care of this and we can rely on them to produce more colors.
        self.hue_offset = 0.66     # range 0 - 1

        # These HSV values allow a direct mapping from the 0 - 1 range to the RGB space
        # See: https://en.wikipedia.org/wiki/HSL_and_HSV
        # maximum values for S and V create more vivid and intense colors, and are a good choice with these cheep LEDs
        self.hsv_S = 1
        self.hsv_V = 1

        # This will allow us to detect when all the lights are off, and we don't have to bother doing all the music effects
        self.idle = False

    def is_idle(self):
        return self.idle

    def refresh(self):
        if self.base_red or self.base_green or self.base_blue or self.tolerance:
            self.idle = False

        # This transmits data to the LED strip to set the color of each LED according to the strip array
        with self.strip_lock:
            print(self.print_colors()[1:],end='')
            self.strip.show()

    def clear(self):
        # DOES NOT TRANSMIT NEW COLORS TO STRIP
        # refresh is needed after this to actually turn off the lights
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColorRGB(i,0,0,0)

    def set_base_color_from_valence(self, valence):
        # Takes a valence value (0 - 1) describing the song and returns a color mapping of that value, with the hue_offset applied
        # The offset shifts
        hue = valence + self.hue_offset
        if hue > 1:
            hue = hue - 1

        # colorsys.hsv_to_rgb returns values from 0 - 1, we need to scale these to integers in the range 0 - 255
        (self.base_red, self.base_green, self.base_blue) = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(hue, self.hsv_S, self.hsv_V))

    def set_base_color_from_RGB(self, red, green, blue):
        self.base_red = red
        self.base_green = green
        self.base_blue = blue

    def music_effect(self):
        if self.base_red or self.base_green or self.base_blue or self.tolerance:
            self.idle = False

        if self.idle:
            return

        # If all the lights are off, this will remain True through the updates
        all_off = True
        with self.strip_lock:
            for i in range(self.strip.numPixels()):
                pixel_color = self.strip.getPixelColor(i)

                # Extract the R G B values for this pixel from the packed 24 bit color
                pixel_color = ((0xFF0000 & pixel_color) >> 16,
                               (0x00FF00 & pixel_color) >> 8,
                               (0x0000FF & pixel_color))

                # Mutate each of the colors to find a new color value for the pixel
                pixel_color = self.mutate_color(pixel_color, self.mutation_rate, self.mutation_step)

                # Apply the limiting bound on the new pixel color
                red   = self.apply_bound(pixel_color[0], self.base_red,   self.tolerance)
                green = self.apply_bound(pixel_color[1], self.base_green, self.tolerance)
                blue  = self.apply_bound(pixel_color[2], self.base_blue,  self.tolerance)

                # Update the color of this pixel
                self.strip.setPixelColorRGB(i, red, green, blue)

                # If a pixel_color is nonzero, than not all lights are off
                if red or green or blue:
                    all_off = False

        self.idle = all_off
        #and not self.base_red and not self.base_green and not self.base_blue and not self.tolerance

    def mutate_color(self, color, mutation_rate, mutationStep):
        # Applies a random mutation to each pixel, allowing a natural variation between pixel colors
        mutated_color = list(color)

        # This arithmetic means we only need one call to random in order to generate all three random numbers
        rand = random.randint(0,10000000)
        mutation = [rand % 100,
                    (rand // 100) % 100,
                    (rand // 100000) % 100
        ]

        for i in (0,1,2):
            if mutation[i] < mutation_rate:
                # Apply the color mutation, either increase or decrease the color
                if mutation[i] % 2 == 0:
                    mutated_color[i] = color[i] + mutationStep
                else:
                    mutated_color[i] = color[i] - mutationStep

                # Make sure the mutated color is within 0 - 255
                if mutated_color[i] > 255:
                    mutated_color[i] = 255
                if mutated_color[i] < 0:
                    mutated_color[i] = 0

        return mutated_color

    def apply_bound(self, color, base_color, bound_size):
        # Applies the bound on a particular color value (0 - 255).
        # If the color is outside the allowed bound, gently push it towards the bound.
        # This allows the lights to turn on/off change colors from song to song gradually
        if color > base_color + bound_size:
            return color - 1
        if color < base_color - bound_size:
            return color + 1
        return color

    def print_colors(self):
        # This is some unicode magic that wont work with all terminals, etc...
        strip_length = self.strip.numPixels()
        i = 0
        printout = []
        while(i < strip_length):
            if i % 10 == 0:
                printout.append('\n')

            pixel_color = self.strip.getPixelColor(i)

            # Extract the R G B values for this pixel from the packed 24 bit color
            red   = str((0xFF0000 & pixel_color) >> 16)
            green = str((0x00FF00 & pixel_color) >> 8)
            blue  = str(0x0000FF & pixel_color)

            printout.append('\x1B[38;2;' + red + ';' + green + ';' + blue +'m\u2588')

            i = i + 1

        printout.append('\n\x1B[m')
        return ''.join(printout)


import cv2
import numpy as np

"""
YUV란?

빛의 밝기를 나타내는 휘도(Y)와 색상신호 2개(U, V)로 표현하는 방식이다.

The Y′UV model defines a color space in terms of one luma component (Y′) and
two chrominance components, called U (blue projection) and V (red projection) respectively.

Y = 0.299R + 0.587G + 0.114B
"""

src = cv2.imread('../resources/Lena.png')

(h,w,c) = src.shape
yuv = cv2.cvtColor(src,cv2.COLOR_BGR2YUV)
my_y = np.zeros((h,w))
my_y = (src[:,:,0] * 0.114) + (src[:,:,1] * 0.587) + (src[:,:,2] * 0.299)
my_y = np.round(my_y).astype(np.uint8)

print(yuv[0:5,0:5,0])
print(my_y[0:5,0:5])

cv2.imshow('original',src)
cv2.imshow('cvtColor',yuv[:,:,0]) # yuv의 첫번째 채널은 y
cv2.imshow('my_y',my_y)

cv2.waitKey()
cv2.destroyAllWindows()

Assignment/Fundamentals of Image processing/BGRToY.py


from __future__ import absolute_import
from __future__ import unicode_literals

import argparse

from .. import api, utils
from ..command import Command, CMD_SUCCESS, HELP_LIST
from ..exceptions import InvalidDateError, NotFoundError, WrappedValueError

class Log(Command):
    """List enrollment information available in the registry.

    The command list a set of enrollments. Some searching parameters
    to filter the results are available. Parameters <uuid> and <organization>
    filter by unique identity and organization name. Enrollments between a
    period can also be listed using <from> and <to> parameters, where
    <from> must be less or equal than <to>. Default values for these dates
    are '1900-01-01' and '2100-01-01'.

    Dates may follow several patterns. The most common and recommended
    is 'YYYY-MM-DD'. Optionally, time information can be included using
    patters like 'YYYY-MM-DD hh:mm:ss'.
    """
    def __init__(self, **kwargs):
        super(Log, self).__init__(**kwargs)

        self.parser = argparse.ArgumentParser(description=self.description,
                                              usage=self.usage)

        # Enrollments search options
        self.parser.add_argument('--uuid', default=None,
                                 help="unique identity to withdraw")
        self.parser.add_argument('--organization', default=None,
                                 help="organization where the uuid is enrolled")
        self.parser.add_argument('--from', dest='from_date', default=None,
                                 help="date (YYYY-MM-DD:hh:mm:ss) when the enrollment starts")
        self.parser.add_argument('--to', dest='to_date', default=None,
                                 help="date (YYYY-MM-DD:hh:mm:ss) when the enrollment ends")

        # Exit early if help is requested
        if 'cmd_args' in kwargs and [i for i in kwargs['cmd_args'] if i in HELP_LIST]:
            return

        self._set_database(**kwargs)

    @property
    def description(self):
        return """List enrollments."""

    @property
    def usage(self):
        return "%(prog)s log [--uuid <uuid>] [--organization <organization>] [--from <date>] [--to <date>]"

    def run(self, *args):
        """List enrollments using search parameters."""

        params = self.parser.parse_args(args)

        uuid = params.uuid
        organization = params.organization

        try:
            from_date = utils.str_to_datetime(params.from_date)
            to_date = utils.str_to_datetime(params.to_date)

            code = self.log(uuid, organization, from_date, to_date)
        except InvalidDateError as e:
            self.error(str(e))
            return e.code

        return code

    def log(self, uuid=None, organization=None, from_date=None, to_date=None):
        """"List enrollment information available in the registry.

        Method that returns a list of enrollments. If <uuid> parameter is set,
        it will return the enrollments related to that unique identity;
        if <organization> parameter is given, it will return the enrollments
        related to that organization; if both parameters are set, the function
        will return the list of enrollments of <uuid> on the <organization>.

        Enrollments between a period can also be listed using <from_date> and
        <to_date> parameters. When these are set, the method will return
        all those enrollments where Enrollment.start >= from_date AND
        Enrollment.end <= to_date. Defaults values for these dates are
        1900-01-01 and 2100-01-01.

        :param db: database manager
        :param uuid: unique identifier
        :param organization: name of the organization
        :param from_date: date when the enrollment starts
        :param to_date: date when the enrollment ends
        """
        try:
            enrollments = api.enrollments(self.db, uuid, organization,
                                          from_date, to_date)
            self.display('log.tmpl', enrollments=enrollments)
        except (NotFoundError, WrappedValueError) as e:
            self.error(str(e))
            return e.code

        return CMD_SUCCESS


#!python
import collections

#text=haystack, pattern=needle
def contains(text, pattern):
    """Return a boolean indicating whether pattern occurs in text."""
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
    #funny storytime! initially did not pass because I falsely remembered a lack of explicitly written "else" statement resulting in a default return of "False". In truth, it defaults to "None"
    #Runtime: O(n) because it must go through text to find the pattern. Best case would be O(1), like if the pattern/needle was at the very front of the text/haystack.
    #Space: O(1) because it will always be simply true or false. Boolean, boom!
    if pattern in text:
        return True
    else:
        return False

def index_helper(text, pattern):
    assert isinstance(text, str), 'text is not a string: {}'.format(text)
    assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)

    indices = []
    for index, _ in enumerate(text):
        if pattern == text[index: (index + len(pattern))]:
            indices.append(index)
    return indices

def find_index(text, pattern):
    """Return the starting index of the first occurrence of pattern in text,
    or None if not found."""

    #Runtime: O(n) because it must duplicated the array AND go through the now-quasi-dictionarified text. Each of these is O(n), adding to O(2n), but because runtime is about estimations and not exact figures, it's ultimately just O(n).
    #Space: O(1). Either 'None' or a single index is returned, and no matter what the parameters, the size of output will remain the same

    indices = index_helper(text, pattern) #call the helper function
    if len(indices) is not 0:
        return indices[0] #return the first index
    return None #unless there's nothing, in which case, return None

def find_all_indexes(text, pattern):
    """Return a list of starting indexes of all occurrences of pattern in text,
    or an empty list if not found."""

    #Runtime: O(n), for same reasons as above. Array duplication is O(n), looping through the enumerated text is O(n), adding to O(2n) but ultimately being recorded and treated as O(n) because simplification is alright
    #Space: O(n). This is the same code as the function above (they use the same helper function), EXCEPT that it returns an array rather than a single variable of constant size. We don't know how many times the pattern will be found; it could be one time, it could be a ton

    return index_helper(text, pattern) #call the helper function
    #either it's empty or it contains something. Or some things. Either way, we're returning a list

def test_string_algorithms(text, pattern):
    found = contains(text, pattern)
    print('contains({!r}, {!r}) => {}'.format(text, pattern, found))
    index = find_index(text, pattern)
    print('find_index({!r}, {!r}) => {}'.format(text, pattern, index))
    indexes = find_all_indexes(text, pattern)
    print('find_all_indexes({!r}, {!r}) => {}'.format(text, pattern, indexes))

def main():
    """Read command-line arguments and test string searching algorithms."""
    import sys
    args = sys.argv[1:]  # Ignore script file name
    if len(args) == 2:
        text = args[0]
        pattern = args[1]
        test_string_algorithms(text, pattern)
    else:
        script = sys.argv[0]
        print('Usage: {} text pattern'.format(script))
        print('Searches for occurrences of pattern in text')
        print("\nExample: {} 'abra cadabra' 'abra'".format(script))
        print("contains('abra cadabra', 'abra') => True")
        print("find_index('abra cadabra', 'abra') => 0")
        print("find_all_indexes('abra cadabra', 'abra') => [0, 8]")

if __name__ == '__main__':
    main()


from collections import deque

def solution(progresses, speeds):
    progresses = deque(progresses)
    speeds = deque(speeds)
    answer = []
    while progresses:
        count = 0
        for i in range(len(speeds)):
            progresses[i] += speeds[i]
        while True:
            if progresses[0] < 100:
                break
            else:
                progresses.popleft()
                speeds.popleft()
                count += 1
            if not progresses:
                break
        if count != 0:
            answer.append(count)

    return answer

if __name__ == "__main__":
    progresses = [93, 30, 55]
    speeds = [1, 30, 5]
    solution(progresses, speeds)

프로그래머스_복습/스택_기능개발.py


import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *

class SwitchNode(Node, ArmLogicTreeNode):
    '''Switch node'''
    bl_idname = 'LNSwitchNode'
    bl_label = 'Switch'
    bl_icon = 'CURVE_PATH'
    min_inputs = 1
    min_outputs = 1

    def __init__(self):
        array_nodes[str(id(self))] = self

    def init(self, context):
        self.inputs.new('ArmNodeSocketAction', 'In')
        self.inputs.new('NodeSocketShader', 'Value')
        self.outputs.new('ArmNodeSocketAction', 'Default')

    def draw_buttons(self, context, layout):
        row = layout.row(align=True)
        op = row.operator('arm.node_add_input_output', text='New', icon='PLUS', emboss=True)
        op.node_index = str(id(self))
        op.in_socket_type = 'NodeSocketShader'
        op.out_socket_type = 'ArmNodeSocketAction'
        op.in_name_format = 'Case {0}'
        op.out_name_format = 'Case {0}'
        op.in_index_name_offset = -1
        op2 = row.operator('arm.node_remove_input_output', text='', icon='X', emboss=True)
        op2.node_index = str(id(self))

add_node(SwitchNode, category='Logic')


import tensorflow as tf, numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from baselines.bench.monitor import load_results

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo/train'
df_train = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo/test'
df_test = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo_v1/train/cpo_d_is_1'
df_train_d_is_1 = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo_v1/test/cpo_d_is_1'
df_test_d_is_1 = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo_v1/train/cpo_d_is_2'
df_train_d_is_2 = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo_v1/test/cpo_d_is_2'
df_test_d_is_2 = load_results(logger_dir)

logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/sp/sp_returns.txt'
f_sp = np.loadtxt(logger_dir)

xmax = 3000000

rolling_window = 365*1
rolling_reward = pd.Series(df_train["r"]).rolling(rolling_window)
rolling_reward = rolling_reward.mean().values[rolling_window-1:]
rolling_safety = pd.Series(df_train["s"]).rolling(rolling_window)
rolling_safety = rolling_safety.mean().values[rolling_window-1:]

linestyle_str = [
     ('solid', 'solid'),      # Same as (0, ()) or '-'
     ('dotted', 'dotted'),    # Same as (0, (1, 1)) or '.'
     ('dashed', 'dashed'),    # Same as '--'
     ('dashdot', 'dashdot')]  # Same as '-.'

linestyle_tuple = dict([
     ('loosely dotted',        (0, (1, 10))),
     ('dotted',                (0, (1, 1))),
     ('densely dotted',        (0, (1, 1))),

     ('loosely dashed',        (0, (5, 10))),
     ('dashed',                (0, (5, 5))),
     ('densely dashed',        (0, (5, 1))),

     ('loosely dashdotted',    (0, (3, 10, 1, 10))),
     ('dashdotted',            (0, (3, 5, 1, 5))),
     ('densely dashdotted',    (0, (3, 1, 1, 1))),

     ('dashdotdotted',         (0, (3, 5, 1, 5, 1, 5))),
     ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
     ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])

d = np.sum(f_sp)
cpo_r = "{0:.2f}%".format(np.mean((d+df_test["r"].sum())/d) * 100)
cpo_r_d_is_1 = "{0:.2f}%".format(np.mean((d+df_test_d_is_1["r"].sum())/d) * 100)
cpo_r_d_is_2 = "{0:.2f}%".format(np.mean((d+df_test_d_is_2["r"].sum())/d) * 100)

fig = plt.figure(figsize=(10,7))
ax = plt.subplot(111)
plt.plot(np.cumsum(f_sp), label='SP', linewidth=3.0, marker='*', markersize=10, markevery=20, color='#ff7f0e')
plt.plot(np.cumsum(-df_test["r"]), label=r'$d=0.1$', linewidth=3.0)
plt.plot(np.cumsum(-df_test_d_is_1["r"]), label=r'$d=1$', marker='v', markersize=7, markevery=20, linewidth=3.0, color='#2ca02c')
plt.plot(np.cumsum(-df_test_d_is_2["r"]), label=r'$d=2$', linewidth=3.0, linestyle='dashed', marker='X', markersize=8, markevery=20, color='#9467bd')
plt.xlim(0, 365)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.xlabel('Day', fontsize=20)
plt.ylabel('Cumulative Costs ($)', fontsize=20)
plt.legend(fontsize=20)
ax.text(368, np.around(np.sum(-df_test["r"])+3,2), cpo_r, style='italic', fontsize='x-large',
        bbox={'facecolor': '#1f77b4', 'alpha': 0.5, 'pad': 5})
ax.text(368, np.around(np.sum(-df_test_d_is_1["r"]),2), cpo_r_d_is_1, style='italic',  fontsize='x-large',
        bbox={'facecolor': '#2ca02c', 'alpha': 0.5, 'pad': 5})
ax.text(368, np.around(np.sum(-df_test_d_is_2["r"])-6,2), cpo_r_d_is_2, style='italic',  fontsize='x-large',
        bbox={'facecolor': '#9467bd', 'alpha': 0.5, 'pad': 5})
axh = ax.axhline(y=np.sum(-df_test["r"]))
axh.set_linestyle('--')
axh.set_color('#7f7f7f')
axh = ax.axhline(y=np.sum(-df_test_d_is_1["r"]))
axh.set_linestyle('--')
axh.set_color('#7f7f7f')
axh = ax.axhline(y=np.sum(-df_test_d_is_2["r"]))
axh.set_linestyle('--')
axh.set_color('#7f7f7f')
ax.yaxis.set_label_coords(-0.11,0.5)
plt.tight_layout(rect=(0,0,1,1))
plt.show(block=False)

d = 0.1
cpo_v_01 = "{0:.2f}%".format(np.mean(np.maximum(0, df_test["s"].values-d)/d) * 100)
d = 1.0
cpo_v_1 = "{0:.2f}%".format(np.mean(np.maximum(0, df_test_d_is_1["s"].values-d)/d) * 100)
d = 2.0
cpo_v_2 = "{0:.2f}%".format(np.mean(np.maximum(0, df_test_d_is_2["s"].values-d)/d) * 100)

fig = plt.figure(figsize=(10,7))
ax = plt.subplot(111)
plt.plot(np.cumsum(df_test["s"]), label=r'$d=0.1$', linewidth=3.0)
plt.plot(np.cumsum(df_test_d_is_1["s"]), label=r'$d=1$', marker='v', markersize=7, markevery=20, linewidth=3.0, color='#2ca02c')
plt.plot(np.cumsum(df_test_d_is_2["s"]), label=r'$d=2$', marker='X', markersize=8, markevery=20, linewidth=3.0, linestyle='dashed', color='#9467bd')
plt.xlim(0, 365)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.xlabel('Day', fontsize=20)
plt.ylabel('Cumulative Constraint Values (kWh)', fontsize=20)
ax.text(370, 70, cpo_v_01, style='italic', fontsize='x-large',
        bbox={'facecolor': '#1f77b4', 'alpha': 0.5, 'pad': 7})
ax.text(370, 420, cpo_v_1, style='italic', fontsize='x-large',
        bbox={'facecolor': '#2ca02c', 'alpha': 0.5, 'pad': 7})
ax.text(370, 780, cpo_v_2, style='italic', fontsize='x-large',
        bbox={'facecolor': '#9467bd', 'alpha': 0.5, 'pad': 7})
axh = ax.axhline(y=399)
axh.set_linestyle('--')
axh.set_color('#7f7f7f')
axh1 = ax.axhline(y=780)
axh1.set_linestyle('--')
axh1.set_color('#7f7f7f')
plt.legend(fontsize=20)
plt.tight_layout(rect=(0,0,1,1))
plt.show(block=True)


from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializer import perfil_usuarioSerializer
from .models import perfil_usuario

@api_view(['GET', 'POST'])
def lista_usuarios(request):
    if request.method == 'GET':
        users = perfil_usuario.objects.all()
        serializer = perfil_usuarioSerializer(users, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        data = request.data
        correo = data.get('correo')
        existing_user = perfil_usuario.objects.filter(correo=correo).first()
        if existing_user:
            return Response({'error': 'Ya existe un usuario con este correo electrónico.'}, status=status.HTTP_400_BAD_REQUEST)

        serializer = perfil_usuarioSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


from evdev import ecodes
from datetime import datetime, timedelta
from four_button_pages import StaticMenu, TokenEntryMenu, PAYGStatusMenu, ServiceMenu

class FourButtonUserInterface(object):

    BACKLIGHT_TIMEOUT = 300

    def __init__(self, lcd, conn, kbd, static_pages):
        self.conn = conn
        self.disp = lcd
        self.kbd = kbd
        self.static_pages = static_pages
        self.last_key_pressed = datetime.now()
        self.selected_menu = None
        self.current_menu = None
        self.index = 0
        self.last_index = 1
        self.last_menu_number = 0
        self.menus = [
            ('PAYG Status', PAYGStatusMenu(self.conn)),
            ('Enter Token', TokenEntryMenu(self.conn)),
            ('LAN Status', StaticMenu(self.static_pages[16])),
            ('WiFi Status', StaticMenu(self.static_pages[17])),
            ('General Status', StaticMenu(self.static_pages[0])),
            ('Solar Status', StaticMenu(self.static_pages[12])),
            ('Battery Status', StaticMenu(self.static_pages[18])),
            ('Solar History', StaticMenu(self.static_pages[14])),
            ('Service Menu', ServiceMenu(self.conn)),
        ]
        self.alarm_menus = [
            StaticMenu(self.static_pages[2]), # VE Bus error
            StaticMenu(self.static_pages[3]),  # VE Bus alarm
            StaticMenu(self.static_pages[13]),  # Solar error
        ]

    def start(self):
        self.disp.clear()
        self.update_menu_list()

    def key_pressed(self):
        self.last_key_pressed = datetime.now()
        for event in self.kbd.read():
            if event.type == ecodes.EV_KEY and event.value == 1:
                self.update_current_menu(event.code)

    def tick(self):
        self.display_alarms()
        self.update_current_menu(None)
        self.update_backlight_status()

    def update_backlight_status(self):
        if self.last_key_pressed + timedelta(seconds=self.BACKLIGHT_TIMEOUT) < datetime.now():
            self.disp.on = False
        else:
            self.disp.on = True

    def display_alarms(self):
        for alarm in self.alarm_menus:
            alarm.enter(self.conn, self.disp) # It will only display if the menu actually exists

    def get_available_menus(self):
        menus = []
        for menu in self.menus:
            if menu[1].is_available(self.conn):
                menus.append(menu)
        return menus

    def update_menu_list(self):
        menus = self.get_available_menus()

        number_menus = len(menus)
        if number_menus < self.last_menu_number:
            self.index = 0
        self.last_menu_number = number_menus

        if number_menus == 0:
            top_string = ' Victron Energy '
            bottom_string = ' '.ljust(16, ' ')
        elif number_menus == 1:
            top_string = menus[0][0].ljust(15, ' ') + '>'
            bottom_string = ' '.ljust(16, ' ')
        else:
            if self.index < self.last_index:
                top_string = menus[self.index][0].ljust(15, ' ') + '>'
                bottom_string = menus[self.index + 1][0].ljust(15, ' ') + ' '
            else:
                top_string = menus[self.index - 1][0].ljust(15, ' ') + ' '
                bottom_string = menus[self.index][0].ljust(15, ' ') + '>'

        self.disp.display_string(top_string, 1)
        self.disp.display_string(bottom_string, 2)

        self.selected_menu = menus[self.index][1]

    def menu_list_loop(self, key_pressed):
        number_of_menus = len(self.get_available_menus())
        if key_pressed == ecodes.KEY_UP:
            if self.index > 0:
                self.last_index = self.index
                self.index -= 1
                self.update_menu_list()
        if key_pressed == ecodes.KEY_DOWN:
            if self.index < number_of_menus - 1:
                self.last_index = self.index
                self.index += 1
                self.update_menu_list()
        if key_pressed == ecodes.KEY_RIGHT:
            self.current_menu = self.selected_menu
            self.current_menu.enter(self.conn, self.disp)
        else:
            self.update_menu_list()

    def update_current_menu(self, key_pressed):
        if self.current_menu is not None and not self.current_menu.update(self.conn, self.disp, key_pressed):
            self.current_menu = None
            key_pressed = None
            self.disp.clear()
            self.update_menu_list()
        if self.current_menu is None:
            self.menu_list_loop(key_pressed)


tokens = "this is a decent enough test sentence".split(" ")
cap = len(tokens)
degree = 2

for ti in range(cap):
    lower = ti if ti < degree else degree
    upper = cap - ti -1 if ti >= cap - degree -1 else degree
    # the -1 is because (range(1, 1) won't run once for 1
    for i in range(upper):
        print(i, ti, ti + i +1, upper, cap, degree)
        print(tokens[ti], tokens[ti+i+1])


'''
Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht the frist and lsat ltteers be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe

input: String arr[words in a dictionary]

output: all sets of words that are 'equivalent'

sample input: ['word', 'string', 'field', 'flied', 'fried', 'array', 'fired']
'''

'''
Idea:

Let's use a hashtable:
    Keys = a touple containing the first and last characters of that word
    Values = a touple: a set of inner characters and a list of words.

'''

from collections import Counter
def print_equivalent(words):
    ht = dict()

    for word in words:
        word = word.strip('\'s')

        key = (word[0], word[-1])

        inner_letters = Counter(word[1:-1])

        if key not in ht.keys():
            ht[key] = [(inner_letters, set([word]))]

        else:
            matched = False
            for entry in ht[key]:
                if entry[0] == inner_letters:
                    entry[1].add(word)
                    matched = True

            if not matched:
                new_entry = (inner_letters, set([word]))
                ht[key].append(new_entry)

    for key in ht.keys():
        for entry in ht[key]:
            if len(entry[1]) > 1:
                print (' '.join(entry[1]))

if __name__ == '__main__':
    import file_utils, os
    #print_equivalent([word for word in file_utils.read_file(os.path.join(os.environ['PYTHONPATH'], 'dic.txt')).splitlines() if len(word) > 2])
    print_equivalent(['word', 'fired', 'fried', 'flied', 'field', 'felid'])


import matplotlib.pyplot as plt
from scipy.io import loadmat
import numpy as np
import pandas
from os.path import join,exists
from os import mkdir
import cv2
import math
import os

rho = 1

actions = ['No-Action', 'sweeping', 'gargling', 'opening cupboard', 'washing hands', 'eating', 'writing', 'wiping',
           'drinking','opening microwave oven', 'Throwing trash']

def get_skeleton(skeleton):
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')
    skeleton[:,0]=-skeleton[:,0]
    lines=[[0,1],[1,2],[2,3],[3,4],[21,22],[22,23],[23,24],[21,4],[4,20],[20,11],[11,13],[13,12],[10,11],[14,11]
        ,[10,9],[9,8],[8,7],[7,5],[5,6],[14,15],[15,16],[16,17],[17,19],[18,19]]
    for a,b in lines:
        ax.plot3D([skeleton[a][0],skeleton[b][0]], [skeleton[a][1],skeleton[b][1]], [skeleton[a][2],skeleton[b][2]], 'gray')
    ax.scatter3D(skeleton[:,0],   skeleton[:,1], skeleton[:,2] ,c=skeleton[:,2])
    ax = plt.gca()
    xmin,xmax=min(skeleton[:,0])-0.25,max(skeleton[:,0])+0.25
    ymin,ymax=min(skeleton[:,1])-0.25,max(skeleton[:,1])+0.25
    zmin,zmax=min(skeleton[:,2])-0.25,max(skeleton[:,2])+0.25
    ax.set_xlim([xmin, xmax])
    ax.set_ylim([ymin, ymax])
    ax.set_zlim([zmin, zmax])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.view_init(elev=-75, azim=90)
    ax.set_axis_off()
    plt.tight_layout()
    plt.show()
def get_data(file,type='foot_to_foot'):
    try:
        f = open(file,'r').read().split()
        datait = [float(x) for x in f]
        if type=='no_order':
            data = np.asarray(datait)
            data = data.reshape((25,3))
        else:
            spine_base = datait[0:3]
            spine_mid = datait[3:6]
            neck = datait[6:9]
            head = datait[9:12]
            shoulder_left = datait[12:15]
            elbow_left = datait[15:18]
            wrist_left = datait[18:21]
            hand_left = datait[21:24]
            shoulder_right = datait[24:27]
            elbow_right = datait[27:30]
            wrist_right = datait[30:33]
            hand_right = datait[33:36]
            hip_left = datait[36:39]
            knee_left = datait[39:42]
            ankle_left = datait[42:45]
            foot_left = datait[45:48]
            hip_right = datait[48:51]
            knee_right = datait[51:54]
            ankle_right = datait[54:57]
            foot_right = datait[57:60]
            spine_shoulder = datait[60:63]
            handtip_left = datait[63:66]
            thumb_left = datait[66:69]
            handtip_right = datait[69:72]
            thumb_right = datait[72:75]

            if type=='human':
                data=np.stack((head, neck, spine_shoulder, shoulder_left, shoulder_right, elbow_left, elbow_right,
                                                               wrist_left, wrist_right, thumb_left, thumb_right, hand_left, hand_right, handtip_left,
                                                               handtip_right, spine_mid, spine_base, hip_left, hip_right, knee_left, knee_right,
                                                               ankle_left, ankle_right, foot_left, foot_right))
            else :
                data=np.stack((foot_left, ankle_left, knee_left, hip_left, spine_base, handtip_left, thumb_left,
                                        hand_left, wrist_left, elbow_left, shoulder_left
                                                                   ,spine_shoulder,head,neck, shoulder_right,elbow_right,
                                                                        wrist_right,   hand_right,thumb_right
                                                                       , handtip_right, spine_mid, hip_right,
                                                                       knee_right, ankle_right,foot_right))
        return data
    except:
        print('Ex',file)
        return None

def normalize(array):
    min_ = np.min(array,0)
    max_ = np.max(array,0)
    return (array-min_)/(max_-min_)

def get_sequence_energy(sequence):
    energy = np.zeros((len(sequence),25))
    for i in range(len(sequence)):
        for k in range(25):
            if i == 0:
                energy[i][k] = np.linalg.norm(sequence[i][k] - sequence[i + 1][k])
            elif i == len(sequence)-1:
                energy[i][k] = np.linalg.norm(sequence[i][k] - sequence[i - 1][k])
            else:
                energy[i][k] = (np.linalg.norm(sequence[i][k] - sequence[i + 1][k])+np.linalg.norm(sequence[i][k] - sequence[i - 1][k]))/2
    E = normalize(energy)
    w = rho*E + (1-rho)
    return w
def get_labels(file):
    labels = open(file,'r').read().splitlines()
    prev_action=None
    start =[]
    end = []
    actions=[]
    for line in labels:
        if line.replace(' ','').isalpha():
            prev_action = line.strip()
        else:
            tab = line.split(' ')
            start.append(int(tab[0]))
            end.append(int(tab[1]))
            actions.append(prev_action)
    return (start,end,actions)

def get_image_label(start,end,labels):
    index = (start+end)//2
    for s,e,a in set(zip(labels[0],labels[1],labels[2])):
        if s <= index and index <= e:
            return a
    return 'No-Action'

def to_ludl(data_path,labels,window_length=30,type='no_order'):
    start_frame = min(labels[0]) - window_length//2
    end_frame = max(labels[1]) + window_length //2
    data = []
    for i in range(start_frame,end_frame+1):
        data.append(get_data(data_path+'/'+str(i)+'.txt',type))
    images = [data[i:i + window_length] for i in range(len(data) - window_length + 1)]
    lab = [get_image_label(i,i+window_length,labels) for i in range(start_frame,end_frame -window_length+2)]

    i=0
    while i <len(lab):
        if lab[i] is None:
            del lab[i]
            del images[i]
        else:
            i+=1
    i = 0
    while i < len(images):
        for x in images[i]:
            if x is None or not x.shape==(25,3):
                del lab[i]
                del images[i]
                break
        else:
            i += 1
    return np.asarray(images),lab

def transform_image_ludl(image,path,name,weights):
    RGB = image
    height = image.shape[1]
    width = image.shape[0]
    X = np.arange(height)
    Y = np.arange(width)
    RGB = np.squeeze(RGB)
    # weights = np.expand_dims(weights,0)
    white = np.ones((width,height))*255
    for i in range(3):
        RGB[:,:,i] = np.floor(255 * (RGB[:,:,i] - np.amin(RGB[:,:,i])) / (np.amax(RGB[:,:,i]) - np.amin(RGB[:,:,i])))
        RGB[:, :, i] = RGB[:, :, i]*weights+(1-weights)*white
    # w = np.expand_dims(w,1)
    # print(w[:10])
    # print(sequence[0][:10])
    # # w = np.concatenate([w,w,w],axis=1)
    # print(w.shape)
    # for i in range(len(sequence)):
    #     sequence[i]=sequence[i]*w + np.asarray([255,255,255])*(1-w)
    # sequence = np.asarray(sequence)
    # print(sequence[0][:10])
    # print(sequence.shape,w.shape)
    # print(sequence*w)
    #
    #

    img = np.zeros((height, width, 3), dtype=np.uint8)
    for i in X:
        for j in Y:
            img[i,j]=RGB[j,i]
    # img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_LINEAR)
    cv2.imwrite(join(path,name+'_.png'),img)
    return img

def to_nassim(data_path,labels,window_length=40,type_='foot_to_foot'):

    # start_frame = min(labels[0]) - window_length//2
    # end_frame = max(labels[1]) + window_length //2

    subdirs = [x[2] for x in os.walk(data_path)][0]
    frames = [int(x[:-4]) for x in subdirs]
    start_frame = min(frames)
    end_frame = max(frames)
    data = []
    for i in range(start_frame,end_frame+1):
        data.append(get_data(data_path+'/'+str(i)+'.txt',type_))
    images = [data[i:i + window_length] for i in range(len(data) - window_length + 1)]
    lab = [get_image_label(i,i+window_length,labels) for i in range(start_frame,end_frame - window_length+2)]

    i=0
    No_action_count = 100
    while i <len(lab):
        if lab[i] is None:
            del lab[i]
            del images[i]
        elif lab[i] == 'No-Action':
            # if No_action_count <= 0:
                del lab[i]
                del images[i]
            # else:
            #     No_action_count -= 1
            #     i+=1
        else:
            i+=1
    i = 0
    images_aug=[]
    while i < len(images):
        jump = False
        new_image=[]
        for x in images[i]:
            if x is None or not x.shape==(25,3):
                    del lab[i]
                    del images[i]
                    jump = True
                    break
            else:
                new_image.append(x * [1,1,-1])
        if not jump:
            i += 1
            images_aug.append(new_image)
            # lab.append(lab[i])
    # images.extend(images_aug)
    return np.asarray(images),np.asarray(lab),[get_sequence_energy(x) for x in images]

def transform_nassim(data_path,label_path,out_path):
    images, labels, weights = to_nassim(data_path, get_labels(label_path), window_length=10,type_='foot')
    data = []
    lab = []
    for i in range(len(images)):
        path = join(out_path,labels[i])
        if not exists(path):
            mkdir(path)
        data.append(transform_image_ludl(images[i],path,str(i),weights[i]))
        lab.append(actions.index(labels[i]))

    data = np.asarray(data)
    labels = np.asarray(lab)
    return data , labels

data_path='data'
train_path = 'Train_OAD_40_base'
test_path = 'Test_OAD_40_base'
if not exists(train_path):
    mkdir(train_path)
if not exists(test_path):
    mkdir(test_path)
train_sub = [1, 2, 3, 4, 7, 8, 9, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 32, 33, 34, 35, 37, 38, 39, 49, 50, 51, 54, 57, 58]
test_sub  = [0, 10, 13, 17, 21, 26, 27, 28, 29, 36, 40, 41, 42, 43, 44, 45, 52, 53, 55, 56]
train = None
train_label = None
test = None
test_label = None
for i in range(59):
    path = join(data_path, str(i))
    label_path = join(path,'label','label.txt')
    image_path = join(path,'skeleton')
    print('Processing sequence num ===========>',i)
    data, label  = transform_nassim(image_path, label_path, train_path if i in train_sub else test_path)
    if i in train_sub:
        if train_sub.index(i)==0:
            train = data
            train_label = label
        else:
            train = np.concatenate([train, data])
            train_label = np.concatenate([train_label, label])
    elif i in test_sub:
        if test_sub.index(i)==0:
            test = data
            test_label = label
        else:
            test = np.concatenate([test,data])
            test_label = np.concatenate([test_label,label])
#
# from keras.utils.np_utils import to_categorical
# test_label = to_categorical(test_label)
# train_label = to_categorical(train_label)
# test_label=test_label[:,1:]
# train_label=train_label[:,1:]
# np.save('train_x_{}_base_one_by_one.npy'.format(rho),train)
# np.save('test_x_{}_base_one_by_one.npy'.format(rho),test)
# np.save('train_y_{}_base_one_by_one.npy'.format(rho),train_label)
# np.save('test_y_{}_base_one_by_one.npy'.format(rho),test_label)

Y = np.argmax(train_label,axis=1)
print(Y.shape)
unique, counts = np.unique(Y, return_counts=True)
print(dict(zip(unique, counts)))

Y = np.argmax(test_label,axis=1)
print(Y.shape)
unique, counts = np.unique(Y, return_counts=True)
print(dict(zip(unique, counts)))
print(train.shape,train_label.shape,test.shape,test_label.shape)
#29126,)
# (23912,)


def parser(l, r):
    if all(S[i].isdigit() for i in range(l, r + 1)):
        return int(S[l:r + 1]) // 2 + 1
    ret = []
    cnt = 0
    start = 0
    for i in range(l, r + 1):
        if S[i] == '[':
            cnt += 1
            if cnt == 1:
                start = i
        elif S[i] == ']':
            if cnt == 1:
                ret.append(parser(start + 1, i - 1))
            cnt -= 1
    ret.sort()
    return sum(ret[:len(ret) // 2 + 1])

N = int(input())
for _ in range(N):
    S = input()
    print(parser(0, len(S) - 1))


#To Calcculate the Roots for Quadratic Equation

import cmath

num1 = int(input("Enter the first number:"))#Take three numbers from user as num1,num2,num3
num2 = int(input("Enter the Second number:"))
num3 = int(input("Enter the Third number:"))

def Quadratic(num1, num2, num3):#Defining function
    delta = (num2 ** 2) - (4 * num1 * num3)#Calculating delta by using formula
    Root1 = (-num2 + cmath.sqrt(delta)) / (2 * num1)#Calculating Root1 and Root2 for three numbers
    Root2 = (-num2 - cmath.sqrt(delta)) / (2 * num1)
    print('The Roots are {0} and {1}'.format(Root1, Root2))#Display the result by Using format function to calculating the complex numbers

Quadratic(num1, num2, num3)


import csv
from utils import DateCounter

def pad(filename: str):
    #---------------read_in---------------
    data = []
    with open(filename, mode='r') as file:
        reader = csv.reader(file)
        for row in reader:
            data.append(row)
    #---------------padding---------------
    newdata = []
    newdata.append(data[0])
    for n in range(1, len(data)-1):
        counter = DateCounter(data[n][1])
        counter.count()
        # print(counter.current_date())
        if (data[n][0] != data[n+1][0]) or (counter.current_date() == data[n+1][1]):  # 用户变更，或日起连续，不需要补齐
            newdata.append(data[n])
        else:
            newdata.append(data[n])
            while counter.current_date() != data[n+1][1]:
                newdata.append(data[n].copy())
                newdata[-1][1] = counter.current_date()
                counter.count()
    #--------------write_back--------------
    with open(filename, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(newdata)


import itertools
import logging

from django.conf import settings
from django.core.management.base import BaseCommand

from autoslug.utils import slugify

from rainboard.models import (
    Forge,
    Namespace,
    Project,
    Robotpkg,
    update_github,
    update_gitlab,
)

class Command(BaseCommand):
    help = "run project creation stuff"  # noqa: A003

    def add_arguments(self, parser):
        parser.add_argument("org")
        parser.add_argument("project")

    def handle(self, org, project, *args, **options):  # noqa: C901
        path = settings.RAINBOARD_RPKG
        logger = logging.getLogger("rainboard.management.project")

        org = Namespace.objects.get(slug=org)
        slug = slugify(project)
        logger.warning("looking for %s / %s", org, slug)

        project = Project.objects.filter(slug=slug)

        if project.exists():
            logger.warning("found %s", project.get())
        else:
            logger.warning("not found. let's get it from github & gitlab")
            github = Forge.objects.get(slug="github")
            for data in github.api_list(f"/orgs/{org.slug}/repos"):
                if slugify(data["name"]) == slug:
                    logger.warning("found on github / %s", org)
                    update_github(github, org, data)
                    break
            for user in Namespace.objects.filter(group=False):
                for data in github.api_list(f"/users/{user.slug}/repos"):
                    if slugify(data["name"]) == slug:
                        logger.warning("found on github / %s", user)
                        update_github(github, user, data)
                        break
            gitlab = Forge.objects.get(slug="gitlab")
            for data in gitlab.api_list("/projects"):
                if slugify(data["name"]) == slug:
                    logger.warning("found on gitlab / %s", data["namespace"]["name"])
                    update_gitlab(gitlab, data)

        project = Project.objects.get(slug=slug)

        for slug in [project.slug, project.slug.replace("_", "-")]:
            for pkg in itertools.chain(
                path.glob(f"*/{slug}{project.suffix}"),
                path.glob(f"*/py-{slug}{project.suffix}"),
            ):
                obj, created = Robotpkg.objects.get_or_create(
                    name=pkg.name,
                    category=pkg.parent.name,
                    project=project,
                )
                if created:
                    logger.warning("found on robotpkg %s", obj)
                    obj.update(pull=False)

        for rpkg in project.robotpkg_set.all():
            logger.warning("updating images for %s", rpkg)
            rpkg.update_images()

        logger.warning("Done")