import wx

class RadioButtonGrid(wx.Panel):
    CtrlType = wx.RadioButton
    firstCtrlStyle = wx.RB_GROUP

    def __init__(
        self,
        parent,
        id = wx.ID_ANY,
        pos = wx.DefaultPosition,
        size = wx.DefaultSize,
        rows = None,
        columns = None
    ):
        wx.Panel.__init__(self, parent, id, pos, size)
        biggestWidth = 0
        sizer = wx.FlexGridSizer(len(rows) + 2, len(columns) + 1)
        sizer.Add((0, 0))
        for column in columns:
            staticText = wx.StaticText(self, -1, column)
            width = staticText.GetBestSize()[0]
            if width > biggestWidth:
                biggestWidth = width
            sizer.Add(staticText, 0, wx.ALIGN_CENTER_HORIZONTAL)

        self.ctrlTable = ctrlTable = []
        for column in columns:
            ctrl = self.CtrlType(self, style=self.firstCtrlStyle)
            ctrlColumn = [ctrl]
            for row in rows[1:]:
                ctrl = self.CtrlType(self)
                ctrlColumn.append(ctrl)
            ctrlTable.append(ctrlColumn)

        biggestWidth += 3
        width = ctrl.GetBestSize()[0]
        if width > biggestWidth:
            biggestWidth = width

        for y, row in enumerate(rows):
            staticText = wx.StaticText(self, -1, row)
            sizer.Add(staticText, 0, wx.ALIGN_CENTER_VERTICAL)
            for x, column in enumerate(columns):
                ctrl = ctrlTable[x][y]
                sizer.Add(ctrl, 0, wx.ALIGN_CENTER_HORIZONTAL)

        sizer.Add((0, 0))
        for column in columns:
            sizer.Add((biggestWidth, 0))

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        sizer.Fit(self)
        self.Layout()
        self.SetMinSize(self.GetSize())
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def GetValue(self):
        result = []
        for column in self.ctrlTable:
            for i, ctrl in enumerate(column):
                if ctrl.GetValue():
                    break
            result.append(i)
        return result

    def OnSize(self, event):
        if self.GetAutoLayout():
            self.Layout()

    def SetValue(self, value):
        for column, val in enumerate(value):
            self.ctrlTable[column][val].SetValue(True)


# Libraries
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import sys

# Custom files
from tile import Tile
from module import Module
from stacked_chip import StackedChip
from technology import Technology
from error import error, warning

# Colors used for different aspects of the model
grid_color = "#999999"
tile_color = "#9999FF"
schip_color = "#CCCCCC"
chiplet_color = "#888888"
master_color = "#FF9999"
slave_color = "#FFFF99"
phy_in_color = "#FF9933"
phy_out_color = "#CC6600"
con_color = "#333333"
collision_color = "#FF0000"

wire_ratio = 1

# Auxiliary Function: Component-wise addition of two tuples
def tadd(a,b):
	return (a[0] + b[0], a[1] + b[1])

# Draw a line
def draw_line(a,b,c, arr = False, lwd= 1, grid_mode = True):
	global wire_ratio
	if grid_mode:
		(a,b) = ((a[0]*wire_ratio, a[1]),(b[0]*wire_ratio,b[1]))
	plt.arrow(	a[0],a[1],b[0]-a[0],b[1]-a[1],
				color = c,
				head_width = 0.1 if arr else 0,
				length_includes_head = True,
				linewidth = lwd)

# Draw a rectangle
def draw_rectangle(x, y, w, h, c, a = 1.0, border = False, grid_mode = True):
	global wire_ratio
	if grid_mode:
		x = x * wire_ratio
		w = w * wire_ratio
	if border:
		rectangle = plt.Rectangle((x,y), w, h, fc = c, fill = True, alpha = a, ec = "#000000")
	else:
		rectangle = plt.Rectangle((x,y), w, h, fc = c, fill = True, alpha = a)
	plt.gca().add_patch(rectangle)

# Draw a circle
def draw_circle(x,y,r,c):
	circle = plt.Circle((x,y),radius = r, color = c)
	plt.gca().add_patch(circle)

# Draw text
def draw_text(x,y,txt):
	global wire_ratio
	x = x * wire_ratio
	plt.text(x,y,txt,verticalalignment='center', horizontalalignment='center',)

# Visualize a single tile
def visualize_tile(tile):
	(rows, cols) = (tile.n_rows, tile.n_cols)
	fig, ax = plt.subplots()
	# Draw tile
	draw_rectangle(0, 0, cols, rows, tile_color)
	# Draw grid
	for row in range(rows + 1):
		draw_line((0,row),(cols,row), grid_color)
	for col in range(cols + 1):
		draw_line((col,0),(col,rows), grid_color)
	# Draw master-ports:
	for mport in tile.master_ports:
		(row,col) = mport["location"]
		draw_rectangle(col, row, 1, 1, master_color)
	# Draw slave-ports:
	for sport in tile.slave_ports:
		(row,col) = sport["location"]
		draw_rectangle(col, row, 1, 1, slave_color)
	# Draw phys:
	for phy in tile.phys:
		(row,col) = phy["location"]
		color = phy_in_color if phy["direction"] == "in" else phy_out_color
		draw_rectangle(col, row, 1, 1, color)
	# Fix ticks
	ax.set_xticks([(x + 0.5) * 0.5 for x in range(cols)])
	ax.set_xticklabels([str(x) for x in range(cols)])
	ax.set_yticks([x + 0.5 for x in range(rows)])
	ax.set_yticklabels([str(x) for x in range(rows)])
	# Make ration between height and width correct
	plt.gca().set_aspect('equal', adjustable='box')
	plt.show()

# Draw a module
def visualize_module(module):
	(rows, cols) = (module.n_rows, module.n_cols)
	fig, ax = plt.subplots()
	# Draw tiles
	for tile in module.tiles:
		(row, col) = tile["location"]
		(height, width) = tile["dimensions"]
		draw_rectangle(col, row, width, height, tile_color)
	# Draw grid
	for row in range(rows + 1):
		draw_line((0,row),(cols,row), grid_color)
	for col in range(cols + 1):
		draw_line((col,0),(col,rows), grid_color)
	# Draw master-ports:
	for mport in module.master_ports:
		(row,col) = mport["location"]
		draw_rectangle(col, row, 1, 1, master_color)
		pid = mport["label"][-2]
		draw_text(col+0.5,row+0.25,pid)
		draw_text(col+0.5,row+0.75,pid)
	# Draw slave-ports:
	for sport in module.slave_ports:
		(row,col) = sport["location"]
		draw_rectangle(col, row, 1, 1, slave_color)
		pid = sport["label"][-2]
		draw_text(col+0.5,row+0.25,pid)
		draw_text(col+0.5,row+0.75,pid)
	# Draw phys:
	for phy in module.phys:
		(row,col) = phy["location"]
		color = phy_in_color if phy["direction"] == "in" else phy_out_color
		draw_rectangle(col, row, 1, 1, color)
		pid = phy["label"][-2]
		draw_text(col+0.5,row+0.25,pid)
		draw_text(col+0.5,row+0.75,pid)
	# Draw collisions:
	grid = module.grid
	for row in range(rows):
		for col in range(cols):
			if type(grid[row][col]) == list and (grid[row][col][0] > 1 or grid[row][col][1] > 1):
				draw_rectangle(col, row, 1, 1, collision_color)
	# Draw connections:
	for con in module.connections:
		for i in range(len(con)-1):
			a = con[i]
			b = con[i+1]
			draw_line((a[1]+0.5,a[0]+0.5),(b[1]+0.5, b[0]+0.5), con_color, True, 1.5)
	# Draw tile-borders
	for tile in module.tiles:
		(row, col) = tile["location"]
		(height, width) = tile["dimensions"]
		draw_rectangle(col, row, width, height, "none", border = True)
	# Fix ticks
	ax.set_xticks([(x + 0.5) * 0.5 for x in range(cols)])
	ax.set_xticklabels([str(x) for x in range(cols)])
	ax.set_yticks([x + 0.5 for x in range(rows)])
	ax.set_yticklabels([str(x) for x in range(rows)])
	# Make ration between height and width correct
	plt.gca().set_aspect('equal', adjustable='box')
	plt.show()

# Draw a 2.5D stacked chip
def visualize_schip(schip):
	(width, height) = (schip.width_in_mm, schip.height_in_mm)
	fig, ax = plt.subplots()
	ax.set_xlim(0,width)
	ax.set_ylim(0,height)
	# Draw stacked chip
	draw_rectangle(0, 0, width, height, schip_color, grid_mode = False)
	# Draw chiplets
	for chiplet in schip.chiplets:
		(x,y) = chiplet["location"]
		(w,h) = (chiplet["width"], chiplet["height"])
		draw_rectangle(x, y, w, h, chiplet_color, grid_mode = False)
		for phy in chiplet["phys"]:
			(x_phy,y_phy) = phy["location"]
			color = phy_in_color if phy["direction"] == "in" else phy_out_color
			draw_circle(x + x_phy, y + y_phy, 0.5, color)
	# Connections
	for ((c1,m1,p1,l1), (c2,m2,p2,l2), _) in schip.connections:
		phy1_loc = phy2_loc = None
		chiplet = schip.chiplets[c1]
		for phy in chiplet["phys"]:
			if phy["label"] == (m1,p1,l1):
				phy1_loc = tadd(chiplet["location"], phy["location"])
		chiplet = schip.chiplets[c2]
		for phy in chiplet["phys"]:
			if phy["label"] == (m2,p2,l2):
				phy2_loc = tadd(chiplet["location"], phy["location"])
		if None not in [phy1_loc, phy2_loc]:
			draw_line(phy1_loc, phy2_loc, con_color, arr = True, lwd= 3, grid_mode = False)
	# Make ratio between height and width correct
	plt.gca().set_aspect('equal', adjustable='box')
	plt.show()

