from contextlib import contextmanager as _contextmanager

from fabric.api import env, cd, run, prefix
from fabric.context_managers import settings
from fabric.operations import sudo

env.hosts = ['reddyprasad.me']

django_collectstatic_prompt = 'Type \'yes\' to continue, or \'no\' to cancel: '

@_contextmanager
def virtualenv():
    with prefix('source ~/.envs/blog/bin/activate'):
        yield

def bootstrap():
    env.user = 'ubuntu'

    sudo('apt update && apt upgrade')
    sudo('apt install python-virtualenv python-pip nginx')
    sudo('pip install --upgrade pip')
    run('mkdir -p apps')
    run('mkdir -p .envs')
    with cd('.envs'):
        run('virtualenv blog')
    with cd('apps'):
        run('git clone https://github.com/dev-drprasad/my_blog.git')

def pull():
    env.user = 'ubuntu'
    with cd('apps'):
        with cd('my_blog'):
            run('git pull')

            with virtualenv():
                run('pip install --upgrade pip')
                run('pip install -r requirements.txt')
                with cd('src'):
                    run('python manage.py migrate')
                    with settings(prompts={django_collectstatic_prompt: 'yes'}):
                        run('python manage.py collectstatic --settings=project.settings.production')


import functools

import graphviz as gv

import gvboost
import pyutils.func as func
import pyutils.graph as graph_util
import styles
import visualize.actions_labels as labels
from abstractir.actions import *
from abstractir.pstree import ProcessTreeConcept

class VisualizeOptions(object):
    def __init__(self,
                 output_file=None,
                 output_type='svg',
                 layout_dir='LR',
                 engine='dot',
                 do_show=False):
        self.output_file = output_file
        self.output_type = output_type
        self.layout_dir = layout_dir
        self.engine = engine
        self.do_show = do_show

def make_gv_graph(graph,
                  vis_opts,
                  base_graph_attr=styles.BASE_GRAPH_ATTRS,
                  base_node_attr=styles.BASE_NODE_ATTRS,
                  base_edge_attr=styles.BASE_EDGE_ATTRS,
                  clusterer_function=lambda _: None,
                  cluster_attr_factory=lambda _: {},
                  node_label_factory=lambda _: "",
                  node_attr_factory=lambda node: {},
                  edge_attr_factory=lambda edge: {}):
    """ Builds graphviz dot graph from given objects graph (GraphInterface)

    :param graph: graph to draw
    :type graph: graph_util.GraphInterface
    :param vis_opts: visualize options
    :type vis_opts: VisualizeOptions
    :param base_edge_attr: default graph edge attributes
    :param base_node_attr: default graph node attributes
    :param base_graph_attr: default graph attributes
    :param clusterer_function: function, which gives cluster id for specified vertex/node
    :param cluster_attr_factory: function, which returns cluster graph attrs for given cluster id
    :param node_label_factory: function, which returns string label for given node
    :param node_attr_factory: function, which returns attributes dictionary for given node
    :param edge_attr_factory: function, which returns edge attributes dictionary for given edge

    :return Dot Graph
    """

    gv_builder = gvboost.GraphVizBuilder(graph_attr=base_graph_attr,
                                         node_attr=base_node_attr,
                                         edge_attr=base_edge_attr)

    for node in graph.vertices_iter:
        cluster_id = clusterer_function(node)
        if cluster_id is not None and not gv_builder.has_cluster(cluster_id):
            gv_builder.cluster(cluster_id, graph_attr=cluster_attr_factory(cluster_id))

        gv_builder.node(node,
                        label=node_label_factory(node),
                        cluster_id=cluster_id,
                        node_attr=node_attr_factory(node))

    for edge in graph.edges_iter:
        gv_builder.edge(edge[0], edge[1], edge_attr=edge_attr_factory(edge))

    return gv_builder.build_gv_graph(g_format=vis_opts.output_type, engine=vis_opts.engine)

def render_actions_graph(actions_graph,
                         do_process_cluster=False,
                         node_buckets=None,
                         vis_opts=None):
    """ Renders actions graph to

    :param actions_graph: actions graph
    :type actions_graph: graph_util.DirectedGraph
    :param do_process_cluster: adds actions clusters by action executor
    :param node_buckets: dict from depth to list of vertices, which encodes vertices buckets
    :param vis_opts: visualisation options
    :type vis_opts: VisualizeOptions
    """

    vis_opts = vis_opts if vis_opts else VisualizeOptions()

    cluster_fun = func.val_returner(None)
    cluster_attr_factory = func.val_returner({})

    if node_buckets:
        reverse_buckets = {v: k for k, vs in node_buckets.iteritems() for v in vs}

        def cluster_fun(node): return reverse_buckets[node]

        def cluster_attr_factory(cluster):
            return {
                'style': 'bold, dashed, rounded, filled',
                'color': 'blue'
            }

    if do_process_cluster:
        def cluster_fun(node): return get_action_executor(node)

        def cluster_attr_factory(cluster):
            return {
                'style': 'bold, dashed, rounded, filled',
                'color': 'blue'
            }

    gv_graph = make_gv_graph(actions_graph,
                             vis_opts,
                             clusterer_function=cluster_fun,
                             cluster_attr_factory=cluster_attr_factory,
                             node_label_factory=labels.get_action_vertex_label,
                             node_attr_factory=styles.get_action_node_style)

    _save_and_show(gv_graph, vis_opts, show_tmp_suffix="actions-graph")

def render_pstree(process_tree,
                  vis_opts=None,
                  skip_tmp_resources=False,
                  draw_fake_root=False):
    """ Renders process tree

    :param process_tree: process tree (ProcessTreeConcept)
    :type process_tree: ProcessTreeConcept
    :param vis_opts: visualization options
    :type vis_opts: VisualizeOptions
    :param skip_tmp_resources: if True, no temporary resources rendered
    :param draw_fake_root: if True, then process tree root is drawn
    """
    from process_label import get_proc_label

    if draw_fake_root:
        filtered_pstree = process_tree
    else:
        filtered_pstree = graph_util.VertexFilteredGraph(process_tree,
                                                         vertex_filter=lambda v: v != process_tree.root_process)

    gv_graph = make_gv_graph(filtered_pstree,
                             vis_opts=vis_opts,
                             base_node_attr=styles.get_process_node_style(),
                             node_label_factory=functools.partial(get_proc_label, no_tmp=skip_tmp_resources))

    _save_and_show(gv_graph, vis_opts, show_tmp_suffix="actions-list")

def render_actions_list(actions_list, vis_opts=None):
    """ Renders given actions list as a node sequence with arrows from i to i + 1

    :param actions_list: list of actions
    :param vis_opts: visualization options
    :type vis_opts: VisualizeOptions
    """
    graph = graph_util.make_chain_graph(actions_list)
    gv_graph = make_gv_graph(graph, vis_opts,
                             node_label_factory=labels.get_action_vertex_label,
                             node_attr_factory=styles.get_action_node_style)

    _save_and_show(gv_graph, vis_opts, show_tmp_suffix="actions-list")

def render_actions_cycle(cycle, vis_opts):
    """ Renders given actions list as a cycle

    :param cycle: list of actions
    :param vis_opts: visualization options
    :type vis_opts: VisualizeOptions
    """

    graph = graph_util.make_cycle_graph(cycle)
    vis_opts.engine = 'circo'
    gv_graph = make_gv_graph(graph, vis_opts,
                             node_label_factory=labels.get_action_vertex_label,
                             node_attr_factory=styles.get_action_node_style)

    _save_and_show(gv_graph, vis_opts, show_tmp_suffix="actions-cycle")

def _save_and_show(gv_graph, vis_opts, show_tmp_suffix="tmp-graph"):
    """
    :type gv_graph: gv.dot.Dot
    :type vis_opts: VisualizeOptions
    """

    if vis_opts.output_file:
        gv_graph.render(filename=vis_opts.output_type)

    if not vis_opts.output_file or vis_opts.do_show:
        gvboost.show_gv_graph(gv_graph, show_tmp_suffix)


#Создай собственный Шутер!

from pygame import *
from random import *
from time import time as timer

class GameSprite (sprite.Sprite):
    def __init__ (self, player_image, player_x, player_y, size_x, size_y, player_speed):
        super().__init__()
        #каждый спрайт должен хранить свойство image - изображение
        self.image = transform.scale(image.load(player_image), (size_x, size_y))
        self.speed = player_speed
        #каждый спрайт должен хранить свойство rect - прямоугольник, в который он вписан
        self.rect = self.image.get_rect()
        self.rect.x = player_x
        self.rect.y = player_y

    def reset (self):
        window.blit(self.image,(self.rect.x, self.rect.y))

class Player(GameSprite):
    def update(self):
        keys = key.get_pressed()
        if keys[K_LEFT] and self.rect.x > 5:
            self.rect.x -= self.speed
        if keys[K_RIGHT] and self.rect.x < width - 50:
            self.rect.x += self.speed
        '''if keys[K_UP] and self.rect.y > 5:
            self.rect.y -= self.speed
        if keys[K_DOWN] and self.rect.y < height - 50:
            self.rect.y += self.speed'''

    def fire (self):
        bullet = Bullet('bullet.png', self.rect.centerx, self.rect.top, 15, 20, -15)
        bullets.add(bullet)

class Enemy (GameSprite):
    def update(self):
        self.rect.y += self.speed
        global lost
        if  self.rect.y > height:
            self.rect.y = 0
            self.rect.x = randint(50, width-50)
            lost = lost + 1

class Bullet (GameSprite):
    def update(self):
        self.rect.y += self.speed
        if  self.rect.y > height:
            self.kill()

#окно
width = 700
height = 500
window = display.set_mode((width, height))
display.set_caption("Шутер")
background = transform.scale(image.load('galaxy.jpg'), (700, 500))
run = True
finish = False
rel_time = False
num_fire = 0
FPS = 60
count = 0
life = 3
font.init()
font1 = font.SysFont('Arial', 36)

win = font1.render('Ты выйграл!', True, (255, 255, 255))
lose = font1.render('Ты проиграл!', True, (255, 0, 0))

#музыка
mixer.init()
mixer.music.load('space.ogg')
mixer.music.play()
lost = 0
player = Player('rocket.png', width/2, height-80, 65, 65, 10)
bullets = sprite.Group()
fire_sound = mixer.Sound('fire.ogg')

asteroids = sprite.Group()
for i in range (1, 6):
    asteroid = Enemy('asteroid.png', randint(50, width-50), -40, 80, 50, randint (1,7))
    asteroids.add(asteroid)

monsters = sprite.Group()
for i in range (1, 6):
    monster = Enemy('ufo.png', randint(50, width-50), -40, 80, 50, randint (1,7))
    monsters.add(monster)

font.init()
font1 = font.SysFont('Arial', 36)

while run:
    for e in event.get():
        if e.type == QUIT:
            run = False
        elif e.type == KEYDOWN:
            if e.key == K_SPACE:

                if num_fire < 5 and rel_time == False:
                    num_fire += 1
                    player.fire()
                    fire_sound.play()

                if num_fire >= 5 and rel_time == False:
                    last_time = timer()
                    rel_time = True

    if finish != True:
        window.blit(background, (0,0))

        text_win = font1.render('Счёт: ' + str(count), 1, (255, 255, 255))
        window.blit(text_win, (10, 20))

        text_lose  =  font1.render('Пропущено: ' + str(lost), 1, (255, 255, 255))
        window.blit(text_lose, (10, 50))

        text_life  =  font1.render('Жизней: ' + str(life), 1, (255, 255, 255))
        window.blit(text_life, (10, 80))

        bullets.update()
        player.update()
        monsters.update()
        asteroids.update()
        player.reset()
        monsters.draw(window)
        asteroids.draw(window)
        bullets.draw(window)

        if rel_time == True:
            now_time = timer()

            if now_time - last_time < 3:
                text_reload = font1.render('Идёт перезагрузка... ', 1, (255, 255, 255))
                window.blit(text_reload, (250, 350))
            else:
                num_fire = 0
                rel_time = False

        collides = sprite.groupcollide(monsters, bullets, True, True)
        for c in collides:
            count = count + 1
            monster = Enemy('ufo.png', randint(50, width-50), -40, 80, 50, randint (1,7))
            monsters.add(monster)

        '''если коснулись'''
        if sprite.spritecollide(player, monsters, False) or sprite.spritecollide(player, asteroids, False):
            sprite.spritecollide(player, monsters, True)
            sprite.spritecollide(player, asteroids, True)
            life -= 1

        '''если проиграли'''
        if life == 0 or lost > 10:
            finish = True
            window.blit(lose, (200, 200))
        '''победа'''
        if count >= 10:
            finish = True
            window.blit(win, (200, 200))

    display.update()
    time.delay(50)