# Read a tile/module/stacked-chip and visualize it
def read_and_visualize(typ, name):
	global wire_ratio
	# Tile
	if typ == "tile":
		tile = Tile(name)
		tech = Technology(tile.technology)
		wire_ratio = tech.mm_per_vertical_wire / tech.mm_per_horizontal_wire
		visualize_tile(tile)
	# Module
	elif typ == "module":
		module = Module(name)
		tech = Technology(module.technology)
		wire_ratio = tech.mm_per_vertical_wire / tech.mm_per_horizontal_wire
		visualize_module(module)
	# 2.5D Stacked Chip
	elif typ == "schip":
		schip = StackedChip(name)
		visualize_schip(schip)
	else:
		msg = "Invalid type \"%s\". Only \"tile\" and \"module\" are valid"
		msg %= typ
		error(__file__, msg)

if __name__ == "__main__":
    args = sys.argv
    if len(args) < 3:
        print("Usage: python visualize_physical_model.py <type in {tile, module, schip}> <name>")
        sys.exit()
    read_and_visualize(args[1], args[2])


import os

import numpy as np

import torch
import torch.optim as optim

class NnetHelper():

	def __init__(self, num_epoch=10, batch_size=64):
		self.num_epoch = num_epoch
		self.batch_size = batch_size

	def train_network(self, nnet, train_examples):

		train_examples = [ex for itr in train_examples for episode in itr for ex in episode]
		np.random.shuffle(train_examples)

		optimizer = optim.Adam(nnet.parameters())

		for _ in range(self.num_epoch):
			for i in range(0, len(train_examples), self.batch_size):

				states, pis, rewards = self.handle_data(train_examples[i:i+self.batch_size])

				pred_pi, pred_v = nnet(states)

				loss_v, loss_pi = self.loss_function(pred_v=pred_v, z=rewards, pi=pis, pred_pi=pred_pi)
				total_loss = loss_pi + loss_v

				optimizer.zero_grad()
				total_loss.backward()
				optimizer.step()

			print('training loss: {:.3f} --- {:.3f}'.format(loss_pi.data.numpy(), loss_v.data.numpy()))

		return nnet

	def handle_data(self, batch_examples):

		states, pis, rewards = zip(*batch_examples)

		states = torch.FloatTensor(np.array(states).astype(np.float64))
		states = states.view(states.size(0), 1, states.size(1), states.size(2))
		pis = torch.FloatTensor(np.array(pis))
		rewards = torch.FloatTensor(np.array(rewards).astype(np.float64))

		return states, pis, rewards

	def loss_function(self, pred_v=None, z=None, pred_pi=None, pi=None):
		v_loss = torch.sum((z - pred_v.view(-1))**2) / z.size(0)
		pi_loss = torch.sum(pi*torch.log(pred_pi + 1e-8)) / pi.size(0)
		return v_loss, -pi_loss

	def save_network(self, nnet, folder=None, filename=None):
		filepath = os.path.join(folder, filename)
		torch.save(nnet.state_dict(), filepath)

	def load_network(self, nnet, folder=None, filename=None):
		filepath = os.path.join(folder, filename)
		cp = torch.load(filepath)
		nnet.load_state_dict(torch.load(filepath))


from numpy.testing._private.utils import assert_equal
import bpy
import numpy as np

xDG = bpy.context.evaluated_depsgraph_get()

objOrigX = bpy.data.objects["HW4L.Surface"]
objX = objOrigX.evaluated_get(xDG)
vglX = objX.vertex_groups

lNames = [x.name for x in vglX]
print(lNames)

lAtVg = [x.name for x in vglX if x.name.startswith("AT.Label;")]
print(lAtVg)

vgX = vglX[lAtVg[0]]
print(vgX)

iVgIdx = vgX.index
print("VG index: {0}".format(iVgIdx))

mWorld = objX.matrix_world

mWorldT = np.array(mWorld.to_3x3()).transpose()
mTrans = np.array(mWorld.translation)

mshX = objX.to_mesh()

# lEdgeIdx = [x.index for i, x in enumerate(mshX.loops) if mshX.vertex_colors[0].data[i].color[0] > 0.0]
# print(lEdgeIdx)
lColVexIdx = [
    x.vertex_index
    for i, x in enumerate(mshX.loops)
    if mshX.vertex_colors[0].data[i].color[0] > 0.0
]
# print("lColVexIdx ({0}):\n{1}\n".format(len(lColVexIdx), lColVexIdx))

# Don't do this, since it also includes edges where only one of the vertices has the color
# lEdgeIdx = [x.edge_index for i, x in enumerate(mshX.loops) if mshX.vertex_colors[0].data[i].color[0] > 0.0]
# print("lEdgeIdx ({0}):\n{1}\n".format(len(lEdgeIdx), lEdgeIdx))

lEdgeIdx = [x.index for x in mshX.edges if all((v in lColVexIdx for v in x.vertices))]
# print("lEdgeIdx ({0}):\n{1}\n".format(len(lEdgeIdx), lEdgeIdx))

lEdgeVexIdx = [[mshX.edges[i].vertices[0], mshX.edges[i].vertices[1]] for i in lEdgeIdx]
# print("lEdgeVexIdx ({0}):\n{1}\n".format(len(lEdgeVexIdx), lEdgeVexIdx))

lVexIdx = list(set([i for lSublist in lEdgeVexIdx for i in lSublist]))
# print("lVexIdx ({0}):\n{1}\n".format(len(lVexIdx), lVexIdx))

aVex = np.array([list(mshX.vertices[i].co) for i in lVexIdx])
# # # print("lVex:")
# # # print(lVex)
# # # print("")

lMyEdgeVexIdx = [
    [lVexIdx.index(lEdge[0]), lVexIdx.index(lEdge[1])] for lEdge in lEdgeVexIdx
]
print("lMyEdgeVexIdx ({0}):\n{1}\n".format(len(lMyEdgeVexIdx), lMyEdgeVexIdx))

lSameVexIdx = [
    lEdge
    for lEdge in lMyEdgeVexIdx
    if np.linalg.norm(aVex[lEdge[0]] - aVex[lEdge[1]]) < 1e-6
]
# print("lSameVexIdx ({0}):\n{1}\n".format(len(lSameVexIdx), lSameVexIdx))

lSameRefIdx = np.arange(aVex.shape[0]).tolist()
# print(lSameRefIdx)

for lSameIdx in lSameVexIdx:
    lSameRefIdx[max(lSameIdx)] = min(lSameIdx)
# endfor
print("lSameRefIdx ({0}):\n{1}\n".format(len(lSameRefIdx), lSameRefIdx))

lUniqueVexIdx = list(set(lSameRefIdx))
print(
    "lUniqueVexIdx ({0}, max: {1}):\n{2}\n".format(
        len(lUniqueVexIdx), max(lUniqueVexIdx), lUniqueVexIdx
    )
)
iUniqueVexCnt = len(lUniqueVexIdx)

aUniqueVex = aVex[lUniqueVexIdx]
# print("aUniqueVex ({0}):\n{1}\n".format(len(aUniqueVex), aUniqueVex))

lMyEdgeVexIdx = [
    [lSameRefIdx[lEdge[0]], lSameRefIdx[lEdge[1]]]
    for lEdge in lMyEdgeVexIdx
    if lSameRefIdx[lEdge[0]] != lSameRefIdx[lEdge[1]]
]
print("lMyEdgeVexIdx ({0}):\n{1}\n".format(len(lMyEdgeVexIdx), lMyEdgeVexIdx))

# Reduce to unique vertex indices
lMyEdgeVexIdx = [
    [lUniqueVexIdx.index(lEdge[0]), lUniqueVexIdx.index(lEdge[1])]
    for lEdge in lMyEdgeVexIdx
]
print("lMyEdgeVexIdx ({0}):\n{1}\n".format(len(lMyEdgeVexIdx), lMyEdgeVexIdx))

setMyEdgeVexIdxHash = set(
    [min(lEdge) * iUniqueVexCnt + max(lEdge) for lEdge in lMyEdgeVexIdx]
)
print(
    "setMyEdgeVexIdxHash ({0}):\n{1}\n".format(
        len(setMyEdgeVexIdxHash), setMyEdgeVexIdxHash
    )
)

lMyUniqueEdge = [
    [int(h / iUniqueVexCnt), h % iUniqueVexCnt] for h in set(setMyEdgeVexIdxHash)
]
print("lMyUniqueEdge ({0}):\n{1}\n".format(len(lMyUniqueEdge), lMyUniqueEdge))

# Parent and Child edges of each edge
lMyConnect = [
    [
        [
            iTestEdgeIdx
            for iTestEdgeIdx, lTestEdge in enumerate(lMyUniqueEdge)
            if iTestEdgeIdx != iEdgeIdx
            and any((iTestVexIdx == iVexIdx for iTestVexIdx in lTestEdge))
        ]
        for iVexIdx in lEdge
    ]
    for iEdgeIdx, lEdge in enumerate(lMyUniqueEdge)
]
print("lMyConnect ({0}):\n{1}\n".format(len(lMyConnect), lMyConnect))

# Find all start edges, if any
lStartEdges = [i for i, lC in enumerate(lMyConnect) if len(lC[0]) == 0]
print("lStartEdges ({0}):\n{1}\n".format(len(lStartEdges), lStartEdges))

# Find connected edges from start edges
lPolygons = []
for iStartIdx in lStartEdges:
    lPoly = []
    iIdx = iStartIdx
    while True:
        lEdge = lMyUniqueEdge[iIdx]
        lPoly.append(lEdge[0])
        lCE = lMyConnect[iIdx]
        if len(lCE[1]) == 0:
            break
        # endif
        iIdx = lCE[1][0]
    # endwhile
    lPoly.append(lEdge[1])
    lPolygons.append(lPoly)
# endfor

print("lPolygons ({0}):\n{1}\n".format(len(lPolygons), lPolygons))


# -*- coding: utf-8 -*-
"""Models for Django Virtual Collection App."""
from django.core.urlresolvers import reverse
from django.db import models
from django.http import QueryDict
from django_extensions.db.fields import AutoSlugField
from django_extensions.db.models import TimeStampedModel
from django.utils.translation import ugettext_lazy as _

from nave.void.models import GroupOwned

class VirtualCollection(TimeStampedModel, GroupOwned):
    """
    The models holds the information for the Virtual collections
    """
    title = models.CharField(
        _("title"),
        max_length=512
    )
    slug = AutoSlugField(populate_from='title')
    body = models.TextField(
        _("body"),
        blank=True,
        null=True
    )
    query = models.TextField(
        _("query"),
        blank=True,
        null=True,
        help_text=_("The full query as used on the search page or search API.")
    )
    oai_pmh = models.BooleanField(
        _("published"),
        default=True,
        help_text=_("Is this collection publicly available.")
    )
    published = models.BooleanField(
        _("published"),
        default=True,
        help_text=_("Is this collection publicly available.")
    )
    owner = models.CharField(
        _("owner key"),
        max_length=512,
        blank=True,
        null=True,
        help_text=_("profile ID, user key, etc")
    )
    creator = models.CharField(
        _("creator"),
        max_length=512,
        blank=True,
        null=True,
        help_text=_("name or institution")
    )

    class Meta(object):
        verbose_name = _("Virtual Collection")
        verbose_name_plural = _("Virtual Collections")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('virtual_collection_detail', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        allowed_filters = ["qf=", 'hfq=', "q=", "hqf[]=", "qf[]="]
        if any(key in self.query for key in allowed_filters):
            # create the proper format string
            filter_list = []
            query_dict = QueryDict(query_string=self.query.split("?", maxsplit=1)[-1])
            for k, v in query_dict.items():
                if any([key.startswith(k) for key in allowed_filters]) and v:
                    applied_filter = query_dict.getlist(k)
                    filter_list.extend(applied_filter)
            self.query = ";;;".join(["\"{}\"".format(k) for k in filter_list])
        super(VirtualCollection, self).save(*args, **kwargs)

class VirtualCollectionFacet(models.Model):
    """
    Facets to be retrieved and displayed
    """
    diw = models.ForeignKey(
        VirtualCollection,
        related_name="facets"
    )

    name = models.CharField(
        max_length=55,
        blank=False,
        help_text=_("The desired field to retrieve ie: dc_creator_facet, dc_subject_facet"),
        verbose_name=_("Facet field")
    )

    label = models.CharField(
        max_length=55,
        blank=False,
        help_text=_("The label to appear above the list of retrieved facets"),
        verbose_name=_("Facet header")
    )

    position = models.PositiveSmallIntegerField(
        "Position",
        default=0
    )
    facet_size = models.PositiveSmallIntegerField(
        "Facet-size",
        default=50
    )

    class Meta:
        verbose_name = _("Facet")
        verbose_name_plural = _("Facets")
        ordering = ['position']

class VirtualCollectionOrQuery(models.Model):
    """
    Or queries related to the main query
    """
    diw = models.ForeignKey(
        VirtualCollection,
        related_name="orqueries"
    )
    query = models.TextField(
        _("query"),
        blank=True,
        null=True,
        help_text=_("Additional or queries")
    )
    position = models.PositiveSmallIntegerField(
        "Position",
        default=0
    )

    def save(self, *args, **kwargs):
        allowed_filters = ["qf=", 'hfq=', "q=", "hqf[]=", "qf[]="]
        if any(key in self.query for key in allowed_filters):
            # create the proper format string
            filter_list = []
            query_dict = QueryDict(query_string=self.query.split("?", maxsplit=1)[-1])
            for k, v in query_dict.items():
                if any([key.startswith(k) for key in allowed_filters]) and v:
                    applied_filter = query_dict.getlist(k)
                    filter_list.extend(applied_filter)
            self.query = ";;;".join(["\"{}\"".format(k) for k in filter_list])
        super(VirtualCollectionOrQuery, self).save(*args, **kwargs)

    class Meta:
        verbose_name = _("Or Query")
        verbose_name_plural = _("Or Queries")
        ordering = ['position']


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import logging

from gapipy.exceptions import EmptyPartialUpdateError
from gapipy.models.base import BaseModel
from gapipy.request import APIRequestor
from gapipy.utils import enforce_string_type

logger = logging.getLogger(__name__)

class Resource(BaseModel):

    _resource_name = None
    _is_parent_resource = False
    _is_listable = True  # True if resource can be listed/queried (i.e /{resource_name} is an endpoint)
    _uri = None

    def __init__(self, data, stub=False, client=None):
        self.is_stub = stub
        if not self._uri:
            self._uri = self._resource_name
        super(Resource, self).__init__(data, client)

    @classmethod
    def options(cls, client):
        return APIRequestor(client, cls).options()

    def fetch(self, httperrors_mapped_to_none=None):
        """
        httperrors_mapped_to_none is a list of HTTP errors we will silently absorb (i.e.
        not float up). This brings back behavior prior to 2.25.0.
        ref: https://github.com/gadventures/gapipy/pull/119
        """
        logger.info('Fetching %s/%s', self._resource_name, self.id)

        # Fetch the resource using the client bound on it, which handles cache get/set.
        resource_obj = getattr(self._client, self._resource_name).get(
            self.id,
            variation_id=getattr(self, 'variation_id', None),
            httperrors_mapped_to_none=httperrors_mapped_to_none)
        if resource_obj:
            self._fill_fields(resource_obj._raw_data)
            self.is_stub = False

        return self

    @classmethod
    def create(cls, client, data_dict, headers=None):
        request = APIRequestor(client, cls)
        response = request.create(json.dumps(data_dict), headers=headers)
        return cls(response, client=client)

    def __getattr__(self, name):
        # If we try to access a field that's allowed, and this resource is a
        # stub, we need to fetch it.
        if name == 'id':
            raise AttributeError(
                'No id found for Resource %s. Possibly caused due to bad or stale data.' % self._resource_name
            )

        if name in self._allowed_fields() and self.is_stub:
            self.fetch()
            return self.__getattribute__(name)

        raise AttributeError("%r has no field %r available" % (type(self).__name__, name))

    @enforce_string_type
    def __repr__(self):
        if self.is_stub:
            return '<{}: {} (stub)>'.format(self.__class__.__name__, self.id)
        else:
            return '<{}: {}>'.format(self.__class__.__name__, self.id)

    def __hash__(self):
        return hash('{}{}'.format(self.__class__.__name__, self.id))

    def __eq__(self, other):
        # Same resource name and ID determine equality
        return (
            self._resource_name == getattr(other, '_resource_name', None)
            and self.id == other.id
        )

    def __ne__(self, other):
        return not self.__eq__(other)

    def to_json(self):
        return json.dumps(self.to_dict())

    def _update(self, partial=False):
        request = APIRequestor(self._client, self)

        # payload to send
        data = self.to_dict()

        # when making a partial (PATCH) request, ensure we only include values
        # changed on self compared to the initial raw response received from
        # the G API.
        #
        # Added (2.35.0): If the change computed results in an empty data
        #                 dictionary we'll raise a EmptyPartialUpdateError
        if partial:
            data = {k: v for k, v in data.items() if self._raw_data.get(k) != v}
            if not data:
                raise EmptyPartialUpdateError

        return request.update(self.id, json.dumps(data), partial=partial)

    def _create(self):
        request = APIRequestor(self._client, self)
        return request.create(self.to_json())

    def save(self, partial=False):
        """
        Save the current state of the resource to GAPI. If a new instance, it
        will result in a POST request to the G API, otherwise depending on the
        value of partial, will result in a PUT request if partial is `False`
        otherwise a PATCH request.

        Added (2.35.0): we check if a partial update threw an exception and
                        re-raise it if the client has been configured to do so
                        via raise_on_empty_update config option.
        """

        # update if we have an `id` value
        #
        # due to the explicit check for `id` in __getattr__, we need to check
        # the __dict__ directly for the `id` attribute... 🐔 & 🥚 situation
        is_update = 'id' in self.__dict__ and self.__dict__['id']
        if is_update:
            try:
                result = self._update(partial=partial)
            except EmptyPartialUpdateError:
                if self._client.raise_on_empty_update:
                    raise
                # return early to avoid calling _fill_fields unnecessarily
                return self
        else:
            result = self._create()

        # set result fields as attributes
        self._fill_fields(result)
        return self


"""empty message

Revision ID: 51ae747709ff
Revises: 821602078adc
Create Date: 2023-07-16 01:02:43.969265

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '51ae747709ff'
down_revision = '821602078adc'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Field', sa.Column('year', sa.Integer(), nullable=True))
    op.drop_column('Group', 'year')
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Group', sa.Column('year', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_column('Field', 'year')
    # ### end Alembic commands ###


# libraries
import networkx as nx
import matplotlib.pyplot as plt
import math
import sys

# Custom files
import config as cfg

# Visualize graph given as a BookSim anynet input file
def visualize(anynet_file, cols):

	# Initialize graph
	G=nx.DiGraph()

	# Read anynet file
	routers = []
	nodes = []
	node_parents = {}
	edges = []
	with open(cfg.bs_topologies + anynet_file + ".anynet", "r") as file:
		lines = file.readlines()
		n = len(lines)
		for line in lines:
			words = line.split(" ")
			cur = words.pop(0) + words.pop(0)
			routers.append(cur)
			while len(words) > 0:
				nxt = words.pop(0) + words.pop(0)
				if "router" in nxt:
					words.pop(0)
				if "node" in nxt:
					nodes.append(nxt)
					node_parents[nxt] = cur
				edges.append((cur,nxt))

	# compute rows to display
	rows = math.ceil(len(routers) / cols)

	# Compute router positions (only to visualize, not corresponding to physical locations)
	# and add routers to graph
	router_pos = {}
	for i in range(len(routers)):
		router = routers[i]
		row = i // cols
		col = i % cols
		pos = (col + 0.3 * min(row,rows-row-1)**0.5,\
			   row + 0.3 * min(col,cols-col-1)**0.5)
		G.add_node(router, pos = pos)
		router_pos[router] = pos

	# Compute endpoint positions: Arrange them in a circle around their router
	# and add nodes to graph
	nodes_per_router = {router : 0 for router in routers}
	for i in range(len(nodes)):
		nodes_per_router[router] += 1
		node = nodes[i]
		router = node_parents[node]
		pos = router_pos[router]
		node_cnt = (len(nodes)/len(routers))
		node_idx = nodes_per_router[router]
		r = 0.33
		t = ((3.141592654 / 4) + (2 * 3.141592654 / node_cnt * node_idx)) % (2 * 3.141502654)
		x = r*math.cos(t) + pos[0];
		y = r*math.sin(t) + pos[1];
		G.add_node(node, pos = (x,y))

	# Add edges to graph
	for edge in edges:
		G.add_edge(edge[0], edge[1])

	# Color-coded vertices
	color_map = []
	for node in G:
		if "router" in node:
			color_map.append("#009900")
		else:
			color_map.append("#000099")

	# Draw graph
	nx.draw(	G,
				pos=nx.get_node_attributes(G,'pos'),
				node_color=color_map,
				with_labels=True,
				node_size=500,
				node_shape="o",
				alpha=0.5,
				linewidths=2,
				arrowstyle="-|>",
    			arrowsize=10,
			)
	plt.show()

### Main ###
if __name__ == "__main__":
	args = sys.argv
	if len(args) < 3:
		print("Usage: python %s <filename> <cols>" % args[0])
		sys.exit()
	visualize(args[1], int(args[2]))


__author__ = '310176470'

from sklearn.svm import OneClassSVM
import pandas as pd

# dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d')
train_data = pd.read_csv("subject_1.csv", header=0, index_col=1, parse_dates=[1])
test_data = pd.read_csv("subject_2.csv", header=0, index_col=1, parse_dates=[1])

# print(train_data)

clf = OneClassSVM()
output_training = clf.fit(train_data)

print(output_training)

print(test_data)

# for data in test_data:
# 	if clf.predict(data) < 0:
# 		print(data)


import math
import copy
from datetime import datetime
global tour_list,best_list, best_distance
tour_list = []
best_list = []
best_distance = 1000

def read_file():
    file_name = input('파일이름을 입력하시오 : ')
    with open(file_name,'r',encoding='UTF8') as f:
        global n, x_list, y_list , tour_list
        text = f.read()
        line = text.split('\n')
        n = int(line[0])  # 첫 줄의 첫 원소 = n
        x_list = []
        y_list = []
        for i in range(1,n+1):
            token = line[i].split()
            x_list.append(int(token[0]))
            y_list.append(int(token[1]))
        for i in range(0,n):
            tour_list.append(i)

def swap(k,i):
    global x_list,y_list,tour_list
    temp = x_list[k]
    x_list[k] = x_list[i]
    x_list[i] = temp
    temp = y_list[k]
    y_list[k] = y_list[i]
    y_list[i] = temp
    temp = tour_list[k]
    tour_list[k] = tour_list[i]
    tour_list[i] = temp

def tour(k,curdist):
    global n, x_list, y_list,best_distance,tour_list,best_list
    check = 0
    if curdist >= best_distance:
        check = 1
    elif k==n:
        curdist += (((x_list[k-1]-x_list[0])**2) + (y_list[k-1]-y_list[0])**2)**0.5
        if best_distance > curdist:
            best_distance = curdist
            best_list = copy.deepcopy(tour_list)
    for i in range(k, n):
        swap(k,i)
        tour(k+1,curdist + ((((x_list[k] - x_list[k - 1]) ** 2) + ((y_list[k] - y_list[k - 1]) ** 2)) ** 0.5))
        swap(k,i)
read_file()
now = datetime.now()
print('start : %s:%s:%s'%(now.hour,now.minute,now.second))
tour(1,0)
print(best_distance,'\n',best_list)
now = datetime.now()
print('end : %s:%s:%s'%(now.hour,now.minute,now.second))


from flask import Flask, render_template, url_for, request, redirect
from test import *

app = Flask(__name__, static_url_path='/static',static_folder='static')

#defining view routes
@app.route('/')
@app.route('/index/')
@app.route('/home/')
def index():
    return render_template('index.html')

@app.route('/index/#roomselect')
def room():
    return redirect('/index/#roomselect')

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

    #checking the form user submitted
    #validating formsX
    selected = ""
    direction = []

    if request.method == "GET":

        #passing arguments to the AI based on the selected input
        if request.args['submit'] == 'submit_office':
            office = request.args['offices']
            selected = office
            direction =  main_ai(selected)#passing user input to the ai

            #returning the generated path/direction to the web browser
            return render_template('direction.html',direction = direction)

        if request.args['submit'] == 'submit_lab':
            lab = request.args['labrooms']
            selected = lab
            direction = main_ai(selected)#passing user input to the ai

            #returning the generate path/direction to the web server
            return render_template('direction.html',direction = direction)
        if request.args['submit'] == 'submit_lecture':
            lecture_room = request.args['lecturerooms']
            selected = lecture_room
            direction = main_ai(selected)#passing user input to the ai

            #returning the generate path/direction to the web server
            return render_template('direction.html',direction = direction)
    #fall back mechanism
    else:
        return redirect(url_for('index.html'))

#@app.route("/<room>")
#def show_data(room):
   # return f"<h1>{room}</h1>"

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


from jina import Client
from docarray import Document

client = Client(host='localhost', port=23456)

query = Document(text="Can I catch COVID from my pet armadillo?")

search_filter = {"source": {"$eq": "biomedical"}}

results = client.search(query, parameters={"filter": search_filter})

for result in results:
    print(result.text)


from statistics import mean
import matplotlib.pyplot as plt

from benchmarks.utils import read_data

def read_mean_sym_time(file):
    data = read_data(file)
    sym_times = [row[1] for row in data]
    return mean(sym_times)

def create_plot(file_template, algorithms, models):
    bar_width = 0.2
    x_step = bar_width * (len(models) + 1)
    x_poses = [x_step * i for i in range(len(algorithms))]
    colors = ['blue', 'red']
    for i, model in enumerate(models):
        x = []
        y = []
        for j, alg in enumerate(algorithms):
            sym_time = read_mean_sym_time(file_template.format(alg, model))
            x.append(x_step * j + i * bar_width)
            y.append(sym_time)
        plt.bar(x, y, color=colors[i], width=bar_width, edgecolor='grey', label=model)
    plt.xlabel('Algorithm')
    plt.ylabel('Simulation time (secs.)')
    print(x_poses)
    plt.xticks([r + bar_width / 2 for r in x_poses], algorithms)
    plt.legend()
    plt.title('Compairing ESRN and Izhikevich(cpu1=1, cpu2=1, cpu3=1')
    plt.savefig('fig/esrn_izh_1_1_1.png', dpi=500)

if __name__ == '__main__':
    algs = ['weighted_fluid', 'fluid', 'spinglass', 'fast_greedy', 'walktrap']
    input_models = ['esrn', 'izh']
    create_plot('res/1_1_1/{}_{}_reflect_arc.csv', algs, input_models)


import unittest
import selenium
import os

class ClosureWithSeleniumTestType(type):
    def __new__(cls, name, bases, attrs):
        cls.createTestMethods(attrs)
        return type.__new__(cls, name, bases, attrs)

    @classmethod
    def createTestMethods(cls, attrs):
        urlPrefix = attrs['urlPrefix']
        for key, url in attrs['urlsToTest'].iteritems():
            attrs['test%s' % key.capitalize()] = cls.createTestMethod('%s%s' % (urlPrefix, url))

    @classmethod
    def createTestMethod(cls, url):
        return lambda self: self._testClosureUrl(url)

class GroovesharkControlTest(unittest.TestCase):
    __metaclass__ = ClosureWithSeleniumTestType

    # Must be call by Makefile on root of repository.
    urlPrefix = 'file://%s/groovesharkControl/javascript/' % os.getcwd()
    urlsToTest = {
        'background': 'background/background_test.html',
        'contextMenu': 'background/contextMenu_test.html',
        'viewUpdater': 'groovesharkControl/viewUpdater_test.html',
        'closure_i18n': 'libs/closure-i18n_test.html',
    }

    @classmethod
    def setUpClass(cls):
        cls.selenium = selenium.selenium('localhost', 4444, '*chrome', 'http://www.google.com/')
        cls.selenium.start()

    def _testClosureUrl(self, url):
        sel = self.__class__.selenium
        sel.open(url)
        sel.wait_for_condition('window.G_testRunner && window.G_testRunner.isFinished()', '5000')
        success = sel.get_eval('window.G_testRunner.isSuccess()') == 'true'
        if not success:
            report = sel.get_eval('window.G_testRunner.getReport()')
            self.fail(report)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.stop()

if __name__ == '__main__':
    unittest.main(verbosity=2)


# from django.conf.urls import include
from django.urls import path
from api_test import views

app_name='api_test'
urlpatterns=[
    path('add/',views.add_things,name='add'),
    path('show/',views.show_things,name='show'),

    #这个啥 $ 好像不行 我以为是我 http api 测试有问题，还去找一堆api测试工具装   玩不明白
    # path(r'add$',views.add_things,name='add'),
    # path(r'show$',views.show_things,name='show'),
]


from django.urls import path, include

from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('profile/<int:profile_id>/', views.profile_page, name='profile_page'),
    path('profile/<int:pk>/review/', views.CommentCreateView.as_view(), name='review'),
    path('profile/<int:user_id>/<int:pk>/', views.CommentDeleteView.as_view(), name='comment-delete'),
    path('profile/<int:profile_id>/edit/', views.edit_profile, name='edit_profile'),
    path('inbox/', views.inbox, name='inbox'),
    path('request/<int:pk>/', views.AskDetailView.as_view(), name='ask-detail'),
    path('request/<int:pk>/delete/', views.AskDeleteView.as_view(), name='ask-delete'),
    path('request/<int:pk>/complete/', views.AskCompleteView.as_view(), name='ask-complete'),
    path('request/<int:ask_id>/accept/', views.accept_ask, name='ask-accept'),
    path('request/<int:ask_id>/decline/', views.decline_ask, name='ask-decline'),
]


import random

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        cats = [
            {"image": "images/1.jpg", "name": "Шаурма"},
            {"image": "images/2.jpg", "name": "Пуля"},
            {"image": "images/3.jpeg", "name": "Кама"},
            {"image": "images/4.jpg", "name": "Ежжи"},
            {"image": "images/5.jpg", "name": "Барсик"},
        ]
        catOfTheDay = random.choice(cats)
        self.render("page.html", cat=catOfTheDay)

settings = [
    (r"/", MainHandler),
    (r'/images/(.*)', tornado.web.StaticFileHandler, {'path': 'images'})
]
app = tornado.web.Application(settings)
app.listen(8888)
tornado.ioloop.IOLoop.current().start()


#!/usr/bin/env python3

import argparse
from typing import Iterable

import numpy as np

def verify_x(inputs: Iterable[int], x: Iterable[int]) -> Iterable[int]:
    inputs_matrix = np.array(inputs)
    same_nutrients_per_row_matrix = inputs_matrix.transpose()

    x_vector = np.array(x)
    return np.dot(same_nutrients_per_row_matrix, x_vector)

def solve_for_multiples(inputs: Iterable[Iterable[int]], target: Iterable[int]) -> Iterable[int]:
    inputs_matrix = np.array(inputs)
    same_nutrients_per_row_matrix = inputs_matrix.transpose()
    target_array = np.array(target)
    return np.linalg.solve(same_nutrients_per_row_matrix, target_array)

def parse_npk(npk: str) -> Iterable[int]:
    return [int(n) for n in npk.split('-')]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Calculate the ratios and amount of fertilizers to add to water')
    parser.add_argument('--inputs', required=True, type=str, nargs='+',
        help='The n-p-k ratios of the input solutions, inputted in the following format: <n1>-<p1>-<k1> <n2>-<p2...')
    parser.add_argument('--target', default=None, type=int, nargs='+',
                    help='The target n-p-k ratio to achieve with the input solutions.')
    parser.add_argument('--x', type=float, default=None, nargs='+', required=False, help='input solutions multiplers. The inputs will be multiplied with this when it is supplied and the first number of the returned vector is the multiplier for the first solution and so on')
    args = parser.parse_args()

    inputs = [parse_npk(s) for s in args.inputs]

    if args.x is None:
        if args.target is None:
            raise Exception('Provide --target when calculating x for --inputs')

        print(solve_for_multiples(inputs, args.target))
    else:
        print(verify_x(inputs, args.x))


import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits import mplot3d
import pandas as pd
import numpy as np
import seaborn as sns
import copy
import collections
from functools import reduce
from pathlib import Path
from statistical_tests import StatisticalTests
from datetime import datetime, timedelta
from matplotlib import dates as mpl_dates

class Plots:

    def __init__(self):
        pass

    def change_to_percents(self, df, label_list, number_columns):
        sum_elements = sum(list(df.values()))
        temp_value = [0 for i in range(number_columns + 1)]
        res_dict = dict(zip(label_list, temp_value))
        for i in label_list:
            res_dict[i] = (df[i] / sum_elements) * 100

        return res_dict

    def calculate_structure_population_age_based_range(self, list_df, save_name):
        x_pos = list()
        y_pos = ['2014a', '2014b', '2015a', '2015b', '2016a', '2016b', '2017a', '2017b', '2018a', '2018b', '2019']
        z_pos = list()
        # label_list = [i + 1 for i in range(6)]
        label_list = ['18-24', "25-34", '35-44', '45-54', '55-64', '65+']
        temp_value = [0 for i in range(6)]
        structure_population_list = list()
        for df, save in zip(list_df, save_name):
            # print('df in calculate')
            # print(df)
            range_birth = (df.iloc[:, 1]).to_list()
            # print('range_birth')
            # print(range_birth)
            structure_population = dict(zip(label_list, temp_value))
            for year in range_birth:
                if year == '18-24':
                    structure_population[label_list[0]] += 1
                elif year == '25-34':
                    structure_population[label_list[1]] += 1
                elif year == '35-44':
                    structure_population[label_list[2]] += 1
                elif year == '45-54':
                    structure_population[label_list[3]] += 1
                elif year == '55-64':
                    structure_population[label_list[4]] += 1
                elif year == '65+':
                    structure_population[label_list[5]] += 1
                else:
                    continue

            structure_population_list.append(structure_population)

            x_pos.append(structure_population.values())
            z_pos.append(structure_population.keys())
            plt.bar(structure_population.keys(), structure_population.values())
            plt.ylim(top=1000)
            plt.ylim(bottom=0)
            plt.xlabel('Grupa wiekowa')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram struktury wieku uczestników badania - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/population_age/hist_' + save + '.png')
            plt.clf()

        plt.savefig('results/histograms/population_age/hist_3d.png')
        plt.clf()
        return structure_population_list

    def calculate_structure_education(self, list_df, save_name):
        legend_list = ["Podstawowe", "Zasadnicze zawodowe", "Średnie ogólnokształcące", "Średnie techniczne",
                       "Pomaturalne", "Studia wyższe niepełne", "Studia wyższe ukończone"]
        temp_value = [0 for i in range(7)]
        label_list = [i + 1 for i in range(7)]
        education_list = list()
        for df, save in zip(list_df, save_name):
            temp = df.iloc[:, 1].to_list()
            education_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    education_dict[label_list[0]] += 1
                elif i == 2:
                    education_dict[label_list[1]] += 1
                elif i == 3:
                    education_dict[label_list[2]] += 1
                elif i == 4:
                    education_dict[label_list[3]] += 1
                elif i == 5:
                    education_dict[label_list[4]] += 1
                elif i == 6:
                    education_dict[label_list[5]] += 1
                elif i == 7:
                    education_dict[label_list[6]] += 1

            education_dict_percents = self.change_to_percents(education_dict, label_list, 7)
            education_list.append(education_dict_percents)
            colors = list('rgbkymc')
            handles = list()
            plt.bar(education_dict.keys(), education_dict.values(), color=colors)
            handles = list()
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('Poziom wykształcenia')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1200)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram poziomu wykształcenia uczestników badania - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/education/hist_' + save + '.png')
            plt.clf()

        return education_list

    def calculate_structure_accomodation(self, list_df, save_name):
        legend_list = ["W wysokim bloku (>= 5 pięter)", "W niskim bloku (<= 4 pięter)", "W kamienicy",
                       "W domu w zabudowie szeregowej", "W domu jednorodzinnym"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]
        accommodation_list = list()
        for df, save in zip(list_df, save_name):
            accommodation_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    accommodation_dict[label_list[0]] += 1
                elif i == 2:
                    accommodation_dict[label_list[1]] += 1
                elif i == 3:
                    accommodation_dict[label_list[2]] += 1
                elif i == 4:
                    accommodation_dict[label_list[3]] += 1
                elif i == 5:
                    accommodation_dict[label_list[4]] += 1

            accommodation_dict_percents = self.change_to_percents(accommodation_dict, label_list, 5)
            accommodation_list.append(accommodation_dict_percents)
            colors = list('rgbkymc')
            handles = list()
            plt.bar(accommodation_dict.keys(), accommodation_dict.values(), color=colors)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.ylim(top=1000)
            plt.ylim(bottom=0)
            plt.xlabel('Miejsce zamieszkania')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram rozkładu miejsca zamieszkania uczestników badania - ' + year + ' ' + month, fontsize=9)
            plt.savefig('results/histograms/accomodation/hist_' + save + '.png')
            plt.clf()

        return accommodation_list

    def calculate_A2(self, list_df, save_name):
        legend_list = ["Zdecydowanie tak", "Raczej tak", "Ani tak, ani nie",
                       "Raczej nie", "Zdecydowanie nie"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]

        a2_list = list()
        for df, save in zip(list_df, save_name):
            A2_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    A2_dict[label_list[0]] += 1
                elif i == 2:
                    A2_dict[label_list[1]] += 1
                elif i == 3:
                    A2_dict[label_list[2]] += 1
                elif i == 4:
                    A2_dict[label_list[3]] += 1
                elif i == 5:
                    A2_dict[label_list[4]] += 1

            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A2_dict[i])
            a2_list.append(A2_dict)
            colors = list('rgbymc')
            handles = list()
            plt.bar(A2_dict.keys(), A2_dict.values(), color=colors, yerr=error_dict.values(), ecolor='black',
                    capsize=10)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('5-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w Krakowie - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/A2/hist_' + save + '.png')
            plt.clf()

        return a2_list

    def calculate_A2_with_3_cat(self, list_df, save_name):
        legend_list = ["tak", "Ani tak, ani nie", "nie"]
        temp_value = [0 for i in range(3)]
        label_list = [i + 1 for i in range(3)]

        a2_list = list()
        for df, save in zip(list_df, save_name):
            A2_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1 or i == 2:
                    A2_dict[label_list[0]] += 1
                elif i == 3:
                    A2_dict[label_list[1]] += 1
                elif i == 4 or i == 5:
                    A2_dict[label_list[2]] += 1

            A2_dict_percents = self.change_to_percents(A2_dict, label_list, 3)
            a2_list.append(A2_dict_percents)
            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A2_dict[i])

            colors = list('rgbymc')
            handles = list()
            plt.bar(A2_dict.keys(), A2_dict.values(), color=colors, yerr=error_dict.values(), ecolor='black',
                    capsize=10)
            plt.xticks(range(1, 4))
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('3-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w Krakowie - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/A2_ver_2/hist_' + save + '.png')
            plt.clf()

        return a2_list

    def calculate_fear_index_affective_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            affective_list = list()
            affective_dict = dict()
            for i in range(2):
                temp = list()
                df_list = df.iloc[:, i].to_list()
                for col in df_list:
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    elif col == 2:
                        temp.append(7.5)
                    elif col == 3:
                        temp.append(15)
                    elif col == 4:
                        temp.append(22.5)
                    elif col == 5:
                        temp.append(30)
                    affective_dict[str(i + 1)] = temp
            for i, j in zip(affective_dict['1'], affective_dict['2']):
                affective_list.append((i + j) / 2)
            df_dict[number] = affective_list

        return df_dict

    def calculate_fear_index_cognitive_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            list_all = list()
            cognitive_dict = dict()
            for i in range(2, 10):
                temp = list()
                for col in df.iloc[:, i].to_list():
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1:
                        temp.append(3.75)
                    elif col == 2:
                        temp.append(2.81)
                    elif col == 3:
                        temp.append(1.88)
                    elif col == 4:
                        temp.append(0.94)
                    elif col == 5 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    cognitive_dict[str(i)] = temp
            for i in cognitive_dict.keys():
                list_all.append(cognitive_dict[i])
            list_all = np.array(list_all)
            cognitive_list = np.sum(list_all, axis=0)
            df_dict[number] = cognitive_list
        return df_dict

    def calculate_fear_index_behavioral_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            list_all = list()
            behavioral_dict = dict()
            for i in range(10, 21):
                temp = list()
                for col in df.iloc[:, i].to_list():
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1:
                        temp.append(2.73)
                    elif col == 2:
                        temp.append(2.05)
                    elif col == 3:
                        temp.append(1.36)
                    elif col == 4:
                        temp.append(0.68)
                    elif col == 5 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    behavioral_dict[str(i)] = temp
            for i in behavioral_dict.keys():
                list_all.append(behavioral_dict[i])
            list_all = np.array(list_all)
            behavioral_list = np.sum(list_all, axis=0)
            df_dict[number] = behavioral_list
        return df_dict

    def calculate_fear_index(self, list_df, save_name):
        legend_list = ["bardzo niski", "raczej niski", "średni",
                       "raczej wysoki", "bardzo wysoki"]
        legend_list_3_cat = ["niski", "średni", "wysoki"]
        affective_dict = self.calculate_fear_index_affective_part(list_df)
        cognitive_dict = self.calculate_fear_index_cognitive_part(list_df)
        behavioral_dict = self.calculate_fear_index_behavioral_part(list_df)
        list_all = list()
        for i in affective_dict.keys():
            temp = np.array([affective_dict[i], cognitive_dict[i], behavioral_dict[i]])
            list_all.append(np.sum(temp, axis=0))

        label_list = [i + 1 for i in range(5)]
        temp_value = [0 for i in range(5)]
        label_list_3_cat = [i + 1 for i in range(3)]
        temp_value_3_cat = [0 for i in range(3)]
        fear_list_df = list()
        fear_list_df_3_cat = list()
        for element, save in zip(list_all, save_name):
            fear_index_dict = dict(zip(label_list, temp_value))
            fear_index_dict_3_cat = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in element:
                if 0 <= i < 30:
                    fear_index_dict[label_list[0]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[0]] += 1
                elif 30 <= i < 40:
                    fear_index_dict[label_list[1]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 40 <= i < 50:
                    fear_index_dict[label_list[2]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 50 <= i < 60:
                    fear_index_dict[label_list[3]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 60 <= i <= 90:
                    fear_index_dict[label_list[4]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[2]] += 1

            error_dict = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in label_list_3_cat:
                error_dict[i] = np.sqrt(fear_index_dict_3_cat[i])
            fear_index_dict_percents = self.change_to_percents(fear_index_dict, label_list, 5)
            fear_list_df.append(fear_index_dict_percents)
            fear_index_dict_percents_3_cat = self.change_to_percents(fear_index_dict_3_cat, label_list_3_cat, 3)
            fear_list_df_3_cat.append(fear_index_dict_percents_3_cat)
            colors = list('rgb')
            handles = list()
            plt.bar(fear_index_dict_3_cat.keys(), fear_index_dict_3_cat.values(), yerr=error_dict.values(),
                    ecolor='black', capsize=10, color=colors)
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            plt.xticks(range(1, 4))
            for name, number, color in zip(legend_list_3_cat, label_list_3_cat, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('Wartość indeksu strachu')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Indeks strachu - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/fear_index_3_cat/hist_' + save + '.png')
            plt.clf()

        return list_all, fear_list_df, fear_list_df_3_cat, affective_dict, cognitive_dict, behavioral_dict

    def calculate_A3(self, list_df, save_name):
        legend_list = ["Zdecydowanie tak", "Raczej tak", "Ani tak, ani nie",
                       "Raczej nie", "Zdecydowanie nie"]
        legend_list_cat3 = ["tak", "Ani tak, ani nie", "nie"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]
        temp_value_3_cat = [0 for i in range(3)]
        label_list_3_cat = [i + 1 for i in range(3)]
        a3_list = list()
        a3_list_3_cat = list()
        for df, save in zip(list_df, save_name):
            A3_dict = dict(zip(label_list, temp_value))
            A3_dict_3_cat = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    A3_dict[label_list[0]] += 1
                    A3_dict_3_cat[label_list[0]] += 1
                elif i == 2:
                    A3_dict[label_list[1]] += 1
                    A3_dict_3_cat[label_list[0]] += 1
                elif i == 3:
                    A3_dict[label_list[2]] += 1
                    A3_dict_3_cat[label_list[1]] += 1
                elif i == 4:
                    A3_dict[label_list[3]] += 1
                    A3_dict_3_cat[label_list[2]] += 1
                elif i == 5:
                    A3_dict[label_list[4]] += 1
                    A3_dict_3_cat[label_list[2]] += 1

            colors = list('rgbkymc')
            handles = list()
            A3_dict_percents = self.change_to_percents(A3_dict, label_list, 5)
            A3_dict_percents_3_cat = self.change_to_percents(A3_dict_3_cat, label_list_3_cat, 3)
            a3_list.append(A3_dict_percents)
            a3_list_3_cat.append(A3_dict_percents_3_cat)
            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A3_dict[i])
            plt.bar(A3_dict.keys(), A3_dict.values(), yerr=error_dict.values(), ecolor='black', capsize=10,
                    color=colors)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('5-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w poszczególnych dzielnicach Krakowa - ' + year + ' ' + month,
                      fontsize='10')
            plt.savefig('results/histograms/A3/hist_' + save + '.png')
            plt.clf()
        return a3_list, a3_list_3_cat

    def create_time_series(self, list_dicts, question, number_of_answers, label_x):
        label_list = [i + 1 for i in range(number_of_answers)]
        data_label = ['2014 III', '2014 IX', '2015 VI', '2015 IX', '2016 III', '2016 IX',
                      '2017 VI', '2017 IX', '2018 VI', '2018 IX', '2019 VIII']

        dates = [
            datetime(2014, 3, 1),
            datetime(2014, 9, 1),
            datetime(2015, 6, 1),
            datetime(2015, 9, 1),
            datetime(2016, 3, 1),
            datetime(2016, 9, 1),
            datetime(2017, 6, 1),
            datetime(2017, 9, 1),
            datetime(2018, 6, 1),
            datetime(2018, 9, 1),
            datetime(2019, 8, 1)]

        temp_dict = collections.defaultdict(list)
        error_dict = collections.defaultdict(list)
        error_value_up_dict = collections.defaultdict(list)
        error_value_down_dict = collections.defaultdict(list)
        for i in list_dicts:
            for label in label_list:
                temp_dict[label].append(i[label])
                error = np.sqrt(i[label])
                error_dict[label].append(error)
                error_value_up_dict[label].append(i[label] + error)
                error_value_down_dict[label].append(i[label] - error)

        for i, label in zip(label_list, label_x):
            plt.xticks(fontsize=7)
            plt.plot_date(dates, temp_dict[i], linestyle='solid', color='black')
            plt.plot_date(dates, error_value_up_dict[i], fmt='--', color='k', linewidth=0.5)
            plt.plot_date(dates, error_value_down_dict[i], fmt='--', color='k', linewidth=0.5)
            plt.ylim(top=100)
            plt.ylim(bottom=0)
            plt.xlabel('Data')
            plt.ylabel('Procent respodentów')
            plt.title("Zmiana odpowiedzi '" + label + "' dla skali subiektywnego ryzyka wiktymizacjii", fontsize='9')

            plt.savefig('results/time_series/' + question + '/' + str(i) + '.png', dpi=300)
            plt.clf()


import cv2
import mediapipe as mp
import time

class handDetector():
    #Detection model initialization
    def __init__(self, mode=False, maxHands = 2, modelCom = 1, detectionCon = 0.5, trackCon=0.5 ):
        # static_image_mode = False,
        # max_num_hands = 2,
        # model_complexity = 1,
        # min_detection_confidence = 0.5,
        # min_tracking_confidence = 0.5

        self.mode = mode
        self.maxHands = maxHands
        self.modelCom = modelCom
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands #Mediapipe hand detection
        self.hands = self.mpHands.Hands(self.mode,self.maxHands,self.modelCom,self.detectionCon,self.trackCon) #create an object for detect hands
        self.mpDraw = mp.solutions.drawing_utils #object for draw hand landmarks

    #hand detector method
    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #convert image to RGB
        self.results = self.hands.process(imgRGB) #call hands object

        #retrived and visualized hands info
        if self.results.multi_hand_landmarks:
            for handLMS in self.results.multi_hand_landmarks:
                #Check weather draw is True
                if draw:
                    self.mpDraw.draw_landmarks(img, handLMS, self.mpHands.HAND_CONNECTIONS) #visualized the hand landmarks

        return img

    #land mark position values extract
    def findPosition(self, img, handNo=0, draw=True):
        lmList = [] #landmark list

        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]

            for id, lm in enumerate(myHand.landmark): #landmarks details/locations
                h, w, c = img.shape
                cx, cy = int(lm.x*w), int(lm.y*h) #position according to display pixles
                lmList.append([id,cx, cy])

                if draw:
                    cv2.circle(img, (cx,cy), 7, (0,0,255), cv2.FILLED)

        return lmList

def main():
    #define the webcam
    cap = cv2.VideoCapture(0)

    detector = handDetector() #call hand detector class

    pTime = 0 #varibles for calculate FPS
    cTime = 0

    while True:
        success, img = cap.read()
        img = detector.findHands(img) #call the method
        lmList = detector.findPosition(img)

        if len(lmList) !=0: #check weather any hand detected
            print(lmList[4])

        #Calculate the FPS
        cTime = time.time()
        fps = 1/(cTime-pTime)
        pTime = cTime
        cv2.putText(img, str(int(fps)), (10,70), cv2.FONT_HERSHEY_PLAIN , 3, (255,0,255), 3)

        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()


from sequana.lazy import pylab
from sequana.lazy import pandas as pd
from sequana.utils.pandas import PandasReader
from sequana.viz.venn import plot_venn

import colorlog

logger = colorlog.getLogger(__name__)

__all__ = ["MACS3Reader", "PeakConsensus"]

class MACS3Reader:
    """This class reads output of macs3 tool

    ::

        from sequana import MACS3Reader
        mr = MACS3Reader(data)
        mr.df
        mr.plot_volcano()

    If input file ends in .xls, we assume this is a NAME_peaks.xls file. It is
    therefore a tabulated file where columns are:

    - chromosome name
    - start position of peak
    - end position of peak
    - length of peak region
    - absolute peak summit position
    - pileup height at peak summit
    - -log10(pvalue) for the peak summit (e.g. pvalue =1e-10, then this value should be 10)
    - fold enrichment for this peak summit against random Poisson distribution with local lambda,
    - -log10(qvalue) at peak summit

    Note that coordinates in XLS is 1-based which is different from BED format
    that follows. When --broad is enabled for broad peak calling, the pileup, p-value,
    q-value, and fold change in the XLS file will be the mean value across
    the entire peak region, since peak summit won't be called in broad peak calling mode.

    NAME_peaks.narrowPeak is BED6+4 format file which contains the peak locations
    together with peak summit, p-value, and q-value.

    The fifth column is the **score** calculate as int(-10*log10_pvalue) or
    int(-10*log10_pvalue) where log10-pvalue/log10-qvalue is the 8th or 9th column
    depending on whether -p (pvalue) or -q (qvalue) is used as score cutoff. The 7th
    columns stores the fold-change at peak summit. The 8th is -log10pvalue at peak summit
    and the 9th is -log10qvalue at peak summit. The 10th is the relative summit position
    to peak start equivalent to absolute peak summit position in the xls file.

    NAME_peaks.broadPeak is in BED6+3 format which is similar to narrowPeak file, except
    for missing the 10th column for annotating peak summits. This file and the
    gappedPeak file will only be available when --broad is enabled. Since in the
    broad peak calling mode, the peak summit won't be called, the values in the 5th,
    and 7-9th columns are the mean value across all positions in the peak region.
    Refer to narrowPeak if you want to fix the value issue in the 5th column

    .. reference:: https://github.com/macs3-project/MACS/blob/master/docs/callpeak.md
    """

    def __init__(self, filename):

        # .xls is not stuctured similarly to .narrowPeak
        if filename.endswith(".xls"):
            #
            self.df = PandasReader(filename, comment="#", sep="\t").df
            # narrow and broad files have this header in common and can be checked.
            for x in [
                "chr",
                "start",
                "end",
                "abs_summit",
                "-log10(pvalue)",
                "fold_enrichment",
                "-log10(qvalue)",
                "name",
            ]:
                # we could have also pileup depending on the user's options
                assert x in self.df.columns
            self.df["stop"] = self.df["end"]
        elif filename.endswith("narrowPeak"):
            columns = [
                "chr",
                "start",
                "stop",
                "name",
                "score",
                "NA",
                "fold_enrichment",
                "-log10(pvalue)",
                "-log10(qvalue)",
                "abs_summit_from_start",
            ]
            self.df = PandasReader(filename, header=None, sep="\t", columns=columns).df
        elif filename.endswith("broadPeak"):
            columns = [
                "chr",
                "start",
                "stop",
                "name",
                "score",
                "NA",
                "fold_enrichment",
                "-log10(pvalue)",
                "-log10(qvalue)",
            ]
            self.df = PandasReader(filename, header=None, sep="\t", columns=columns).df
        self.df["length"] = self.df["stop"] - self.df["start"]
        #

    def __len__(self):
        return len(self.df)

    def plot_volcano(self, plotly=False, marker_color="b", title=""):
        """Plots -log10 p-value versus fold change of all peaks"""

        if plotly:
            from plotly import express as px

            df = self.df.copy()
            df["log_adj_pvalue"] = self.df["-log10(pvalue)"]
            df["log2FoldChange"] = pylab.log2(self.df["fold_enrichment"])
            df["info"] = df["chr"] + ":" + df["start"].astype(str) + "-" + df["stop"].astype(str)

            fig = px.scatter(
                df,
                x="log2FoldChange",
                y="log_adj_pvalue",
                hover_name="info",
                log_y=False,
                color="length",
                height=600,
                title=title,
                labels={"log2_fold_enrichment": "log10 p-value"},
            )
            return fig

        pylab.scatter(
            pylab.log2(self.df["fold_enrichment"]),
            self.df["-log10(pvalue)"],
            marker="o",
            alpha=0.5,
            color=marker_color,
            lw=0,
            s=self.df["length"] / self.df["length"].max() * 400,
        )
        pylab.xlabel("Fold enrichment")
        pylab.ylabel("log10 pvalue")
        pylab.title(title)

class PeakConsensus:
    def __init__(self, f1, f2):
        self.df1 = MACS3Reader(f1).df
        self.df1["category"] = "first"
        self.df2 = MACS3Reader(f2).df
        self.df2["category"] = "second"
        self.df_merged = self.merge()

    def merge(self, overlap=0.2):
        df = pd.concat([self.df1, self.df2]).sort_values(["chr", "start"])
        # if overlap at least one base, we merge the peaks and label them with
        # common information, otherwise we report the original peak

        merged = []
        prev = None
        N1 = 0
        N2 = 0
        N12 = 0
        skip_next = True
        for k, current in df.iterrows():
            if skip_next:
                prev = current
                skip_next = False
                continue

            # if current overlaps the prev start or end, there is overlap
            # or if current included in prev there current and prev overlaps
            if current["start"] <= prev["start"] and current["stop"] >= prev["start"]:
                overlap = True
                N12 += 1
            elif current["start"] <= prev["stop"] and current["stop"] >= prev["stop"]:
                overlap = True
                N12 += 1
            elif current["start"] >= prev["start"] and current["stop"] <= prev["stop"]:
                overlap = True
                N12 += 1
            else:
                overlap = False
                if prev["name"].startswith("1_vs_6_7"):
                    N1 += 1
                elif prev["name"].startswith("2_vs_6_7"):
                    N2 += 1

            if overlap:
                m = min(current["start"], prev["start"])
                M = max(current["stop"], prev["stop"])
                data = current.copy()
                data["start"] = m
                data["stop"] = M
                data["category"] = "both"
                merged.append(data)
                skip_next = True
            else:
                m = min(current["start"], prev["start"])
                M = max(current["stop"], prev["stop"])
                merged.append(prev)
                skip_next = False

            prev = current
        df = pd.DataFrame(merged)
        df = df.reset_index(drop=True)
        return df

    def plot_venn(self, title="", labels=[]):

        plot_venn(
            (
                set(self.df_merged.query("category in ['first', 'both']").index),
                set(self.df_merged.query("category in ['second', 'both']").index),
            ),
            labels=(("first", "second")),
        )

    def to_saf(self, filename):
        """For now, all strand are categorised as strand + .
        strand not used in the pipeline for now."""
        df = self.df_merged.reset_index()
        df["strand"] = "+"
        df["GeneID"] = df["index"]
        df[["GeneID", "chr", "start", "stop", "strand", "category"]].to_csv(filename, sep="\t", index=None)

    def to_bed(self, filename):
        # output to be used by homer
        # annotatePeaks.pl file.bed file.fa -gid -gff file.gff
        # GeneID seems to have to start with Interval_ ??

        df = self.df_merged.reset_index()
        df["strand"] = "+"
        df["GeneID"] = ["Interval_{}".format(x) for x in df["index"]]
        mapper = {"both": 3, "first": 1, "second": 2}
        df["score"] = [mapper[x] for x in df["category"]]
        df[["chr", "start", "stop", "GeneID", "score", "strand"]].to_csv(filename, sep="\t", index=None, header=False)


from functools import wraps
import subprocess

_SELECTIONS = {
    '+': 'clipboard',
    '*': 'primary',
}

def _store_selection(data, selection):
    with subprocess.Popen(['xclip',
                           '-selection', selection],
                          stdin=subprocess.PIPE) as xclip:
        xclip.stdin.write(str(data).encode())

def _load_selection(selection):
    with subprocess.Popen(['xclip',
                           '-selection', selection,
                           '-o'], stdout=subprocess.PIPE) as xclip:
        return xclip.stdout.read().decode()

class RPNError(Exception):
    pass

def wrap_user_errors(fmt):
    '''
    Ugly hack decorator that converts exceptions to warnings.

    Passes through RPNErrors.
    '''
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except RPNError:
                raise
            except Exception as e:
                raise RPNError(fmt.format(*args, **kwargs), e)
        return wrapper
    return decorator


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

from imio.helpers.content import get_schema_fields
from plone.dexterity.interfaces import IDexterityContent
from plone.restapi.interfaces import IFieldSerializer
from plone.restapi.serializer.converters import json_compatible
from plone.restapi.serializer.dxfields import ChoiceFieldSerializer
from plone.restapi.serializer.dxfields import CollectionFieldSerializer
from plonemeeting.restapi import logger
from plonemeeting.restapi.interfaces import IPMRestapiLayer
from zope.component import adapter
from zope.interface import implementer
from zope.schema.interfaces import IChoice
from zope.schema.interfaces import ICollection
from zope.schema.interfaces import IField
from zope.schema.interfaces import IVocabularyTokenized
from zope.schema.vocabulary import SimpleTerm

@adapter(IChoice, IDexterityContent, IPMRestapiLayer)
@implementer(IFieldSerializer)
class PMChoiceFieldSerializer(ChoiceFieldSerializer):
    """Override to take elephantvocabulary into account."""

    def __call__(self):
        # Binding is necessary for named vocabularies
        if IField.providedBy(self.field):
            self.field = self.field.bind(self.context)
        value = self.get_value()
        # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
        vocab = getattr(self.field.vocabulary, "vocab", self.field.vocabulary)
        if value is not None and IVocabularyTokenized.providedBy(vocab):
            try:
                term = self.field.vocabulary.getTerm(value)
            # If not found, get it from the z3c.form that maybe uses a MissingTerms adapter...
            except LookupError:
                try:
                    view = self.context.restrictedTraverse("@@view")
                    view.update()
                    # widget_name is the field name prefixed with behavior if any
                    widget_name = [field for field in get_schema_fields(self.context, prefix=True)
                                   if field[1].__name__ == self.field.__name__][0][0]
                    widget = view.widgets[widget_name]
                    term = widget.terms.getTerm(value)
                except Exception:
                    # at worse use value as title
                    term = SimpleTerm(value, title=value)
            finally:
                value = {"token": term.token, "title": term.title}

        return json_compatible(value)

@adapter(ICollection, IDexterityContent, IPMRestapiLayer)
@implementer(IFieldSerializer)
class PMCollectionFieldSerializer(CollectionFieldSerializer):
    """Override to take elephantvocabulary into account."""

    def __call__(self):
        # Binding is necessary for named vocabularies
        if IField.providedBy(self.field):
            self.field = self.field.bind(self.context)
        value = self.get_value()
        value_type = self.field.value_type
        if value is not None and IChoice.providedBy(value_type):
            # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
            vocab = getattr(value_type.vocabulary, "vocab", value_type.vocabulary)
            if IVocabularyTokenized.providedBy(vocab):
                values = []
                for v in value:
                    try:
                        term = value_type.vocabulary.getTerm(v)
                        values.append({u"token": term.token, u"title": term.title})
                    except LookupError:
                        logger.warning("Term lookup error: %r" % v)
                value = values
        return json_compatible(value)


import time
from collections import deque
n, k = list(map(int, input().split()))

def circularize(i):
    dq = deque()
    for i in range(1, n+1):
        dq.append(i)
    return dq

def solution(n, k):
    circle = circularize(n)
    i = 0
    answer = deque()
    while len(circle):
        if i+1 == k:
            answer.append(circle.popleft())
            i = -1
        else:
            circle.append(circle.popleft())
        i += 1
    return '<' + ', '.join(map(str, answer)) + '>'

s = time.time()
print(solution(n, k))
print(time.time()-s)


__author__ = 'Anna Nikishova'

import os
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

def plot_res(prediction, original, name, num, out_color):
    plt.figure(figsize=(5, 11))
    axis1 = plt.subplot(311)
    plt.title('{} training sample of size: {}'.format(type_train, str(len(train_n))))
    plt.plot(prediction, '.', label='Linear interpolator', color=out_color)
    plt.plot(original, '.', label='Turbulence model', color='green')
    plt.xlabel('Run number')
    plt.ylabel('Prediction of {}'.format(name))
    plt.legend()
    plt.grid()
    # plt.yscale("log")
    plt.subplot(312)
    plt.plot(prediction- original, '.', color=out_color)
    plt.grid()
    # plt.yscale("log")
    plt.xlabel('Run number')
    plt.ylabel('Error')
    plt.subplot(313)
    plt.plot(np.fabs(prediction- original)/original * 100, '.', color=out_color)
    plt.grid()
    plt.xlabel('Run number')
    plt.ylabel('Relative error (%)')
    # plt.yscale("log")
    plt.tight_layout()
    plt.savefig('data/GP_prediction_' + name + '_' + type_train + '_' + str(len(train_n)) + '(linear).png',bbox_inches='tight', dpi=100)
    plt.show()
    plt.clf()

data = np.genfromtxt('data/AUG_gem_inoutput.txt', skip_header=1)
input_samples_all = data[:, 1:58]
output_samples_all = data[:, 58:]
input_dim = 8
N_runs = len(input_samples_all[:, 0])

names_in_outputs = ['time', 'Te-ft1', 'Te-ft2', 'Te-ft3', 'Te-ft4', 'Te-ft5', 'Te-ft6', 'Te-ft7', 'Te-ft8', 'dTe-ft1', 'dTe-ft2', 'dTe-ft3', 'dTe-ft4', 'dTe-ft5', 'dTe-ft6', 'dTe-ft7', 'dTe-ft8', 'Ti-ft1', 'Ti-ft2', 'Ti-ft3', 'Ti-ft4', 'Ti-ft5', 'Ti-ft6', 'Ti-ft7', 'Ti-ft8', 'dTi-ft1', 'dTi-ft2', 'dTi-ft3', 'dTi-ft4', 'dTi-ft5', 'dTi-ft6', 'dTi-ft7', 'dTi-ft8', 'ne-ft1', 'ne-ft2', 'ne-ft3', 'ne-ft4', 'ne-ft5', 'ne-ft6', 'ne-ft7', 'ne-ft8', 'dne-ft1', 'dne-ft2', 'dne-ft3', 'dne-ft4', 'dne-ft5', 'dne-ft6', 'dne-ft7', 'dne-ft8', 'q-ft1', 'q-ft2', 'q-ft3', 'q-ft4', 'q-ft5', 'q-ft6', 'q-ft7', 'q-ft8', 'B0', 'flux-Te-ft1', 'flux-Te-ft2', 'flux-Te-ft3', 'flux-Te-ft4', 'flux-Te-ft5', 'flux-Te-ft6', 'flux-Te-ft7', 'flux-Te-ft8', 'flux-Ti-ft1', 'flux-Ti-ft2', 'flux-Ti-ft3', 'flux-Ti-ft4', 'flux-Ti-ft5', 'flux-Ti-ft6', 'flux-Ti-ft7', 'flux-Ti-ft8', 'flux-ne-ft1', 'flux-ne-ft2', 'flux-ne-ft3', 'flux-ne-ft4', 'flux-ne-ft5', 'flux-ne-ft6', 'flux-ne-ft7', 'flux-ne-ft8']

num_output = 0
input_samples8 = input_samples_all[:, num_output::8]
output_samples = output_samples_all[:, num_output]

# Here I excluded the input paprameters that did not vary in the data set
input_samples = np.zeros((N_runs, 5))
input_samples[:,:4] = input_samples8[:,:4]
input_samples[:,4] = input_samples8[:,6]

N_tr = 1000
type_train = 'regular'#'random'#
if type_train == 'random':
    train_n = np.random.randint(0, N_runs, N_tr)
else:
    train_n = np.arange(0, N_runs, 5)

X = input_samples[train_n]
Y = output_samples[train_n]

start = 0
end = 300

prediction = griddata(X, Y, input_samples, method='linear')

plot_res(prediction, output_samples, names_in_outputs[58+num_output], '1', 'blue')