from abc import ABC, abstractmethod

import Levenshtein
import networkx as nx

class GraphAnalyzer(ABC):
    def __init__(self, directory_path, output_file_path):
        self.directory_path = directory_path
        self.graph = None
        self._generate_and_load_graph(output_file_path)

    # Abstract methods
    @abstractmethod
    def _generate_and_load_graph(self, output_filename):
        pass

    # Private helper methods
    def _check_node_exists(self, node_name):
        if node_name not in self.graph:
            raise ValueError(f"Node with name '{node_name}' not found in the graph.")

    def _generate_hierarchical_structure(self, node, graph, visited=None):
        if visited is None:
            visited = set()
        if node in visited:
            return {node: "CYCLE"}
        visited.add(node)
        structure = {}
        for successor in graph.successors(node):
            structure[successor] = self._generate_hierarchical_structure(
                successor, graph, visited.copy()
            )
        return structure

    # Graph manipulation methods
    def set_graph(self, graph):
        self.graph = graph

    # Node relationship methods
    def get_children(self, node_name):
        self._check_node_exists(node_name)
        return list(self.graph.successors(node_name))

    def get_parents(self, node_name):
        self._check_node_exists(node_name)
        return list(self.graph.predecessors(node_name))

    def get_children_by_depth(self, node_name, depth):
        if depth < 1:
            return []
        children = self.get_children(node_name)
        for child in list(children):
            children.extend(self.get_children_by_depth(child, depth - 1))
        return list(set(children))

    def get_parents_by_depth(self, node_name, depth):
        if depth < 1:
            return []
        parents = self.get_parents(node_name)
        for parent in list(parents):
            parents.extend(self.get_parents_by_depth(parent, depth - 1))
        return list(set(parents))

    # Node search and representation methods
    def search_by_node_name(self, node_name):
        if node_name in self.graph:
            return {"name": node_name, "attributes": self.graph.nodes[node_name]}
        return None

    def fuzzy_search_by_node_name(self, search_term):
        """
        Fuzzy search for nodes by name or attributes using Levenshtein distance.

        Parameters:
            - search_term (str): The term to search for.

        Returns:
            - List of tuples where each tuple contains a node name and its distance to the search term.
              Returns the top 3 nodes with the smallest distances.
        """
        distances = []

        for node, attributes in self.graph.nodes(data=True):
            # Check distance with node name
            node_distance = Levenshtein.distance(node, search_term)
            distances.append((node, node_distance))

            # Check distance with node attributes
            for attribute, value in attributes.items():
                if isinstance(value, str):
                    attr_distance = Levenshtein.distance(value, search_term)
                    distances.append((node, attr_distance))

        # Sort by distance and pick the top 3 nodes
        distances.sort(key=lambda x: x[1])
        return distances[:3]

    def represent_node_hierarchy(
        self, node, child_levels=None, parent_levels=None, visited=None
    ):
        if visited is None:
            visited = set()
        if node in visited:
            return {node: "CYCLE"}
        visited.add(node)

        structure = {}

        if parent_levels is not None:
            structure["parents"] = self._get_parents_structure(
                node, parent_levels, visited.copy()
            )

        if child_levels is not None:
            structure["children"] = self._get_children_structure(
                node, child_levels, visited.copy()
            )

        # Filter out empty keys for clarity
        return {node: {k: v for k, v in structure.items() if v}}

    def _get_parents_structure(self, node, levels, visited):
        if levels == 0:
            return {}

        parents_structure = {}
        for parent in self.graph.predecessors(node):
            parents_structure[parent] = self.represent_node_hierarchy(
                parent,
                child_levels=None,
                parent_levels=(levels - 1),
                visited=visited.copy(),
            )

        return parents_structure

    def _get_children_structure(self, node, levels, visited):
        if levels == 0:
            return {}

        children_structure = {}
        for child in self.graph.successors(node):
            children_structure[child] = self.represent_node_hierarchy(
                child,
                child_levels=(levels - 1),
                parent_levels=None,
                visited=visited.copy(),
            )

        return children_structure

    def generate_text_representation(self, graph):
        hierarchical_representations = {}
        for node in graph.nodes():
            if not list(graph.predecessors(node)):
                hierarchical_representations[
                    node
                ] = self._generate_hierarchical_structure(node, graph)
        return hierarchical_representations

    # Graph generation methods
    def _generate_graph_by_attribute(self, attribute):
        new_graph = nx.DiGraph()
        for node, attributes in self.graph.nodes(data=True):
            current_attr = attributes.get(attribute)
            if not current_attr:
                continue
            if current_attr not in new_graph:
                new_graph.add_node(current_attr)
            for child in self.graph.successors(node):
                child_attr = self.graph.nodes[child].get(attribute)
                if child_attr and child_attr != current_attr:
                    new_graph.add_edge(current_attr, child_attr)
        return new_graph


import concurrent.futures
import logging
import time
import grpc

from . import helloworld_pb2
from . import helloworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name.title())

def serve():
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executer:
        server = grpc.server(executer)
        helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
        server.add_insecure_port("[::]:50051")
        server.start()

        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            server.stop(0)

if __name__ == "__main__":
    logging.basicConfig()
    serve()


from django.urls import path
from . import views

urlpatterns = [
    path("signup/", views.UserSignup.as_view(), name="user-signup"),
    path("signin/", views.UserSignin.as_view(), name="user-signin"),
    path("profile/", views.MyProfile.as_view(), name="user-profile"),
    path("profile/<username>/", views.UserProfile.as_view(), name="user-profile"),
    path("logout/", views.UserLogout.as_view(), name="user-logout"),
    path("follow/", views.UserRelation.as_view(), name="relations"),
    path("posts/", views.Posts.as_view(), name="posts"),
    path("posts/<int:page>/<int:offset>/", views.Posts.as_view(), name="posts"),
    path("posts/<int:page>/<int:offset>/<username>/", views.Posts.as_view(), name="my-posts"),
    path("test/", views.test, name="test")
]


"""
100 prisoners go into a room, each is numbered, in the room
is a series of draws with their numbers randomly shuffled in them.
Find a strategy where there is good odds of them all getting
their number.
"""
import math
import itertools

def tiled_is_valid_perm(perm):
    n = len(perm)
    assert n % 2 == 0
    half = n // 2

    def is_idx_valid(i):
        for j in range(half):
            if i == perm[(i + j) % n]:
                return True
        return False

    return all(is_idx_valid(i) for i in perm)

def two_groups_is_valid_perm(perm):
    n = len(perm)
    assert n % 2 == 0
    half = n // 2

    def is_idx_valid(i):
        if i < half:
            return i in perm[:half]
        else:
            return i in perm[half:]

    return all(is_idx_valid(i) for i in perm)

# fat_tiled
def double_tiled_is_valid_perm(perm):
    n = len(perm)
    assert n % 2 == 0
    half = n // 2

    def is_idx_valid(i):
        start = i - i % 2
        for j in range(half):
            if i == perm[(start + j) % n]:
                return True
        return False

    return all(is_idx_valid(i) for i in perm)

# # Something like lots of tranpositions
# def is_valid_perm(perm):
#     n = len(perm)
#     assert n % 2 == 0
#     half = n // 2

#     def is_idx_valid(i):
#         start = i - i % 2
#         found = False
#         for j in range(half):
#             if i == perm[(start + j) % n]:
#                 found = True
#         return found

#     return all([is_idx_valid(i) for i in perm])

def transform_perm(perm):
    return [x + 1 for x in perm]

if __name__ == "__main__":
    # is_valid_perm(range(6))
    ns = [4, 6, 8, 10]
    for n in ns:
        nums = list(range(n))
        perms = itertools.permutations(nums)
        num_valid_perms = sum(1 for perm in perms if is_valid_perm(perm))
        prob = num_valid_perms / math.factorial(n)
        print(f"n: {n} num valid perms: {num_valid_perms} prob {prob:.6f}")

    # nums = list(range(6))
    # perms = itertools.permutations(nums)
    # valid_perms = [perm for perm in perms if is_valid_perm(perm)]
    # valid_perms = [transform_perm(perm) for perm in valid_perms]
    # for perm in valid_perms:
    #     print(perm)


from django.shortcuts import render
from django.http import Http404
from django.shortcuts import get_list_or_404
from .models import Livre
from categorie.models import Categorie
import re

# Create your views here.

def listLivre(request):

    listLivre = Livre.objects.all()
    context = {
        'listLivre':listLivre ,
    }

    return render(request , 'index.html' , context)

def detLivre(request , id):

    try:
        if request.session['idcl'] != None:
            detLivre = Livre.objects.get(id=id)
            context = {
                'detLivre':detLivre ,
            }
            return render(request , 'details.html' , context)

    except KeyError:
        return render(request, 'signin.html')

def LivreCat(request , id):

    cat = Categorie.objects.get(id=id)
    listLivre = Livre.objects.filter(categorie = cat)
    #cat = Categorie.objects.get(id=idcat)
    context = {
      'listLivre':listLivre,
      'cat':cat,
    }
    return render(request, 'Categorie.html', context)

def Search(request):
    mot = request.POST.get('search')

    if mot:
        results = []
        article_list = get_list_or_404(Livre)
        for article in article_list:
            if re.findall(mot, article.titre):
                results.append(article)
        '''for article in results:
            article.body = markdown.markdown(article.body, )
        tag_list = Tag.objects.all().order_by('name')'''

        return render(request, 'search.html', {'article_list': results})
    else:
        return listLivre(request)


import pytest
from airbyte_cdk.models.airbyte_protocol import AdvancedAuth, ConnectorSpecification
from airbyte_cdk.sources.declarative.models.declarative_component_schema import AuthFlow
from airbyte_cdk.sources.declarative.spec.spec import Spec

@pytest.mark.parametrize(
    "test_name, spec, expected_connection_specification",
    [
        (
            "test_only_connection_specification",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}),
            ConnectorSpecification(connectionSpecification={"client_id": "my_client_id"}),
        ),
        (
            "test_with_doc_url",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}, documentation_url="https://airbyte.io"),
            ConnectorSpecification(connectionSpecification={"client_id": "my_client_id"}, documentationUrl="https://airbyte.io"),
        ),
        (
            "test_auth_flow",
            Spec(connection_specification={"client_id": "my_client_id"}, parameters={}, advanced_auth=AuthFlow(auth_flow_type="oauth2.0")),
            ConnectorSpecification(
                connectionSpecification={"client_id": "my_client_id"}, advanced_auth=AdvancedAuth(auth_flow_type="oauth2.0")
            ),
        ),
    ],
)
def test_spec(test_name, spec, expected_connection_specification):
    assert spec.generate_spec() == expected_connection_specification


import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

# =========================================================================
# Используя программу задачи  2.1. , найти решения задач  Коши  для  ОДУ
# 1 порядка (2.1) и (2.2)  на отрезке   с заданной точностью .  Построить
# графики решений и найти наибольшую площадь, заключенную между интегральными
# кривыми.
# (2.1) y' = k(A - y)(y - B)              ; y(0) = y[0]
# (2.2) y' = k(A - z)(z - B) - C*sin(t/w) ; z(0) = z[0] = y[0]

# ==========================[Global Variables]=============================

y0 = 58
T = 40
A = 60
B = 18
C = 3
w = 3
K = 0.04
t0 = 0

eps = 10 ** (-8)

# ==========================[Global Functions]=============================

def f1(y, t):
    return K * (A - y) * (y - B)

def f2(z, t):
    return K * (A - z) * (z - B) - C * np.sin(t / w)

def Runge(first, second, p):
    return abs((first - second) / ((2 ** p) - 1))

def Taylor(y0, t0, h, f, dt, dy):
    return y0 + h * f(y0, t0) + ((h ** 2) / 2) * (dt(y0, t0) + dy(y0, t0) * f(y0, t0))

def TaylorCalculate(y0, t0, h, f, T, dt, dy):
    x = np.arange(t0, T + h, h)
    quantity = x.size
    prev = y0
    array = np.zeros(quantity)
    array[0] = y0

    for i in range(0, quantity - 1):
        prev = Taylor(prev, t0, h, f, dt, dy)
        t0 += h
        array[i + 1] = prev

    return array, x

# ==============================[Task 2.2]=================================
# Найти  приближенные решения задач (2.1) и (2.2).
# Построить графики полученных решений y(t) и z(t).

def dt_f1(y, t):
    return 0

def dy_f1(y, t):
    return 3.12 - 0.08 * y

def dt_f2(z, t):
    return -np.cos(t / 3)

def dy_f2(z, t):
    return 3.12 - 0.08 * z

h = 0.1

first = np.zeros(0)
first_h_div_2 = np.zeros(0)

first_num = 0
first_num_div_2 = 0
precise = 1.0

while (precise >= eps):
    first, first_num = TaylorCalculate(y0, t0, h, f1, T, dt_f1, dy_f1)
    h = h / 2
    first_h_div_2, first_num_div_2 = TaylorCalculate(y0, t0, h, f1, T, dt_f1, dy_f1)
    precision = np.zeros(first_num.size)

    for i in range(0, first_num.size - 1):
        precision[i] = Runge(first_h_div_2[i * 2], first[i], 2)

    precise = np.amax(precision)

print('==========[Task 2.2]==========')
print('Precision     :', precise)
print('Number of dots:', first_num_div_2.size)
print('Step          :', h)

second = np.zeros(0)
second_h_div_2 = np.zeros(0)

second_num = 0
second_num_div_2 = 0
precise = 1.0
h = 0.1

while (precise >= eps):
    second, second_num = TaylorCalculate(y0, t0, h, f2, T, dt_f2, dy_f2)
    h = h / 2
    second_h_div_2, second_num_div_2 = TaylorCalculate(y0, t0, h, f2, T, dt_f2, dy_f2)
    precision = np.zeros(second_num.size)

    for i in range(0, second_num.size - 1):
        precision[i] = Runge(second_h_div_2[i * 2], second[i], 2)

    precise = np.amax(precision)

print('==========[Task 2.2]==========')
print('Precision     :', precise)
print('Number of dots:', second_num_div_2.size)
print('Step          :', h)

x = np.linspace(t0, T + 1, 100, endpoint=True)
plt.plot(first_num_div_2, first_h_div_2, label="y(t)", color='black')
plt.plot(second_num_div_2, second_h_div_2, ls=':', label="z(t)", color='magenta')
plt.legend()
plt.grid('True')
plt.savefig("pic_4.png", dpi = 500)
plt.show()

x_plot = np.linspace(0, T, 100)

solution_1 = odeint(f1, y0, x_plot)
solution_2 = odeint(f2, y0, x_plot)

plt.plot(x_plot, solution_1, ls='-', label='y(t)')
plt.plot(x_plot, solution_2, ls=':', label='z(t)')
plt.legend()
plt.grid('True')
plt.savefig("pic_5.png", dpi = 500)
plt.show()

# ==============================[Task 2.3]=================================
# Вычислить приближенно площади между полученными кривыми на отрезке
# по квадратурной формуле индивидуального варианта ЛР 1

y_dots = np.zeros(0)
x_dots = np.zeros(0)
x_indexes = []
count = 0

# Находим точки пересечения

difference = first_h_div_2 - second_h_div_2
# True = -1 ; False = 1
sign = True

for i in range(1, difference.size):
    if difference[i] > 0 and sign:
        y_dots = np.append(y_dots, first_h_div_2[i])
        x_dots = np.append(x_dots, first_num_div_2[i])
        x_indexes.append(i)
        count += 1
        sign = False

    if difference[i] < 0 and not sign:
        y_dots = np.append(y_dots, first_h_div_2[i])
        x_dots = np.append(x_dots, first_num_div_2[i])
        x_indexes.append(i)
        count += 1
        sign = True

print('==========[Task 2.3]==========')
print('Number of intersections: ', count)
print('y axis coordinates     :', y_dots)
print('x axis coordinates     :', x_dots)
print('Indexes                :', x_indexes)

# Правило центральных треугольников
#
# def midpointRule(f, a, b, step):
#     answer = 0
#     n = int((b - a) / step)
#     for i in range(0, n):
#         answer += f(a + step * (i + 0.5)) * step
#     return answer

def midpointRule(y, a, b, step, start, end):
    answer = 0
    n = int((b - a) / step)
    for i in range(start + 1, end):
        answer += (y[i - 1] + y[i]) / 2
    return answer * step

areas = np.zeros(0)

for i in range(1, x_dots.size):
    one = midpointRule(first_h_div_2, x_dots[i - 1], x_dots[i], h, x_indexes[i - 1], x_indexes[i])
    two = midpointRule(second_h_div_2, x_dots[i - 1], x_dots[i], h, x_indexes[i - 1], x_indexes[i])

    areas = np.append(areas, abs(one - two))

print('==========[Max Area]==========')
print('Areas     :', areas)
print('Max. area :',np.amax(areas))


s = input()
t = []

for i in range(len(s)):
    if s[i] == '[' or s[i] == '(' or s[i] == '{':
        t.append(s[i])
    else:
        if len(t) == 0:
            print("No")
            exit()
        t_top = t[len(t)-1]
        if s[i] == ')' and t_top != '(' or s[i] == ']' and t_top != '[' or s[i] == '}' and t_top != '{':
            print("No")
            exit()
        t.pop()

if len(t) != 0:
    print("No")
else:
    print("Yes")


t = int(input())

while t > 0:

    gift_num = int(input())
    a = map(int, input().split())
    a = list(a)
    b = map(int, input().split())
    b = list(b)

    min_a = min(a)
    min_b = min(b)
    cont = 0

    for i in range(gift_num):
        if a[i] > min_a and b[i] > min_b:
            temp_a = a[i] - min_a
            temp_b = b[i] - min_b
            if temp_a == temp_b:
                a[i] -= temp_a
                b[i] -= temp_b
                cont += temp_b
            elif temp_a > temp_b:
                a[i] -= temp_b
                b[i] -= temp_b
                cont += temp_b
            elif temp_a < temp_b:
                a[i] -= temp_a
                b[i] -= temp_a
                cont += temp_a

        while a[i] > min_a or b[i] > min_b:
            if a[i] > min_a:
                temp = a[i] - min_a
                a[i] -= temp
                cont += temp
            elif b[i] > min_b:
                temp = b[i] - min_b
                b[i] -= temp
                cont += temp
    print(cont)

    t -= 1


import csv
import pandas as pd

df = pd.DataFrame(list())
df.to_csv('mean_for_each_genre.csv')

genre2id = {}
id2genre = {}
artist2genre = {}
genres = [""]

n = 0
with open('influence_data.csv') as file:
	reader = csv.reader(file)
	for row in reader:
		try:
			x = int(row[0])
			if not row[2] in genre2id:
				genre2id[row[2]] = n
				id2genre[n] = row[2]
				genres.append(row[2])
				n += 1
			artist2genre[row[1]] = genre2id[row[2]]
			artist2genre[row[5]] = genre2id[row[6]]
		except:
			pass

# print(artist2genre)

artist2id = {}
id2artist = {}
id2index = {}
index2id = {}

m = 0
with open('data_by_artist.csv') as file:
	reader = csv.reader(file)
	for row in reader:
		try:
			artist2id[row[0]] = int(row[1])
			id2artist[int(row[1])] = row[0]
			id2index[int(row[1])] = m
			index2id[m] = int(row[1])
			m += 1
		except:
			pass

genre_mean = [0] * n
genre_num = [0] * n
properties = [""]
for i in range(n):
	genre_mean[i] = [0] * 12
with open('full_music_data_transformed.csv') as file:
	reader = csv.reader(file)
	for row in reader:
		try:
			artists = row[0][1:len(row[0])-1]
			artists = artists.split(", ")
			# print(artists)
			for artistId in artists:
				if not id2artist[int(artistId)] in artist2genre:
					continue
				g = artist2genre[id2artist[int(artistId)]]
				genre_num[g] += 1
				for j in range(12):
					genre_mean[g][j] += float(row[j+1])
		except:
			print(row)
			for j in range(1,13):
				properties.append(row[j])

print(properties)
print(n)
for i in range(n):
	for j in range(12):
		genre_mean[i][j] /= genre_num[i]

print(genre_mean)

with open('mean_for_each_genre.csv', 'w', newline="") as file:
	writer= csv.writer(file)
	writer.writerow(properties)
	for i in range(n):
		newRow = genre_mean[i][0:12]
		newRow.insert(0, id2genre[i])
		# print(newRow)
		writer.writerow(newRow)


from setuptools import setup, find_packages
import os

here = os.path.abspath(os.path.dirname(__file__))

VERSION = "0.0.1"
DESCRIPTION = """
Simple Python Package
"""

setup(
    name="selenium_sequence",
    version=VERSION,
    author="TZ",
    author_email="zaptom.pro@gmail.com",
    description=DESCRIPTION,
    long_description_content_type="text/markdown",
    packages=find_packages(),
    install_requires=[
        "selenium",
        "flask",
        "colorama",
        "requests",
        # "indeed @ git+https://github.com/Tomizap/indeed.git#egg=indeed",
        # "linkedin @ git+https://github.com/Tomizap/linkedin.git#egg=linkedin"
        "tzmongo @ git+https://github.com/Tomizap/tzmongo.git#egg=tzmongo",
        "selenium_driver @ git+https://github.com/Tomizap/selenium_driver.git#egg=selenium_driver"],
    keywords=[],
    classifiers=[]
)


import json

# 아래 코드 수정 금지
movie_json = open("data/movie.json", encoding="UTF8")
movie = json.load(movie_json)

genres_json = open("data/genres.json", encoding="UTF8")
genres_list = json.load(genres_json)

# 이하 문제 해결을 위한 코드 작성

# movie는 dict, genres_list는 list 유형

this_movie_ids = movie['genre_ids']
result = []

for i in genres_list:
    if this_movie_ids[1] == i['id']:
        result.append(i['name'])
    if this_movie_ids[0] == i['id']:
        result.append(i['name'])

print(result)

# genre_list = []
# for genre_id in this_movie_ids:
    # for genre_dict in genre_list:
        # if genre_id == genre_dict['id']:
            # genre_list.append(genre_dict['name'])


#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt
import math
import sys
import random
import os
import subprocess
from operator import itemgetter
import glob

def instantF(T,s,d,v,N):
  ROUND=13
  if 0 < s and s <= math.sqrt(3)*d/4:
    de = 2*math.sqrt(d**2 - (2*s)**2)
    v1 = math.floor(round(v*T/de,ROUND))
    v2 = math.floor(round(v*T/de + 0.5,ROUND))
  else:
    v1 = math.floor(round(v*T/d,ROUND))
    v2 = math.floor(round(v*T/d+0.5,ROUND))
  f = (1./T)*(v1 + v2)
  return f

def plotInstantEquation(Tf,Ns,s,d,v,lbl,colour='brown'):
  Ys = [instantF(Tf[i],s,d,v,Ns[i]) for i in range(len(Tf))]
  plt.plot(Tf, Ys, label=lbl, color=colour,linestyle='--',alpha=0.8,marker='x')

def plotLimitEquation(Xf,s,d,v,lbl,lastStr,colour='magenta'):
  if 0 < s and s <= math.sqrt(3)*d/4:
    f = v/(d*math.sqrt(1-((2*s)/d)**2))
  else:
    f = 2*v/d
  Ys = [f]*len(Xf)
  plt.plot(Xf, Ys, label=lbl, color=colour)
  vv =  -0.05 if lastStr == 's=0.45' else 0.02
  plt.text(Xf[-1],Ys[-1]+vv,lastStr,horizontalalignment='right')

def funF(T,v,d,s):
  return instantF(T,s,d,v,0)

def main():
    startingRobot = [0,0]
    i = 2
    s = [0.3,0.45]
    d = [1]*i
    v = [1]*i
    paths = ["variousLogs0.3d1","variousLogs0.45d1"]
    algorithmLimitLabels = ['Asymptotic']*i
    algorithmInstantLabels = ['Instantaneous']*i
    lastPointTextAnnotation = ['s=0.3','s=0.45'  ]
    xAxisText = 'Time (s)'
    outputLabel = "Throughput (1/s)"
    Colour1 = ['#1f77b4']*i
    Colour4 = ['brown']*i

    plt.rcParams.update({'font.size': 15})

    for a in range(len(paths)):
      #Save all data from individual robots logs
      robotFiles = glob.glob(paths[a]+"/"+"/robot*")
      robotData = []
      for f in robotFiles:
        robotFile = open(f)
        dataFileStr = robotFile.readlines();
        data = []
        for i in range(4):
          data.append(int(dataFileStr[i]))
        for i in range(2):
          data.append(float(dataFileStr[4+i]))
        robotData.append(data)
      # Sort robot data by target arrival time
      robotDataSorted = sorted(robotData, key= itemgetter(3))

      st = startingRobot[a]
      V = range(2,len(robotDataSorted)+1,5)
      Ts = [(robotDataSorted[st+i-1][3] - robotDataSorted[st][3])/1e6 for i in V]
      Ns = [i   for i in V]
      Tp = [(Ns[i]-1.)/Ts[i] for i in range(len(Ts))]

      plt.plot(Ts,Tp,label='Simulation',color='green',marker='.')
      plotInstantEquation(Ts,Ns,s[a],d[a],v[a],algorithmInstantLabels[a],colour=Colour4[a])
      plotLimitEquation(Ts,s[a],d[a],v[a],algorithmLimitLabels[a],lastPointTextAnnotation[a],colour=Colour1[a])
    plt.legend(loc='center right');
    plt.xlabel(xAxisText);
    plt.ylabel(outputLabel);

    outFileName = "".join(filter(lambda i: i not in ["/",";","*"], outputLabel))
    plt.savefig(outFileName + ".pdf",bbox_inches="tight",pad_inches=0.01);
    plt.clf()

main();


# -*- coding = 'utf-8' -*-
"""

--------------------------------------------------------

File Name : evaluate

Description : 总的预测函数

Author : leiliang

Date : 2020/8/4 10:59 上午

--------------------------------------------------------

"""
import logging
from base_algorithm import BaseAlgorithm
from utils import transform_table_data_to_html, format_dataframe

log = logging.getLogger(__name__)

class predictModel(BaseAlgorithm):
    def __init__(self):
        BaseAlgorithm.__init__(self)
        self.get_config()
        if self.config["oneSample"]:
            self.table_data = None
        else:
            self.table_data = self.exec_sql(self.config['tableName'], self.config['X'], None)
        self.model = self.load_model_by_database(self.config['algorithm'], self.config['model'])

    def get_config(self):
        '''
            前端传过来的参数
        {
            "algorithm": "",
            "model": "",
            "oneSample": False,
            "table": "",
            "X": "",
        }
        :return:
        '''
        self.config = {}
        try:
            self.config['algorithm'] = self.web_data['algorithm']
            self.config['model'] = self.web_data['model']
            self.config['oneSample'] = self.web_data['oneSample']
            self.config['tableName'] = self.web_data.get('tableName', None)
            self.config['X'] = self.web_data.get('X')
        except Exception as e:
            log.info(e)
            raise e

    def model_predict(self):
        try:
            res = {}
            if self.config['oneSample']:
                if not self.config['X']:
                    raise ValueError("feature must not be empty when one-sample")
                X = [[float(x) for x in self.config['X']]]
                predict = self.model.predict(X)[0] if isinstance(self.model.predict(X)[0], str) else "{:.0f}".format(
                    self.model.predict(X)[0])
                res.update({
                    "data": [[",".join([str(s) for s in self.config['X']]), predict]],
                    "title": "单样本预测结果",
                    "col": ["样本特征", "模型预测结果"],
                })
            else:
                # 从数据库拿数据
                if not self.config['tableName'] or self.config['tableName'] == "":
                    raise ValueError("cannot find table data when predict many samples")
                data = self.table_data
                log.info("输入数据大小:{}".format(len(data)))
                data = data.astype(float)
                data["predict"] = self.model.predict(data.values)
                if data["predict"].dtypes != "object":
                    data = format_dataframe(data, {"predict": ".0f"})
                res.update(transform_table_data_to_html({
                    "data": data.values.tolist(),
                    "title": "多样本预测结果",
                    "col": data.columns.tolist(),
                    "row": data.index.tolist()
                }))
            response_data = {"res": res,
                             "code": "200",
                             "msg": "ok!"}
            return response_data
        except Exception as e:
            # raise e
            return {"data": "", "code": "500", "msg": "{}".format(e.args)}


# -*- coding: utf-8 -*-
"""
Write a program (function!) that takes a list and returns a new list that contains all the elements of
 the first list minus all the duplicates.

Extras:

Write two different functions to do this - one using a loop and constructing a list, and another using sets.
Go back and do Exercise 5 using sets, and write the solution for that in a different function.
"""

def removeDup1(list1):
    newList = []
    for x in list1:
        if not x in newList:
            newList.append(x)
    return newList

def removeDup2(list1):
    return set(list1)

a = [1,2,5,4,6,2,4,5,3,1,9,8,7,4,1]

print(removeDup1(a))
print(removeDup2(a))


# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date:   2019-11-26 17:22:56
# @Last Modified by:   ander
# @Last Modified time: 2019-11-27 21:45:52
from moviepy.editor import VideoFileClip, ColorClip, CompositeVideoClip, AudioFileClip
import moviepy.video.fx.all as vfx
from moviepy.video.fx.mask_color import mask_color
import time
import json

def tiktok_effect(frame):
	# 单独抽取去掉红色通道的图像
	gb_channel_frame = frame.copy()
	gb_channel_frame[:, :, 0].fill(0)

	# 单独抽取红色通道图像
	r_channel_frame = frame.copy()
	r_channel_frame[:, :, 1].fill(0)
	r_channel_frame[:, :, 2].fill(0)

	# 错位合并图像，形成抖音效果
	result = frame.copy()
	result[:-5, :-5, :] = r_channel_frame[:-5, :-5, :] + gb_channel_frame[5:, 5:, :]

	return result

def person_mask_effect(roi_clip, mask_clip, current_time, clip_start_time, clip_end_time):
	clip_duration = clip_end_time - clip_start_time
	red_clip = ColorClip(roi_clip.size, (255, 0, 0), duration=clip_duration)
	blue_clip = ColorClip(roi_clip.size, (0, 0, 255), duration=clip_duration)

	roi_clip = roi_clip.subclip(clip_start_time, clip_end_time)
	mask_clip = mask_clip.subclip(clip_start_time, clip_end_time)

	person_clip_height = int(HEIGHT * 0.9)

	center_person_clip = (
		roi_clip.fl_image(tiktok_effect)
		.set_mask(mask_clip)
		.resize(height=person_clip_height)
		.set_pos(("center", "center"))
		.set_start(current_time)
	)
	left_person_clip = (
		red_clip.set_mask(mask_clip)
		.resize(height=person_clip_height)
		.set_opacity(0.5)
		.set_start(current_time)
	)
	right_person_clip = (
		blue_clip.set_mask(mask_clip)
		.resize(height=person_clip_height)
		.set_opacity(0.5)
		.set_start(current_time)
	)

	left_person_clip_x = (WIDTH / 2 - left_person_clip.w / 2) - int(
		left_person_clip.w * 0.3
	)
	right_person_clip_x = (WIDTH / 2 - left_person_clip.w / 2) + int(
		left_person_clip.w * 0.3
	)
	person_clip_y = HEIGHT / 2 - left_person_clip.h / 2

	left_person_clip = left_person_clip.set_pos((left_person_clip_x, person_clip_y))
	right_person_clip = right_person_clip.set_pos((right_person_clip_x, person_clip_y))

	return [left_person_clip, right_person_clip, center_person_clip]

def pure_color_person_mask_effect(roi_clip, mask_clip, current_time, clip_start_time, clip_end_time):
	clip_duration = clip_end_time - clip_start_time
	white_clip = ColorClip(SIZE, (255, 255, 255), duration=clip_duration)

	mask_clip = mask_clip.subclip(clip_start_time, clip_end_time)

	person_clip_height = int(HEIGHT * 0.9)

	center_person_clip = (
		white_clip
		.set_mask(mask_clip.resize(height=person_clip_height))
		.set_pos(("center", "center"))
		.set_start(current_time)
	)

	background_color_clip = ColorClip(
		SIZE, (80, 40, 255), duration=clip_duration
	).set_start(current_time)

	return [
		CompositeVideoClip([background_color_clip, center_person_clip]).fl_image(
			tiktok_effect
		)
	]

with open('config.json', 'r', encoding='utf-8') as f:
	CONFIGS = json.load(f)
	WIDTH, HEIGHT = CONFIGS['width'], CONFIGS['height']
	SIZE = (WIDTH, HEIGHT)
	PURE_COLOR_EFFECT_TIMES = CONFIGS['special times']
	PERSON_CLIPS_FILENAMES = CONFIGS['person clip files']
	BACKGROUND_MUSIC = CONFIGS['bgm']
	BACKGROUND_VIDEO = CONFIGS['background video']

background_music = AudioFileClip(BACKGROUND_MUSIC)
final_clip_duration = background_music.duration

composite_clips = []
pure_color_effect_clips = []
current_time = 0

for person_clip_filename in PERSON_CLIPS_FILENAMES:
	roi_clip_filename = ".".join(person_clip_filename.split(".")[:-1]) + "_roi.avi"
	mask_clip_filename = ".".join(person_clip_filename.split(".")[:-1]) + "_mask.avi"

	roi_clip = VideoFileClip(roi_clip_filename).without_audio()
	mask_clip = (
		mask_color(VideoFileClip(mask_clip_filename), color=[255, 255, 255])
		.fx(vfx.loop, duration=roi_clip.duration)
		.to_mask()
	)

	clip_duration = roi_clip.duration

	person_mask_effect_clips = person_mask_effect(roi_clip, mask_clip, current_time, 0, clip_duration)
	composite_clips.extend(person_mask_effect_clips)
	pure_color_person_mask_effect_clips = pure_color_person_mask_effect(
		roi_clip, mask_clip, current_time, 0, clip_duration
	)
	pure_color_effect_clips.extend(pure_color_person_mask_effect_clips)
	current_time += clip_duration

pure_color_effect_clip = CompositeVideoClip(pure_color_effect_clips).fx(vfx.loop, duration=final_clip_duration)
pure_color_effect_subclips = []
for start_time, end_time in PURE_COLOR_EFFECT_TIMES:
	if start_time < final_clip_duration:
		subclip = pure_color_effect_clip.subclip(start_time, end_time).set_start(start_time)
		pure_color_effect_subclips.append(subclip)
	else:
		break
pure_color_effect_subclip = CompositeVideoClip(pure_color_effect_subclips)

background_clip = (
	VideoFileClip(BACKGROUND_VIDEO)
	.without_audio()
	.resize(SIZE)
	.fx(vfx.loop, duration=final_clip_duration)
)

composite_clips.insert(0, background_clip)

loop_clip = CompositeVideoClip(composite_clips).set_duration(
	min(current_time, final_clip_duration)
)
loop_clip_path = f'./Temp/{time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())}.mp4'
loop_clip.write_videofile(
	loop_clip_path,
	fps=30,
	codec='mpeg4',
	bitrate="8000k",
	threads=4,
)

loop_clip = VideoFileClip(loop_clip_path).fx(vfx.loop, duration=final_clip_duration)
final_clip = CompositeVideoClip([loop_clip, pure_color_effect_subclip])
final_clip = final_clip.set_audio(background_music).set_duration(final_clip_duration)
final_clip.write_videofile(
	f'./output/{time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())}.mp4',
	fps=30,
	codec='mpeg4',
	bitrate="8000k",
	audio_codec="libmp3lame",
	threads=4,
)


import time
# applying multithread
import threading

def cal_sqr(n):
    print("Calculated Square Number : ")
    for i in n:
        time.sleep(0.5)
        print('SQR : ', i*i)

def cal_cube(n):
    print("Calculated Cube of Numbers : ")
    for i in n:
        time.sleep(0.5)
        print("CUBE : ",i*i*i)

arr = [1,2,3,4,5]

t = time.time()
t1 = threading.Thread(target=cal_sqr,args=(arr,))
t2 = threading.Thread(target=cal_cube,args=(arr,))

t1.start()
t2.start()

t1.join()
t2.join()

print("Done In : ",time.time() - t)
print("Yah ! .... I am done my all work now .")


import numpy as np
import matplotlib.pyplot as plt
import elecLoader as eloader
import random

# no correlation in fitter...

cerpe = np.arange(0, 1500, 10)
dnum = len(cerpe)

def cerFunc(x, a, b, c):
    s2 = a + b*x + c*x**2
    if s2<0:
        return 0
    else:
        return np.sqrt(s2)

def loadCov(filename, num):
    row, col = 0, 0
    cov_mat = np.ones((num, num))
    with open(filename) as f:
        for lines in f.readlines():
            line = lines.strip("\n")
            data = line.split(" ")
            col = 0
            for i in data:
               cov_mat[row, col] = float(i)
               cov_mat[col, row] = float(i)
               col+=1
            row += 1

    return cov_mat

from scipy.linalg import eigh, cholesky
from scipy.stats import norm

def sample_corelation(filename, num, sampleSize):
    method = 'eigenvectors'

    num_sample = sampleSize

    cov = loadCov(filename, num)
    print(cov)

    x = norm.rvs(size=(num, num_sample))

    if method == 'cholesky':
        # Compute the Cholesky decomposition.
        c = cholesky(cov, lower=True)
    else:
        # Compute the eigenvalues and eigenvectors.
        evals, evecs = eigh(cov)
        # Construct c, so c*c^T = r.
        c = np.dot(evecs, np.diag(np.sqrt(evals)))

    y = np.dot(c, x)

    return y

def cerpe_sim(E, kC):
    return kC * eloader.getCerNPE(E)

def sctpe_sim(E, kA, kB, scale):
    return kA * eloader.getQPE(E, kB, scale)

def main():
    sampleSize = 1000
    sigma = sample_corelation("../rescov_gam+B12_kSimulationSct_kSimulationCer_kSeparate_fixeds0.txt", 3, sampleSize)

    c0, c1, c2 = -123.213, 3.39232, 2.53173e-3

    ymin, ymax = [], []
    for i in range(dnum):
        ymin.append(1000000)
        ymax.append(-100)

    for i in range(sampleSize):

        m_c0 = c0 + random.gauss(0, sigma[0, i])
        m_c1 = c1 + random.gauss(0, sigma[1, i])
        m_c2 = c2 + random.gauss(0, sigma[2, i])

        cersigma = []

        for i in cerpe:

            cersigma2 = cerFunc(i, m_c0, m_c1, m_c2)**2
            cersigma.append(np.sqrt(cersigma2))

        for n in range(dnum):
            if cersigma[n] < ymin[n]:
                ymin[n] = cersigma[n]
            if cersigma[n] > ymax[n]:
                ymax[n] = cersigma[n]

    ymin = np.array(ymin)
    ymax = np.array(ymax)

    best, nominal = [], []
    bc0, bc1, bc2 = -158.41, 4.333, 0.00181082
    for i in cerpe:
        cersigma2 = cerFunc(i, c0, c1, c2)**2
        best.append(np.sqrt(cersigma2))
        cersigma2 = cerFunc(i, bc0, bc1, bc2)**2
        nominal.append( np.sqrt(cersigma2))

    best = np.array(best)

    plt.fill_between(cerpe, ymin, ymax, color="lightskyblue", label=r"$1 \sigma$ zone")
    plt.plot(cerpe, nominal, "--", color="darkviolet", label="nominal")
    plt.plot(cerpe, best, "-", color="darkorange",  label="best fit")

    plt.legend(loc="upper left")

    plt.grid(True)
    plt.title("Electron NPE Sigma")
    plt.xlabel(r"cerenkov NPE")
    plt.ylabel(r"$\sigma_{NPE}$")

    plt.show()

if __name__ == "__main__":
    main()


# HACKERRANK
# https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem

import sys

n = int(input().strip())
c = [int(c_temp) for c_temp in input().strip().split(' ')]

position = 0
count = 0
while position != (n-1):
    if position!= (n-2) and c[position + 2] == 0:
        count += 1
        position += 2
    else:
        count += 1
        position += 1
print(count)


import numpy as np
import pandas as pd
import random
import csv
from sklearn import linear_model
from sklearn.metrics import r2_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from scipy import stats
import matplotlib.pyplot as plt

def split_data(data, prob):
	"""Split data into fractions [prob, 1 - prob]"""
	results = [], []
	for row in data:
		results[0 if random.random() < prob else 1].append(row)
	return results

def train_test_split(x, y, test_pct):
	"""Split the features X and the labels y into x_train, x_test and y_train, y_test
	designated by test_pct. A common convention in data science is to do a 80% training
	data 20% test data split"""
	data = zip(x, y)								# pair corresponding values
	train, test = split_data(data, 1 - test_pct)    # split the data set of pairs
	x_train, y_train = zip(*train)					# magical un-zip trick
	x_test, y_test = zip(*test)
	return x_train, x_test, y_train, y_test

features = ['unemployed', 'income', 'obesity', 'diabetes', 'one_km_sm', 'three_km_sm', 'one_km_ff', 'three_km_ff']
label = 'zip_code'

def MultipleLinearRegression(X, y, linear_model):

	lm = linear_model
	### DO NOT TOUCH THIS PORTION OF THE CODE###
	params = np.append(lm.intercept_,lm.coef_)
	predictions = lm.predict(X)

	newX = np.append(np.ones((len(X),1)), X, axis=1)
	MSE = (sum((y-predictions)**2))/(len(newX)-len(newX[0]))

	var_b = MSE*(np.linalg.inv(np.dot(newX.T,newX)).diagonal())
	sd_b = np.sqrt(var_b)
	ts_b = params/ sd_b

	p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-1))) for i in ts_b]

	myDF3 = pd.DataFrame()
	myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilites"] = [params,sd_b,ts_b,p_values]
	print(myDF3)

if __name__=='__main__':
	# Do not change this seed. It guarantees that all students perform the same train and test split
	random.seed(1)
	# Setting p to 0.2 allows for a 80% training and 20% test split
	p = 0.2
	X = []
	y = []
	#############################################
	# TODO: open csv and read data into X and y #
	#############################################
	def load_file(file_path):
		X = []
		y = []
		with open(file_path, 'r', encoding='latin1') as file_reader:
			reader = csv.reader(file_reader, delimiter=',', quotechar='"')
			next(reader)
			for row in reader:
				if row == []:
					continue
				explanatory_var = []

				##Obesity, 3km FF
				explanatory_var.append(float(row[9]))
				cnt = float(row[3])

				# explanatory_var.append(float(row[7]))
				# cnt = float(row[3])

				# ### Obesity, 1km, 1km
				# explanatory_var.append(float(row[6]))
				# explanatory_var.append(float(row[8]))
				# cnt = float(row[3])

				### Obesity, 3km, 3km
				# explanatory_var.append(float(row[7]))
				# explanatory_var.append(float(row[9]))
				# cnt = float(row[3])

				#Diabetes, 1km SM
				# explanatory_var.append(float(row[6]))
				# cnt = float(row[4])

				# ### Diabetes, 1km, 1km
				# explanatory_var.append(float(row[6]))
				# explanatory_var.append(float(row[8]))
				# cnt = float(row[4])

				# ### Diabetes, 3km, 3km
				# explanatory_var.append(float(row[6]))

				# explanatory_var.append(float(row[7]))
				# cnt = float(row[4])

				# ### FF, Unemployment, Income
				# explanatory_var.append(float(row[1]))

				# explanatory_var.append(float(row[2]))
				# explanatory_var.append(float(row[9]))
				# cnt = float(row[3])

				# ### SM, Unemployment, Income
				# explanatory_var.append(float(row[1]))
				# # explanatory_var.append(float(row[2]))
				# cnt = float(row[6])

				# explanatory_var = explanatory_var[explanatory_var != 0]
				# cnt = cnt[cnt != 0]

				X.append(explanatory_var)
				y.append(cnt)

		#X = X[X!=0]
		#y = y[y!=0]
		return np.array(X, dtype='float64'), np.array(y, dtype='float64')

	#X, y = load_file("/course/cs1951a/pub/stats/data/bike_sharing.csv")
	X, y = load_file("/Users/shehryarhasan/Desktop/out.csv")

	##################################################################################
	# TODO: use train test split to split data into x_train, x_test, y_train, y_test #
	#################################################################################
	x_train, x_test, y_train, y_test = train_test_split(X,y, p)
	x_train = np.array(x_train)
	x_test = np.array(x_test)
	y_train = np.array(y_train)
	y_test = np.array(y_test)

	# x_train = x_train[x_train != 0]
	# y_train = y_train[y_train != 0]
	# x_train = x_train[_train != 0]
	# x_train = x_train[x_train != 0]

	##################################################################################
	# TODO: Use Sci-Kit Learn to create the Linear Model and Output R-squared
	#################################################################################
	linear_model = LinearRegression().fit(x_train, y_train)
	tr_preds = linear_model.predict(x_train)
	preds = linear_model.predict(x_test)
	r2 = r2_score(y_train, tr_preds)
	mse_train = mean_squared_error(y_train, tr_preds)
	mse_test = mean_squared_error(y_test, preds)
	print("Training R-squared:" + str(r2))
	print("Training MSE:" + str(mse_train))
	print("Testing MSE:" + str(mse_test))
	plt.scatter(x_train, y_train)
	plt.plot(x_train, linear_model.predict(x_train),color='k')
	plt.ylim(-2)
	plt.title("Obesity vs Fast Foods")
	plt.legend(['P = 0.087691'], loc='upper right')
	plt.xlabel('Number of Fast Food Restaurants in 3KM')
	plt.ylim(22)
	plt.ylabel('Obesity rate')
	plt.show()

	MultipleLinearRegression(x_train, y_train, linear_model)


'''
Code a "Rock, Paper, Scissors" Game

@author: Sarah Bloch
'''
#Today I will be coding a "Rock, Paper, Scissors" game.
#The objective is to correctly code a "Rock, Paper, Scissors" game for an
#individual to play. This will be written by Sarah Bloch

#import random
import random
from turtledemo.sorting_animate import Block

#Make a boolean variable called keepPlaying to track whether they want
#to keep playing and set it to True
keepPlaying = True

#LOOP 1: Make a game loop that continues while keepPlaying is True
# while (keepPlaying): "code block" when game stops: put to false
#loop needs tab

print("Welcome to Rock Paper Scissors!")
print("Best two out of three. Press 'q' to quit")

#make variables called userScore and cpuScore to track scores both set to 0
cpuScore = 0
userScore = 0

#LOOP 2: Make a round loop while userScore or cpuScore is less than 2
while(userScore < 2 and cpuScore < 2 and keepPlaying):

#LOOP 3: Use input() to get a choice from the user
#(rock, paper or scissors, or "q" {quit})
#store choice in variable. in this variable. Use .lower() to make the user's choice all lowercase

    Choice = input("Please choose (Rock, Paper, Scissors): ").lower()

        #Make a list of choices, then use random.choice() to get a random
        #choice for the cpu. Store the choice in a variable
    choiceList = ("rock", "paper", "scissors")
    cpuChoice = random.choice(choiceList)

    if ((Choice == "rock" and cpuChoice == "rock")
        or (Choice == "paper" and cpuChoice == "paper")
        or (Choice == "scissors" and cpuChoice == "scissors")):
            print("DRAW")
    #print("User: " + str(userScore) + " CPU: " + str(cpuScore))

    elif ((Choice =="rock" and cpuChoice == "paper")
    or (Choice == "paper" and cpuChoice == "scissors")
    or (Choice == "scissors" and cpuChoice == "rock")):
            cpuScore = cpuScore + 1
    #print("User: " + str(userScore) + "CPU: " + str(cpuScore))

    elif ((Choice == "rock" and cpuChoice == "scissors")
    or (Choice == "paper" and cpuChoice =="rock")
    or (Choice == "scissors" and cpuChoice == "paper")):
        userScore = userScore + 1

    elif (Choice == "q"):
        keepPlaying = False

    else: print("Not an option, try again.")

    print("User: " + str(userScore) + " CPU: " + str(cpuScore))

print ("Thanks for playing!")

if userScore > cpuScore:
    print ("User wins!")
else:
    print ("CPU wins!")

print("User: " + str(userScore) + " CPU: " + str(cpuScore))

    #print("Not an option, try again") if(choice.lower() == "q"):
    #keepPlaying = False

#print("Thanks for playing!")

        #Make a if/elif.else statement to check users input against
        #cpu's choice
        #NOTE: you will have to compare the users choice and cpu's choice to
        #"rock", "paper" and "scissors" seperately and combine with logical operators

                #print ("DRAW")
                #print ("User: " + str(userScore) + "CPU: " + str(cpuScore))

                #also adjust to different outcomes not just ties
        #if the user won, add one to the users score, then print out the scores
            #"User: [#]. CPU:[#]"

        #elif if (elif) the computer won, add one to the computer score
        #print out the scores...

        #else if it is a draw, print "DRAW", then print out the scores...

        #else if the user entered "q", then end the round and the game loop
        #use a break statement to end a round (round loop). Make keepPlaying equal False

        #else the user didn't enter accepted input, print"not an option, try again"
        #if(choice.lower() == "q"):
            #keepPlaying = False
    #print out thank you message
    #print who won
        #if the userScore is 2, then the user won
            #code
        #elif the cpuScore is 2, than the CPU won
            #code
    #print out the final scores (same code above)


'''
This file contains the functions to create a typewriter (capitals)
using the turtle package of python
'''
from __future__ import print_function, division
import turtle
from polygon import circle3, arc2

''' preliminaries 0'''

def bk(t,length):
    t.bk(length)

def pu(t):
    t.pu()

def pd(t):
    t.pd()

def fd(t,length):
    t.fd(length)

def fdbk(t,length):
    fd(t,length)
    pu(t)
    bk(t,length)
    pd(t)

def skip(t,length):
    pu(t)
    fd(t,length)
    pd(t)

def skipb(t,length):
    pu(t)
    bk(t,length)
    pd(t)

''' preliminaries 1 '''

def vline (t,length):
    '''
    Draws a verticle line using turtle t and of length height
    leaves the turtle facing right on the top corner
    '''
    t.lt(90)
    t.fd(length)
    t.rt(90)

def hline (t,length):
    '''
    Draws a horiontal line of length size and leaves the turlte
    at final position
    '''
    fd(t,length)

''' preliminaries 2 '''

def backvline(t,length):
    '''
    draws a verticle line by going below the present point
    leaves the turtle facing right
    '''
    t.lt(90)
    bk(t,length)
    t.rt(90)

def gammab (t,length):
    '''
    traces the turtle along a post back to its original position
    without leaving a trail
    '''
    pu(t)
    bk(t,length)
    t.lt(90)
    t.bk(2*length)
    t.rt(90)
    pd(t)

def gamma(t,length):
    '''
    Draws a verticle line of 2*length and
    a horizontal line of length size on top of verticle line

    '''
    vline(t,2*length)
    hline(t,length)

def rise(t,height):
    '''
    turtle rises to height
    '''
    pu(t)
    vline(t,height)
    pd(t)

def fall(t,height):
    '''
    turtle falls below by height
    '''
    pu(t)
    backvline(t,height)
    pd(t)

def floatline(t,length,height):
    '''
    a line of length size with floats 'height' high
    '''
    rise(t,height)
    hline(t,length)

def floatlineb(t,length,height):
    '''
    traces a floatline back to its starting position
    without leaving a trail
    '''
    pu(t)
    bk(t,length)
    fall(t,height)

''' Premilimaries 3 '''

def post(t,length):
    '''
    Draws a post and leaves the turtle at original position
    height : 2*Length, Width = length
    '''
    gamma(t,length)
    gammab(t,length)

def flyline(t,length,height):
    '''
    Draws a floating line and returns back to the initial position
    '''
    floatline(t,length,height)
    floatlineb(t,length,height)

def stump(t,distance,height):
    '''
    Draws a verticle line of height at a distance from current position
    '''
    skip(t,distance)
    vline(t,height)
    backvline(t,height)
    skipb(t,distance)

def disflyline(t,distance,length,height):
    skip(t,distance)
    flyline(t,length,height)
    skipb(t,distance)

def diagonal(t,x,y):
    '''
    Draws a slant line and returns to original position
    x is the x coordinate of final point of line
    y is the y coordinate od final point of line
    '''
    from math import atan2, sqrt, pi
    angle = atan2(y,x) * 180/pi
    length = sqrt(x**2 + y**2)
    t.lt(angle)
    fdbk(t,length)
    t.rt(angle)

'''
Functions to draw the letters

t is the turtle used to to draw the letter and the letters are n length
wide and 2n length high

in each of the functions below the turtle returns to the starting position
'''

def draw_a(t,n):
    #Draw A
    diagonal(t,n/2,2*n)
    skip(t,n)
    diagonal(t,-n/2,2*n)
    skipb(t,n)
    disflyline(t,n/4,n/2,n)
    skip(t,n)

def draw_b(t,n):
    #Draw B
    for i in range(2):
        arc2(t,n/2,180)
        t.rt(180)
    fall(t,2*n)
    stump(t,0,2*n)
    skip(t,n)

def draw_c(t,n):
    #Draws letter C
    post(t,n)
    fdbk(t,n)
    skip(t,n)

def draw_d(t,n):
    #Draw D
    arc2(t,n,180)
    t.rt(180)
    fall(t,2*n)
    stump(t,0,2*n)
    skip(t,n)

def draw_e(t,n):
    #Draws letter E
    draw_f(t,n)
    skipb(t,n)
    fdbk(t,n)
    skip(t,n)

def draw_f(t,n):
    #Draws letter F
    post(t,n)
    flyline(t,n,n)
    skip(t,n)

def draw_g(t,n):
    #Draws letter G
    post(t,n)
    fdbk(t,n)
    stump(t,n,n)
    disflyline(t,n/2,n/2,n)
    skip(t,n)

def draw_h(t,n):
    #Draws letter H
    stump(t,0,2*n)
    flyline(t,n,n)
    stump(t,n,2*n)
    skip(t,n)

def draw_i(t,n):
    #Draws letter I
    flyline(t,n,2*n)
    stump(t,n/2.0,2*n)
    fdbk(t,n)
    skip(t,n)

def draw_j(t,n):
    #Draw letter J
    arc2(t,n/2,90)
    fd(t,(2*n)-n/2)
    t.rt(90)
    floatlineb(t,n/2,2*n)
    flyline(t,n,2*n)
    skip(t,n)

def draw_k(t,n):
    #Draws K
    stump(t,0,2*n)
    rise(t,n)
    diagonal(t,n,n)
    diagonal(t,n,-n)
    fall(t,n)
    skip(t,n)

def draw_l(t,n):
    #Draws letter L
    stump(t,0,2*n)
    fdbk(t,n)
    skip(t,n)

def draw_m(t,n):
    #Draws letter M
    stump(t,0,2*n)
    draw_v(t,n)
    skipb(t,n)
    stump(t,n,2*n)
    skip(t,n)

def draw_n(t,n):
    #Draws N
    stump(t,0,2*n)
    stump(t,n,2*n)
    rise(t,2*n)
    diagonal(t,n,-2*n)
    fall(t,2*n)
    skip(t,n)

def draw_o(t,n):
    #Draws letter O
    skip(t,n)
    circle3(t,n)
    skipb(t,n)
    skip(t,2*n)

def draw_p(t,n):
    #Draw P
    rise(t,n)
    arc2(t,n/2,180)
    t.rt(180)
    fall(t,2*n)
    stump(t,0,2*n)
    skip(t,n)

def draw_q(t,n):
    #Draw Q
    draw_o(t,n)
    diagonal(t,-n,n)

def draw_r(t,n):
    #Draws R
    vline(t,2*n)
    arc2(t,n/2,-180)
    t.rt(180)
    diagonal(t,n,-n)
    fall(t,n)
    skip(t,n)

def draw_s(t,n):
    # Draws S
    fd(t,n/2)
    arc2(t,n/2,180)
    arc2(t,n/2,-180)
    fd(t,n/2)
    gammab(t,n)
    skip(t,n)

def draw_t(t,n):
    #Draws letter T
    flyline(t,n,2*n)
    stump(t,n/2.0,2*n)
    skip(t,n)

def draw_u(t,n):
    #Draws letter U
    stump(t,0,2*n)
    fdbk(t,n)
    stump(t,n,2*n)
    skip(t,n)

def draw_v(t,n):
    #Draws V
    skip(t,n/2)
    diagonal(t,-n/2,2*n)
    diagonal(t,n/2,2*n)
    skipb(t,n/2)
    skip(t,n)

def draw_w(t,n):
    stump(t,0,2*n)
    skip(t,n)
    rise(t,2*n)
    t.lt(180)
    draw_v(t,n)
    skipb(t,n)
    vline(t,2*n)
    t.rt(180)

def draw_x(t,n):
    diagonal(t,n,2*n)
    skip(t,n)
    diagonal(t,-n,2*n)
    skipb(t,n)
    skip(t,n)

def draw_y(t,n):
    #Draws Y
    skip(t,n/2)
    vline(t,n)
    diagonal(t,n/2,n)
    diagonal(t,-n/2,n)
    floatlineb(t,n/2,n)
    skip(t,n)

def draw_z(t,n):
    #Draws z
    flyline(t,n,2*n)
    diagonal(t,n,2*n)
    fdbk(t,n)
    skip(t,n)

def draw_(t, n):
    # draw a space
    skip(t, n)

if __name__ == '__main__' :

    size = 20
    bob = turtle.Turtle()

    for f in [draw_b, draw_a, draw_b, draw_e]:
        f(bob,size)
        skip(bob,size)

    turtle.mainloop()


# api/urls.py

from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from . import views

urlpatterns = {
    url(r'^gzs/$', views.getGZ),
    url(r'^gzs/(?P<gz>[0-9]+)/aois/$', views.aoiView),
    url(r'^aois/(?P<id>[0-9]+)/$', views.deleteAOI),
    url(r'^users/$', views.userView),
    url(r'^aois/(?P<id>[0-9]+)/observations/$', views.addObservation),
    url(r'^observations/(?P<id>[0-9]+)/$', views.observationView),
    url(r'^images/$', views.addImage),
    url(r'^species/$', views.getSpecies),
    url(r'^crowns/$', views.getCrowns),
    url(r'^canopies/$', views.getCanopies),
    url(r'^upload/$', views.fileUploadView)
}

urlpatterns = format_suffix_patterns(urlpatterns)


def mergeIntervals(I):
	merged=[]
	I.sort(key = lambda x: x[0])

	merged.insert(0,I[0])

	for i in range(1,len(I)):
		top = merged[0]

		if top[1]< I[i][0]:
			merged.insert(0,I[i])
		elif top[1] < I[i][1]:
			top[1] = I[i][1]
			merged[0]=top
		print(merged)
	return merged

def merge(intervals):
	merged=[]
	intervals.sort(key=lambda x:x[0])

	merged.append(intervals[0])

	for i in range(1,len(intervals)):
		top=merged[-1]

		if top[1]<intervals[i][0]:
			merged.append(intervals[i])
		elif top[1]<intervals[i][1]:
			top[1]=intervals[i][1]
			merged[-1]=top
	return merged

intervals=[[1,3],[2,6],[8,10],[15,18]]


import sys
import argparse

sys.path.append(r'../')

from puslib.streams.file import FileInput  # noqa: E402

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Extract telemetry packets from archive files.")
    parser.add_argument('input', metavar='path', help='Archive file')
    parser.add_argument('-o', '--offset', metavar='size', type=int, default=0, help="Offset from outer proprietary headers to CCSDS header.")
    parser.add_argument('-v', '--validate-pec', action="store_true", help="Validate packet error control.")
    args = parser.parse_args()

    file_input_stream = FileInput(args.input, args.offset, args.validate_pec)
    for packet in file_input_stream:
        print(packet)


import json
import pandas as pd

def get_icds(file_path):
    selected_icds = []
    with open(file_path, 'r') as j:
        data = json.loads(j.read())
        for row in data:
            if(int(row['count']) > 1000):
                selected_icds.append(row['icd_code'])
    return selected_icds

def get_rowCounts(file_path):
    df = pd.read_csv(file_path)
    print(df.head(10))
    return df.shape

if __name__ == "__main__":
    data = None
    # with open('results-20220218-162426.json', 'r') as j:
    #     data = json.loads(j.read())
    #df = pd.read_csv('bq-results-20220218-153158-cl74v08k7enx.csv')
    #print(df.shape[0], df.shape[1])
    # features = []
    # for row in data:
    #     if(int(row['count']) > 1000):
    #         features.append(row['label'])

    # print(features)
    # print(len(features))
    #print(get_icds('ICD-code-subject-count.json'))
    print(get_rowCounts('../../Downloads/bq-results-20220218-172030-wmt74bsztg7y/bq-results-20220218-172030-wmt74bsztg7y.csv'))


from django.urls import path

from .views import AuthorBookListView, BookListView, BookDetailView, SearchView

app_name = 'main'

urlpatterns = [
    path('', BookListView.as_view(), name='books_list'),
    path('books/<int:pk>/', BookDetailView.as_view(), name='books_detail'),
    path('author/<str:username>/', AuthorBookListView.as_view(), name='author_books'),
    path('search/', SearchView.as_view(), name='search_books')
]


from apiClient import compoundDetailsByCompoundID
from apiClient import hitDetailsByCompoundID
from apiClient import compoundDetailsBySMILE
import csv

_COMPOUND_NOT_FOUND = []

# Prechecks
# Check if compound exists
def checkCompoundExistsbyID(extCompoundId):
    compoundID = compoundDetailsByCompoundID(extCompoundId)["id"]
    # If compound is not found
    if compoundID == 0:
        print(f"{extCompoundId} : NOT FOUND 404")
        return
    print(f"{extCompoundId} : {compoundID}")

    return
    hit = hitDetailsByCompoundID(compoundID)
    print(hit)
    #print(f"{extCompoundId} : Target={hit['targetName']} : Method={hit['method']} : Library={hit['library']} : ScreenID={hit['screenId']}")

def checkCompoundExistsbySMILE(extCompoundId):
    compoundID = compoundDetailsBySMILE(extCompoundId)["id"]
    # If compound is not found
    if compoundID == 0:
        print(f"{extCompoundId} : NOT FOUND 404")
        return
    print(f"{extCompoundId} : {compoundID}")

    return
    hit = hitDetailsByCompoundID(compoundID)
    print(hit)
    #print(f"{extCompoundId} : Target={hit['targetName']} : Method={hit['method']} : Library={hit['library']} : ScreenID={hit['screenId']}")

# Read Voting data from CSV
def loadVoteMap():
    voteMap = []
    with open("inp_data/votes/rho.csv") as input_csv:
        csv_reader = csv.reader(input_csv, delimiter=",")
        next(csv_reader) # Skip header row
        for row in csv_reader:
            vote = {
                "compoundExtID": row[0],
                "smile": row[1],
                "positive": row[2],
                "negative": row[3],
                "neutral": row[4],
            }
            voteMap.append(vote)
    return voteMap

_VOTE_MAP = loadVoteMap()

for vote in _VOTE_MAP:
  checkCompoundExistsbySMILE(vote['smile'])


#gadgetmiser's idempotent splitter

import os
from shutil import move

wd = os.getcwd()
dirs = os.listdir(wd)
lastitemindex = len(dirs) - 1

drive = wd.split(':')[0]
results = ':\\c64Romset_output\\'
filesperfolder = 255
letterstodisplay = 15

firstfn_2l = dirs[0][:letterstodisplay].split("(")[0].strip().upper()[:4]
lastfn_2l = dirs[:filesperfolder - 1][-1][:letterstodisplay].split("(")[0].strip().upper()[:4]

firsttarget = (firstfn_2l + " to " + lastfn_2l).strip()
os.mkdir(drive + results)
os.mkdir(drive + results + firsttarget)
log_output = open(drive + results + "log_output.txt","w+")

tally = 0
counter = 0
target = firsttarget

for folder in dirs:
    tally += 1

    if counter == filesperfolder:
            p1 = folder[:letterstodisplay].split("(")[0].upper().strip()[:4]
            folderpos = dirs.index(folder)
            try:
                p2 =  dirs[folderpos + filesperfolder - 1][:letterstodisplay].split("(")[0].upper().strip()[:4]
            except IndexError:
                p2 =  dirs[lastitemindex][:letterstodisplay].split("(")[0].upper().strip()[:4]
            newdir = (p1 + " to " + p2).strip()
            print(str(tally) + " files processed ... making new dir called: " + newdir)
            target = newdir
            counter = 0
    newfname = folder.split("(")[0].strip()
    move(folder, drive + results + target + "\\" + newfname)
    print("Moved " + folder + " to " + drive + results + target + " as " + newfname)
    log_output.write("\n" + "Moved " + folder + " to: ** " + target + " **" + " as " + newfname)
    counter += 1

print(str(tally) + ' files processed ... ALL DONE')
log_output.write("\n" + str(tally) + " files processed.")
log_output.close()


#!/usr/bin/env python

from __future__ import print_function

import random
import rospy
from pandora_data_fusion_msgs.msg import GlobalProbabilitiesMsg

global_propabilities_topic = "/data_fusion/signs_of_life"

def talker():
    msg = GlobalProbabilitiesMsg()
    pub = rospy.Publisher(global_propabilities_topic, GlobalProbabilitiesMsg,
                          queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rospy.loginfo(" Publisher for Victim Propabilities initialized")
    while not rospy.is_shutdown():
        msg.thermal = random.randint(0, 5)
        msg.co2 = random.randint(0, 5)
        msg.sound = random.randint(0, 5)
        msg.motion = random.randint(0, 5)
        msg.victim = random.randint(0, 5)
        print(msg)
        pub.publish(msg)
        rospy.sleep(1)

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 09:19:48 2022

@author: levi
"""

from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel,QTextEdit,\
    QVBoxLayout, QScrollArea,QHBoxLayout, QLineEdit,QDesktopWidget, QPushButton, QSizePolicy
from PyQt5.QtGui import QFont, QIcon, QTextOption, QPalette, QColor,QFontDatabase
from PyQt5.QtCore import QCoreApplication, Qt, QSize

import examples_loader

SIZE = 960

def clear_layout(layout):
    while layout.count():
        item = layout.takeAt(0)
        if item.widget() is not None:
            item.widget().deleteLater()

        if item.layout() is not None:
            clear_layout(item)
           #item.layout().deleteLater()
            #item.setParent(None)

class ButtonSel(QPushButton):
    def __init__(self, icon, name):
        super().__init__()
        self.icon = icon
        self.name = name
        self.setIcon(QIcon(icon))
        self.setIconSize(QSize(30, 30))
        self.setMaximumWidth(110)

class LangSel_bar(QHBoxLayout):
    def __init__(self):
        super(LangSel_bar, self).__init__()

        b_dict = {"French" :"icons/france.png", "English":"icons/uk.png",\
         "German":"icons/germany.png", "reverse":"icons/reverse.png" }

        self.B_dict = {}
        for b in b_dict:
            self.B_dict[b] = ButtonSel(b_dict[b], b)
        self.B_dict["reverse"].setMaximumWidth(35)

        self.source = "German"
        self.target = "English"
        self.source_label = QLabel(self.source)
        self.target_label = QLabel(self.target)

        for label in [self.source_label, self.target_label]:
            font_id_1 = QFontDatabase.addApplicationFont("./fonts/Roboto/Roboto-Medium.ttf")
            font_1 = QFontDatabase.applicationFontFamilies(font_id_1)[0]
            f0 = QFont(font_1, 16) #, QFont.Bold, False) # auparavant "Segoe UI"
            label.setFont(f0)
            label.setStyleSheet("QLabel { color : #111111}")
            label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        for w in [self.source_label,self.B_dict["reverse"], self.target_label, \
                  self.B_dict["English"],self.B_dict["German"],self.B_dict["French"]]:
            self.addWidget(w)

    def update_lang(self, source, target):
        self.source, self.target = source, target
        self.source_label.setText(self.source)
        self.target_label.setText(self.target)
        self.source_label.update()
        self.target_label.update()

class CustomTextEdit(QTextEdit):
    def __init__(self, col1, col2, font_name="Arial", size=12):
        super(QTextEdit, self).__init__()

        self.setFixedWidth(int(SIZE*.9))
        self.setMaximumHeight(60)
        self.setWordWrapMode(QTextOption.WordWrap)
        self.textChanged.connect(self.updateText)

        self.text1.setStyleSheet("QTextEdit { background: {0}; selection-background-color: {1}; }".format(col1, col2))
        f0 = QFont(font_name, size, QFont.Bold, False)
        self.text1.setFont(f0)

        #self.setFixedSize(SIZE, 40)
        #self.setText(text1)
        #self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def updateText1(self):
          self.setFixedHeight(int(1.2*self.document().size().height()))

class LabelResult(QLabel):
    def __init__(self, col1, col2, font_name="Arial", size=12, bold=False):
        super(LabelResult, self).__init__()
        self.setWordWrap(True)
        self.setMinimumWidth(int(SIZE*.88))
        self.setMaximumWidth(int(SIZE*.88))
        self.setContentsMargins(20, 5, 20, 5) #left, top, right, bottom
        self.setTextInteractionFlags(Qt.TextSelectableByMouse)
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(col1))
        palette.setColor(QPalette.WindowText,  QColor(col2))
        self.setAutoFillBackground(True)
        self.setPalette(palette)
        f1 = QFont(font_name, size)
        if bold: f1.setBold(True)
        self.setFont(f1)

class Result_bar(QHBoxLayout):
    def __init__(self, text1, text2):
        super(Result_bar, self).__init__()
        font_id_1 = QFontDatabase.addApplicationFont("./fonts/Roboto/Roboto-Medium.ttf")
        font_1 = QFontDatabase.applicationFontFamilies(font_id_1)[0]

        self.text1 = LabelResult("#B4ECF4","#000000", font_name=font_1, size=12, bold=False)
        self.text1.setText(text1)

        self.text2 = LabelResult("#D2FCFE","#000000",font_name= "Helvetica",size=11)
        self.text2.setText(text2)

        self.button = QPushButton()
        self.button.setFixedSize(QSize(35, 35))
        self.button.setIcon(QIcon('icons/star.png'))
        self.button.setIconSize(QSize(30, 30))
        self.button.clicked.connect(self.change_status)

        self.status = False

        # Add Widgets to Layout
        v_layout = QVBoxLayout()
        v_layout.setSpacing(0)
        v_layout.addWidget(self.text1)
        v_layout.addWidget(self.text2)
        v_layout.addSpacing(8)

        self.addLayout(v_layout)
        self.addWidget(self.button, alignment= Qt.AlignTop | Qt.AlignLeft)

        self.button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

    def change_status(self):
        self.status = not self.status
        if (self.status):
            self.button.setIcon(QIcon('icons/star2.png'))
        else:
            self.button.setIcon(QIcon('icons/star.png'))

class Window(QMainWindow):
    """
    __init__ : Initialize the window
    This function sets up the window's properties such as title, size, and it calls the initUI() function.
    """

    def __init__(self):
        super().__init__()
        self.setWindowTitle('My Reverso App with Python/PyQT5')

        self.width, self.height = SIZE, int(SIZE*.9)
        self.resize(self.width, self.height)
        self.center_window()

        self.list_sentences = []
        self.list_labels = []

        self.initUI()

        self.source_lang = "German"
        self.target_lang = "English"
        self.loader = examples_loader.examples_loader(\
            source = self.source_lang , target =self.target_lang)

    """
    center_window : center the window on the screen
    This function centers the window on the user's screen by calculating the coordinates
    of the center of the screen and then placing the window there.
    """

    def center_window(self):
        # gros problème après maj de Gnome sur Wayland. Ne fonctionne pas

        desktop = QDesktopWidget()
        geometry = desktop.screenGeometry()
       # print(geometry.width(), geometry.height())
        x0 = geometry.width() // 2 - self.width // 2
        y0 = geometry.height() // 2 - self.height // 2

        self.setGeometry(x0, y0, self.width, self.height)
       # print(self.x(), self.y())
      #  self.setFixedSize(self.width, self.height)

    """
    launch_search : launch the search
    This function retrieves the text from the search bar, calls the retrieve function from the examples_loader
    class to get a list of sentences and then passes that list to the load_sentences function.
    """

    def launch_search(self):
        text = self.search_bar.text()
        if (text): # eviter barre vide
            list_sentences = self.loader.retrieve(text)
            self.load_sentences(list_sentences)

    """
    load_sentences : load the sentences
     This function takes a list of sentences and adds labels to the scroll layout for each sentence.
     It also sets the font of the labels to either bold or regular based on the language.
    """

    def load_sentences(self, list_sentences):
        self.list_sentences = []
        self.list_sentences = list_sentences

        clear_layout(self.scroll_layout)

        assert(len(self.list_sentences)%2 == 0)
        for i in range(0, len(self.list_sentences), 2):
            hl = Result_bar(self.list_sentences[i], \
                          self.list_sentences[i+1])

            self.scroll_layout.addLayout(hl)

    def react_buttons(self):
        name = self.sender().name
        update_flag = False
        if name in ["English", "French", "German"] and name != self.source_lang:
            self.target_lang = name
            update_flag = True
        if name == "reverse":
            self.target_lang, self.source_lang = self.source_lang, self.target_lang
            update_flag = True
        if update_flag:
            self.loader.update_param(self.source_lang, self.target_lang)
            self.langSel_bar.update_lang(self.source_lang, self.target_lang)
            self.launch_search()

    """
    initUI : initialize the user interface
    This function sets up all of the elements of the user interface such as the search bar, scroll area, etc.
    """
    def initUI(self):
      #  self.setStyleSheet("QMainWindow {background-color: #AAAAAA;}")
        self.main_widget = QWidget(self)
        self.setCentralWidget(self.main_widget)
        self.main_layout = QVBoxLayout(self.main_widget)

        ######################################################

        self.search_bar = QLineEdit()
        self.search_bar.setPlaceholderText('Search')
        self.search_bar.setMinimumHeight(40)
        self.search_button = QPushButton("")
        self.search_button.setMinimumSize(40,40)
        self.search_button.setIcon(QIcon('icons/search.png'))
        self.search_button.setIconSize(QSize(35, 35))
        self.search_button.clicked.connect(self.launch_search)
        self.search_bar.returnPressed.connect(self.launch_search)
        h_box = QHBoxLayout()
        h_box.addWidget(self.search_bar)
        h_box.addWidget(self.search_button)
        self.main_layout.addLayout(h_box)

        ######################################################

        self.langSel_bar = LangSel_bar()

        B_dict = self.langSel_bar.B_dict
        for b in B_dict:
            B_dict[b].clicked.connect(self.react_buttons)

        self.main_layout.addLayout(self.langSel_bar)
        ######################################################

        self.scroll_widget = QWidget(self)
        self.main_layout.addWidget(self.scroll_widget)
        self.scroll_layout = QVBoxLayout(self.scroll_widget)
        self.scroll_layout.setSpacing(10)

        self.load_sentences(self.list_sentences)

        self.scroll_area = QScrollArea(self)
        self.scroll_area.setWidget(self.scroll_widget)
        self.scroll_area.setWidgetResizable(True)

        self.scroll_layout_2 = QHBoxLayout(self.main_widget)
        self.scroll_layout_2.addWidget(self.scroll_area)
        self.main_layout.addLayout(self.scroll_layout_2)

    """
    quitApp : quit the application
    This function quits the application when called.
    """

    def quitApp(self):
        QCoreApplication.instance().quit()

##############################################################################

import sys
from PyQt5.QtWidgets import  QApplication
#import translate_window

# ATTENTION LORS D'UN COPIE COLLE LA WINDOW N'est plus la même si importation

app=0 # necessaire crash
app = QApplication([])
app.setStyle('Fusion')
app.aboutToQuit.connect(app.deleteLater)
dow = Window()

dow.show()

sys.exit(app.exec())
app.exit()


"""
输入一个链表，反转链表后，输出新链表的表头
输入一个链表的意思就是输入一个表头
"""

class Node:
    """节点类"""

    def __init__(self, value):
        self.value = value
        self.next = None

class Solution:
    def reverse(self, head_node):
        pre = None
        cur = head_node
        while cur:
            next = cur.next  # 要预先存储一个next，防止进不去下一个
            cur.next = pre  # 反向
            pre = cur  # 前进一个
            cur = next  # 前进一个
        return pre

if __name__ == '__main__':
    s = Solution()
    # 手动创建链表,做一个简单的测试
    head = Node(100)
    head.next = Node(200)
    head.next.next = Node(300)
    node = s.reverse(head)
    print(node.value)


# coding=utf-8

'''
Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to
the definition.

Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the
form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the
form of 0+-2i.
Note:

The input strings will not have extra blank.
The input strings will be given in the form of a+bi, where the integer a and b will
both belong to the range of [-100, 100]. And the output should be also in this form.
'''

'''
公司：Amazon
'''

class Solution(object):
    def complexNumberMultiply(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        real_a, vir_a = a.split('+')
        real_b, vir_b = b.split('+')

        real_a, real_b = int(real_a), int(real_b)
        vir_a, vir_b = int(vir_a[:len(vir_a) - 1]), int(vir_b[:len(vir_b) - 1])

        real_res = real_a * real_b - vir_a * vir_b
        vir_res = real_a * vir_b + real_b * vir_a

        return str(real_res) + '+' + str(vir_res) + 'i'


from setuptools import setup, find_packages
import sys, os

version = '0'

setup(name='ZFSpy',
      version=version,
      description="Python bindings for ZFS",
      long_description="""\
""",
      classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='zfs python',
      author='Chen Zheng',
      author_email='nkchenz@gmail.com',
      url='http://github.com/nkchenz/zfspy/',
      license='GPL v2',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )


import ctypes
import sys
import os

curPath = os.path.split(__file__)[0]
curPath = os.path.split(curPath)[0]
exe = os.path.join(curPath, "NiuniuCapture.exe")

def capture():
    return os.system("{} niuniu,'',0,0,0,0,0,0".format(exe))

if __name__ == "__main__":
    capture()


from Feature_Extraction import *
from Feature_suspiciousness_pole import *
from priors import *
from homophily_matrix import *
from SpEagle import *
import time

def main():

    metadata = "/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/data/raw/metadata"
    review_content = "/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/data/raw/reviewContent"

    #read the metadata file:
    userId, prodId, date, ratings, recommend = read_metadata(path = metadata,N = 1000)

    #read the reviewcontent file
    review_text = read_review_content(review_content,N = 1000, sep='\t')

    #review_words number of words in each review. Seperately calculated and saved.
    #to create this, run wordcount_reviews file..
    review_words = np.loadtxt("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/data/raw/review_words")

    start = time.time()

    #comment after features are built.

    #read user features
    # make_user_features(userId,prodId,date,ratings,recommend,review_words,review_text)
    # end = time.time()
    # print("time taken to build user features:",end-start)

    #read product features
    start = time.time()

    # #read user features
    # make_prod_features(userId,prodId,date,ratings,recommend,review_words,review_text)
    # end = time.time()
    # print("time taken to build user features:",end-start)

    # read review features.
    #sandy is yet to give..

    #read adjacency list.
    adjlist = np.loadtxt("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/data/raw/reviewGraph")

    #reading our features.[this wont work for 6lakh rows?]
    user_features = pd.read_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/feature_csvs/user_features_1.csv")
    prod_features = pd.read_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/feature_csvs/prod_features.csv")
    #review_priors = pd.read_csv("")

    #Calculating priors.

    #calculate priors for users.
    user_priors = pd.DataFrame()
    uprior = prior(user_features[user_features.columns[1:]],isHighUser)
    user_priors.insert(0,"1-prior",1-uprior)
    user_priors.insert(1,"prior",uprior)
    user_priors.to_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/user_priors.csv",index=None,header=True)

    #calculate prior for products
    prod_priors = pd.DataFrame()
    pprior = prior(prod_features[prod_features.columns[1:]],isHighProd)
    prod_priors.insert(0,"1-prior",1-pprior)
    prod_priors.insert(1,"prior",pprior)
    prod_priors.to_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/prod_priors.csv",index=None,header=True)

    #calculate priors for reviews -
    review_priors = pd.DataFrame()
    #rprior = prior(review_features[review_features.columns[1:]],isHighReview)
    #review_priors.insert(0,"1-prior",1-rprior)
    #review_priors.insert(1,"prior",rprior)
    #review_priors.to_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/review_priors.csv",index=None,header=True)

    #read these before calling..speagle : upriors.csv,ppriors.csv,rpriors.csv
    #upriors = pd.read_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/user_priors.csv")
    #ppriors = pd.read_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/prod_priors.csv")
    #rpriors =pd.read_csv("/Users/anaghakaranam/Desktop/Opinion_Spam/coding-playground/prior_csvs/review_priors.csv")
    #Calling the SP Eagle function.

    #beliefsUser, beliefsProd, beliefsReview = SpEagle(adjlist, upriors, ppriors, rpriors, edgep, 100)

if __name__ == "__main__":
    main()


import hashlib
import json
import sys
from time import time

import requests
from flask import Flask, jsonify, request

import black
import channel
import authority

app = Flask(__name__)

@app.route('/join', methods=['POST'])
def join_channel():
    values = request.get_json()

    required = ['remote_node', 'local_node', 'chan']
    if not all(k in values for k in required):
        return "Missing required fields", 400

    remote_node = values['remote_node']
    local_node = values['local_node']
    chan = values['chan']
    data = {'nodes': [local_node] }
    response = requests.post(
        f'{remote_node}/{chan}/nodes/register',
        data = json.dumps(data),
        headers={'Content-Type': 'application/json'}
    )
    body = response.json()
    chan_info = body['channel']

    # manually cloning the channel? gross
    chan = channel.Channel(chan_info['name'])
    chan.created_at = chan_info['created_at']
    chan.ref = chan_info['ref']
    # TODO: clone all registered nodes on remote machine
    chan.chain.register_node(remote_node)

    black.CHANNELS[chan.ref] = chan
    # TODO: return a better response than just "OK"
    return jsonify({'message': "OK"})

@app.route('/<chan>/nodes/register', methods=['POST'])
def register_nodes(chan):
    values = request.get_json()

    if values is None:
        return "Error: Please supply a valid list of nodes", 400

    required = ['nodes']
    if not all(k in values for k in required):
        return "Error: Please supply a valid list of nodes", 400

    nodes = values.get('nodes')
    if nodes is None:
        return "Error: Please supply a valid list of nodes", 400

    for node in nodes:
        black.CHANNELS[chan].chain.register_node(node)

    response = {
        'message': 'New nodes have been added',
        'total_nodes': list(black.CHANNELS[chan].chain.nodes),
        'channel': {
            'name': black.CHANNELS[chan].name,
            'ref': black.CHANNELS[chan].ref,
            'created_at': black.CHANNELS[chan].created_at,
        }
    }
    return jsonify(response), 201

@app.route('/<chan>/nodes/resolve', methods=['GET'])
def consensus(chan):
    replaced = black.CHANNELS[chan].chain.resolve_conflicts(chan)
    authority = black.CHANNELS[chan].chain.authority.votes
    chain = black.CHANNELS[chan].chain.chain

    if replaced:
        response = {
            'message': 'Our chain was replaced',
            'new_chain': chain,
            'new_authority': [e.__dict__ for e in authority],
        }
    else:
        response = {
            'message': 'Our chain is authoritative',
            'chain': chain,
            'authority': [e.__dict__ for e in authority],
        }

    return jsonify(response), 200

@app.route('/<chan>/transactions/new', methods=['POST'])
def new_transaction(chan):
    values = request.get_json()

    # Check that the required fields are in the POST'ed data
    required = ['message', 'pub_key', 'signature']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new Transaction
    index = black.CHANNELS[chan].chain.new_transaction(
        values['pub_key'], values['signature'], values['message']
    )

    response = {'message': f'Transaction will be added to Block {index}'}
    return jsonify(response), 201

@app.route('/<chan>/votes/new', methods=['POST'])
def new_vote(chan):
    values = request.get_json()

    # Check that the required fields are in the POST'ed data
    required = ['vote', 'pub_key', 'signature']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new vote
    vote = authority.Vote(values['vote'], values['pub_key'], values['signature'])
    if black.CHANNELS[chan].chain.authority.vote(vote):
        response = {'message': f'Vote added'}
        return jsonify(response), 201
    else:
        return jsonify({'message': 'No authority or bad signature or bad last sig reference'}, 401)

@app.route('/<chan>/chain', methods=['GET'])
def full_chain(chan):
    chain = black.CHANNELS[chan].chain.chain
    authority = black.CHANNELS[chan].chain.authority.votes
    response = {
        'messages': {
            'chain': chain,
            'length': len(chain),
        },
        'authority': {
            'chain': [e.__dict__ for e in authority],
            'length': len(authority),
        },
    }
    return jsonify(response), 200

@app.route('/channels/new', methods=['POST'])
def new_channel():
    values = request.get_json()

    required = ['name']
    if not all(k in values for k in required):
        return 'Missing values', 400

    chan = channel.Channel(values['name'])
    black.CHANNELS[chan.ref] = chan

    response = {'channel': chan.ref}
    return jsonify(response), 200

@app.route('/channels')
def list_channels():
    return jsonify(black.CHANNELS), 200

@app.route('/channels/<chan>')
def list_channel(chan):
    return jsonify(black.CHANNELS[chan]), 200