import numbers
import numpy as np

import torch
import torch.autograd

import _ext
import _extc
import error_checking as ec
from kernels import KERNELS, KERNEL_NAMES

class ConvSP(torch.nn.Module):
    """ The Smooth Particle Convolution layer. Performs convolutions on particle sets. Each
    particle has a location in N-D space and an associated set of features. An N-D kernel
    is centered at each particle location, with the shape of the kernel and the size of
    each kernel cell being user-specified. Then the feature field induced by the set of
    particles is evaluated at each kernel cell. That is, for every feature f associated
    with the particles and kernel cell center r, a weighted average for f is taken at r
    based on the distance to nearby
    """

    def __init__(self, in_channels, out_channels, ndim, kernel_size, dilation, radius,
                 dis_norm=False, kernel_fn='default', with_params=True):
        """ Initialize a Smooth Particle Convolution layer.

        Arguments:
            -in_channels: The number of features for each input particle.
            -out_channels: The number of features to output for each particle.
            -ndim: The dimensionality of the particle's coordinate space.
            -kernel_size: (int or tuple) The shape of the kernel that is place around each
                          particle. The kernel is centered on the particle, so the size
                          must be odd.
            -dilation: (float or tuple) The spacing between each cell of the kernel.
            -radius: The radius to use when computing the neighbors for each query point.
            -kernel_fn: The kernel function to use in the SPH equation. Refer to kernels.py
                        for a list and explanation of all available functions.
            -dis_norm: If true, will divide by the particle-to-particle distance in the
                       SPH equation.
            -with_params: If true, the parameters weight and bias are registered with
                          PyTorch as parameters. Otherwise they are registered as buffers,
                          meaning they won't be optimized when doing backprop.
        """
        super(ConvSP, self).__init__()
        self.nchannels = ec.check_conditions(in_channels, "in_channels",
                                             "%s > 0", "isinstance(%s, numbers.Integral)")
        self.nkernels = ec.check_conditions(out_channels, "out_channels",
                                            "%s > 0", "isinstance(%s, numbers.Integral)")
        self.ndim = ec.check_conditions(ndim, "ndim",
                                        "%s > 0", "%s < " +
                                        str(_ext.spn_max_cartesian_dim()),
                                        "isinstance(%s, numbers.Integral)")

        self._kernel_size = ec.make_list(kernel_size, ndim, "kernel_size",
                                         "%s >= 0", "%s %% 2 == 1 # Must be odd",
                                         "isinstance(%s, numbers.Integral)")
        self._dilation = ec.make_list(dilation, ndim, "dilation",
                                      "%s >= 0", "isinstance(%s, numbers.Real)")

        self.radius = ec.check_conditions(radius, "radius",
                                          "%s >= 0", "isinstance(%s, numbers.Real)")

        self.kernel_fn = ec.check_conditions(kernel_fn, "kernel_fn",
                                             "%s in " + str(KERNEL_NAMES))
        self.kernel_fn = KERNEL_NAMES.index(self.kernel_fn)
        self.dis_norm = (1 if dis_norm else 0)

        self.ncells = np.prod(self._kernel_size)

        if with_params:
            self.register_parameter("weight", torch.nn.Parameter(torch.Tensor(self.nkernels,
                                                                              self.nchannels, self.ncells)))
            self.register_parameter(
                "bias", torch.nn.Parameter(torch.Tensor(self.nkernels)))
        else:
            self.register_buffer("weight", torch.autograd.Variable(torch.Tensor(self.nkernels,
                                                                                self.nchannels, self.ncells)))
            self.register_buffer("bias", torch.autograd.Variable(
                torch.Tensor(self.nkernels)))

        self.register_buffer("kernel_size", ec.list2tensor(self._kernel_size))
        self.register_buffer("dilation", ec.list2tensor(self._dilation))

        self.nshared_device_mem = -1
        self.device_id = -1

    def forward(self, locs, data, neighbors, qlocs=None):
        """ Compute a forward pass of the Smooth Particle Convolution Layer.

        Inputs:
            -locs: A BxNxD tensor where B is the batch size, N is the number
                   of particles, and D is the dimensionality of the particles'
                   coordinate space.
            -data: A BxNxC tensor where C is the number of input features.
            -neighbors: A BxMxK tensor where K is the maximum number of neighbors.
                        For each particle, this is the list of particle indices
                        that are considered neighbors. If the number of neighbors
                        is less than K, the less is ended with a -1.
            -qlocs: A BxMxD of query locations. Specify this if you want the query
                    locations to be different from the particle locations.

        Returns: A BxMxO tensor where O is the number of output features. Computed at qlocs.
        """

        # Error checking.
        batch_size = locs.size()[0]
        N = locs.size()[1]
        ec.check_tensor_dims(locs, "locs", (batch_size, N, self.ndim))
        ec.check_tensor_dims(data, "data", (batch_size, N, self.nchannels))

        locs = locs.contiguous()
        data = data.contiguous()

        if qlocs is not None:
            ec.check_tensor_dims(qlocs, "qlocs", (batch_size, -1, self.ndim))
            qlocs = qlocs.contiguous()

        if locs.is_cuda:
            if self.device_id != torch.cuda.current_device():
                self.device_id = torch.cuda.current_device()
                self.nshared_device_mem = _extc.spnc_get_shared_mem_size(
                    self.device_id)

        # Do the compution.
        convsp = _ConvSPFunction(self.radius, self.kernel_size, self.dilation,
                                 self.dis_norm, self.kernel_fn, self.ncells, self.nshared_device_mem)
        # data.shape = BxCxN
        data = convsp(qlocs if qlocs is not None else locs,
                      locs, data, neighbors, self.weight, self.bias)
        # data.shape = BxOxN
        return data

"""

INTERNAL FUNCTIONS

"""

class _ConvSPFunction(torch.autograd.Function):

    def __init__(self, radius, kernel_size, dilation, dis_norm, kernel_fn,
                 ncells, nshared_device_mem=-1):
        super(_ConvSPFunction, self).__init__()
        self.radius = radius
        self.kernel_size = kernel_size
        self.dilation = dilation
        self.dis_norm = dis_norm
        self.kernel_fn = kernel_fn
        self.ncells = ncells
        self.nshared_device_mem = nshared_device_mem

    def forward(self, qlocs, locs, data, neighbors, weight, bias):
        self.save_for_backward(qlocs, locs, data, neighbors, weight, bias)
        batch_size = locs.size()[0]
        M = qlocs.size()[1]
        nkernels = weight.size()[0]
        ret = data.new(batch_size, M, nkernels)
        ret.fill_(0)
        if locs.is_cuda:
            if not _extc.spnc_convsp_forward(qlocs, locs, data, neighbors, weight, bias, self.radius,
                                             self.kernel_size, self.dilation, self.dis_norm, self.kernel_fn, ret,
                                             self.nshared_device_mem):
                raise Exception("Cuda error")
        else:
            _ext.spn_convsp_forward(qlocs, locs, data, neighbors, weight, bias, self.radius,
                                    self.kernel_size, self.dilation, self.dis_norm, self.kernel_fn, ret)

        # Add the bias.
        ret += bias.view(1, 1, nkernels)

        return ret

    def backward(self, grad_output):
        qlocs, locs, data, neighbors, weight, bias = self.saved_tensors
        ret_qlocs = grad_output.new(qlocs.size())
        ret_qlocs.fill_(0)
        ret_locs = grad_output.new(locs.size())
        ret_locs.fill_(0)
        ret_data = grad_output.new(data.size())
        ret_data.fill_(0)
        ret_weight = grad_output.new(weight.size())
        ret_weight.fill_(0)
        if grad_output.is_cuda:
            if not _extc.spnc_convsp_backward(qlocs, locs, data, neighbors, weight, bias, self.radius,
                                              self.kernel_size, self.dilation, self.dis_norm, self.kernel_fn,
                                              grad_output, ret_qlocs, ret_locs, ret_data, ret_weight,
                                              self.nshared_device_mem):
                raise Exception("Cuda error")
        else:
            _ext.spn_convsp_backward(qlocs, locs, data, neighbors, weight, bias, self.radius,
                                     self.kernel_size, self.dilation, self.dis_norm, self.kernel_fn,
                                     grad_output, ret_qlocs, ret_locs, ret_data, ret_weight)
        # PyTorch requires gradients for each input, but we don't care about the
        # gradients for neighbors, so set that to all 0s.
        return (ret_qlocs,
                ret_locs,
                ret_data,
                grad_output.new(neighbors.size()).fill_(0),
                ret_weight,
                grad_output.sum(1).sum(0))


# adata.gui.basic
'''
My WX helpers - old 2006 code - needs cleaning
'''

#__all__ = ['app','sizer','panel']

import os
import sys
import time
import datetime
import platform
import wx
import wx.lib.buttons as buttons
import wx.lib.masked as masked
from wx import adv
from wx.lib.wordwrap import wordwrap
from urllib.request import urlopen
from urllib.error import URLError

class Dictionary(dict):
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            return key

class DictionaryDefault(dict):
    def __init__(self, default=None):
        dict.__init__(self)
        self.default = default

    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            return self.default

PATH = os.path.dirname(os.path.dirname(__file__))
PATH_IMAGE = os.path.join(PATH, 'data', 'image')
PATH_ICON = os.path.join(PATH_IMAGE, 'icon')
BRD = 8
BRB = 5
try:
    EXA = wx.EXPAND|wx.ALL
except:
    # Mock
    EXA = 8432

POS = wx.DefaultPosition
SIZE = wx.DefaultSize

TEXT = Dictionary()
TEXT_DB = Dictionary()
HELP = Dictionary()
MSG = Dictionary()
ERROR = Dictionary()
IMAGE = DictionaryDefault("missing.png")
ICON = DictionaryDefault("missing.png")

def PlatformStyle():
    if 'wxMSW' in wx.PlatformInfo: return {
        'times'     : 'Times New Roman',
        'mono'      : 'Courier New',
        'sans'      : 'Arial',
        'size'      : 11,
    }

    if 'wxMac' in wx.PlatformInfo: return {
        'times'     : 'Lucida Grande',
        'mono'      : 'Monaco',
        'sans'      : 'Geneva',
        'size'      : 12,
    }

    if 'gtk2' in wx.PlatformInfo or 'gtk3' in wx.PlatformInfo: return {
        'times'     : 'Serif',
        'mono'      : 'Monospace',
        'sans'      : 'Sans',
        'size'      : 10,
    }

    return {
        'times'     : 'Times',
        'mono'      : 'Courier',
        'sans'      : 'Helvetica',
        'size'      : 12,
    }

def ImageLoad(name):
    path = os.path.join(PATH_IMAGE, name)
    return wx.Image(path, wx.BITMAP_TYPE_JPEG)

def Icon(name):
    filename = os.path.join(PATH_ICON, ICON[name])
    return wx.Icon(filename, wx.BITMAP_TYPE_PNG)

def SetValues(data, controls):
    for i in controls.keys():
        d = data[i]
        if d is None: value = ""
        elif type(d)==type(0) or type(d)==type(0.0): value=str(d)
        else: value = d
        controls[i].SetValue(value)

#  .d8888. d888888b d88888D d88888b d8888b. .d8888.
#  88'  YP   `88'   YP  d8' 88'     88  `8D 88'  YP
#  `8bo.      88       d8'  88ooooo 88oobY' `8bo.
#    `Y8b.    88      d8'   88~~~~~ 88`8b     `Y8b.
#  db   8D   .88.    d8' db 88.     88 `88. db   8D
#  `8888Y' Y888888P d88888P Y88888P 88   YD `8888Y'

def Border(sizer, border):
    s = SizerV()
    s.Add(sizer, 1, wx.EXPAND|wx.ALL, border)
    return s

class SizerV(wx.BoxSizer):
    def __init__(self):
        super(SizerV, self).__init__(wx.VERTICAL)

class SizerH(wx.BoxSizer):
    def __init__(self):
        super(SizerH, self).__init__(wx.HORIZONTAL)

class SizerVB(wx.BoxSizer):
    def __init__(self, items, border=8):
        super(SizerVB, self).__init__(wx.VERTICAL)
        style = EXA
        style_first = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP
        style_last = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM
        if len(items)==1:
            self.Add(items[0][0], items[0][1], style, border)
            return
        last = len(items)-1
        self.Add(items[0][0], items[0][1], style_first, border)
        for i in range(1, last):
            self.Add(items[i][0], items[i][1], style, border)
        self.Add(items[last][0], items[last][1], style_last, border)

class SizerBox(wx.StaticBoxSizer):
    def __init__(self, parent, title):
        box = wx.StaticBox(parent, -1, title)
        super(SizerBox, self).__init__(box, wx.VERTICAL)

class SizerRow(wx.FlexGridSizer):
    def __init__(self, items):
        super(SizerRow, self).__init__(1, len(items), 0, 0)
        self.AddGrowableCol(0)
        prop = 1
        for item in items:
            self.Add(item, prop, wx.EXPAND)
            if prop==1: prop=0

class SizerTable(wx.FlexGridSizer):
    def __init__(self, parent, items, expand=[]):
        super(SizerTable, self).__init__(len(items), 2, 5, 5)
        self.AddGrowableCol(1)
        for row in expand:
            self.AddGrowableRow(row)
        for label, widget in items:
            self.Add(wx.StaticText(parent, -1, label+":"), 0, wx.ALL, 4) #wx.ALIGN_CENTER_VERTICAL
            self.Add(widget, 0, wx.EXPAND)

#  d8888b.  .d8b.  d8b   db d88888b db      .d8888.
#  88  `8D d8' `8b 888o  88 88'     88      88'  YP
#  88oodD' 88ooo88 88V8o 88 88ooooo 88      `8bo.
#  88~~~   88~~~88 88 V8o88 88~~~~~ 88        `Y8b.
#  88      88   88 88  V888 88.     88booo. db   8D
#  88      YP   YP VP   V8P Y88888P Y88888P `8888Y'

class Panel(wx.Panel):
    def __init__(self, parent):
        super(Panel, self).__init__(parent, -1,
                            style=wx.BORDER_NONE|wx.TAB_TRAVERSAL)

    def Visible(self, value=True):
        if value:
            self.Show()
            self.GetParent().Layout()
        else:
            self.Hide()

class DateTimePicker(wx.Panel):
    def __init__(self, parent, call=None, *args,**kwargs):
        super(DateTimePicker, self).__init__(parent, *args, **kwargs)
        self.box_date = DatePicker(self)
        self.box_time = TimePicker(self)
        self.box_time.Now()
        s = SizerH()
        s.Add(self.box_date,1,wx.EXPAND)
        s.Add(self.box_time,0,wx.EXPAND)
        self.SetSizer(s)
        if call is not None:
            self.box_time.Bind(masked.EVT_TIMEUPDATE, call)
            self.box_date.Bind(wx.EVT_DATE_CHANGED, call)

    def SetValue(self,value):
        pass

    def GetValue(self):
        date = self.box_date.GetValue()
        time = self.box_time.GetValue()
        return datetime.datetime(date.year, date.month, date.day,
                                 int(time[0:2]), int(time[3:5]))

class Image(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.image = None  # wxPython image
        wx.EVT_SIZE(self,self.OnSize)
        wx.EVT_PAINT(self, self.OnPaint)

    def display(self, path):
        print("Image display",path)
        if os.path.exists(path):
            self.image = wx.Image(path, wx.BITMAP_TYPE_ANY)
        else:
            self.image = None
        self.Refresh(True)

    def OnSize(self, event):
        self.Width, self.Height = self.GetClientSizeTuple()

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        if not self.image:
            return
        W, H = self.Width, self.Height
        w, h = self.image.GetWidth(), self.image.GetHeight()
        A, a = W/float(H), w/float(h)
        if A < a:
            sw, sh = W, W/a
            ow, oh = 0, (H-sh)/2
        else:
            sw, sh = H*a, H
            ow, oh = (W-sw)/2, 0
        scaled = self.image.Scale(sw, sh, wx.IMAGE_QUALITY_HIGH)
        dc.DrawBitmap(scaled.ConvertToBitmap(), ow, oh)

class ProgressBar(wx.Panel):
    def __init__(self, parent, color=(255,255,255), bgcolor=(0,0,0)):
        wx.Panel.__init__(self, parent,
                          style=wx.BORDER_NONE | wx.NO_FULL_REPAINT_ON_RESIZE)
        wx.EVT_SIZE(self,self.OnSize)
        wx.EVT_PAINT(self,self.OnPaint)
        #self.SetDoubleBuffered(True)
        self.SetBackgroundColour(bgcolor)
        self.SetForegroundColour(color)
        self.value = 0
        self.color = color
        self.OnSize(None)

    def SetValue(self, value):
        self.value = value
        self.UpdateDrawing()

    def OnSize(self, event=None):
        self.Width, self.Height = self.GetClientSizeTuple()
        self._Buffer = wx.EmptyBitmap(self.Width, self.Height)
        self.Draw()

    def OnPaint(self,event):
        event.Skip()
        self.Draw()

    def UpdateDrawing(self):
        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
        self.Draw(dc)

    def Draw(self, dc=None):
        if dc is None: dc = wx.ClientDC(self)
        width,height = self.Width, self.Height#self.GetSize()
        w=int(width*self.value)
        if w<8:w=8
        h=height
        x=(width-w)/2
        y=0
        dc.BeginDrawing()
        dc.Clear()
        dc.SetBrush(wx.Brush((0,0,0)))
        dc.DrawRectangle(0,0,width,height)
        dc.SetBrush(wx.Brush(self.color))

        dc.DrawRoundedRectangle(0,0,width,height,4)
        dc.SetBrush(wx.Brush((0,0,0)))
        dc.DrawRoundedRectangle(4,4,width-8,height-8,4)
        dc.SetBrush(wx.Brush(self.color))
        dc.DrawRoundedRectangle(6,6,int(self.value*(width-12)),height-12,4)
        #dc.SetPen(wx.Pen((255,255,255), 12, wx.SOLID))
        #dc.DrawText(str(int(self.value*100))+"%",0,0)
        dc.EndDrawing()

#   .o88b.  .d88b.  d8b   db d888888b d8888b.  .d88b.  db      .d8888.
#  d8P  Y8 .8P  Y8. 888o  88 `~~88~~' 88  `8D .8P  Y8. 88      88'  YP
#  8P      88    88 88V8o 88    88    88oobY' 88    88 88      `8bo.
#  8b      88    88 88 V8o88    88    88`8b   88    88 88        `Y8b.
#  Y8b  d8 `8b  d8' 88  V888    88    88 `88. `8b  d8' 88booo. db   8D
#   `Y88P'  `Y88P'  VP   V8P    YP    88   YD  `Y88P'  Y88888P `8888Y'

class Text(wx.TextCtrl):
    def __init__(self, parent, edit=True, multiline=False, value="",
                 change=None, key=None, font=None, size=(32,24), style=None):
        if style is None:
            if edit: style = wx.BORDER_SUNKEN
            else: style = wx.TE_READONLY | wx.SIMPLE_BORDER
        if multiline: style = style | wx.TE_MULTILINE
        style = style | wx.TE_RICH | wx.TE_RICH2
        #super(Text, self).__init__(parent, -1, value, style=style, size=size)
        super(Text, self).__init__(parent, -1, style=style, size=size)
        if change is not None: self.Bind(wx.EVT_KILL_FOCUS, change)
        if key is not None: self.Bind(wx.EVT_TEXT, key)
        if font is not None: self.SetFont(font)

class Button(buttons.GenBitmapTextButton):
    """ Image button
    """
    def __init__(self, parent, caption, call, image=None, size=(100,32)):
        #x = wx.Button(parent, -1, caption)
        if image is not None: caption="  "+caption
        if size[0]>100: self.DrawLabel = self.DrawLabelRight
        super(Button, self).__init__(parent, -1, None, caption, size=size)
        if image is not None: self.SetBitmapLabel(image)
        self.Bind(wx.EVT_BUTTON, call)

    def DrawLabelRight(self, dc, width, height, dx=0, dy=0):
        bmp = self.bmpLabel
        if bmp is not None:     # if the bitmap is used
            if self.bmpDisabled and not self.IsEnabled():
                bmp = self.bmpDisabled
            if self.bmpFocus and self.hasFocus:
                bmp = self.bmpFocus
            if self.bmpSelected and not self.up:
                bmp = self.bmpSelected
            bw,bh = bmp.GetWidth(), bmp.GetHeight()
            if not self.up:
                dx = dy = self.labelDelta
            hasMask = bmp.GetMask() is not None
        else:
            bw = bh = 0     # no bitmap -> size is zero

        dc.SetFont(self.GetFont())
        if self.IsEnabled():
            dc.SetTextForeground(self.GetForegroundColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        label = self.GetLabel()
        tw, th = dc.GetTextExtent(label)        # size of text
        if not self.up:
            dx = dy = self.labelDelta

        #pos_x = (width-bw-tw)/2+dx      # adjust for bitmap and text to centre
        pos_x = 8
        if bmp is not None:
            dc.DrawBitmap(bmp, pos_x, (height-bh)/2+dy, hasMask) # draw bitmap if available
            pos_x = pos_x + 2   # extra spacing from bitmap

        dc.DrawText(label, pos_x + dx+bw, (height-th)/2+dy)      # draw the text

class CheckBox(wx.CheckBox):
    def __init__(self, parent, caption, call):
        super(CheckBox, self).__init__(parent, -1, caption)
        self.Bind(wx.EVT_CHECKBOX, call)

class ListBox(wx.ListBox):
    def __init__(self, parent, call=None, double=None):
        self.key={}
        super(ListBox, self).__init__(parent, -1, size=(80,80), style=wx.LB_SINGLE)
        if call is not None:
            self.Bind(wx.EVT_LISTBOX, call)
        if double is not None:
            self.Bind(wx.EVT_LISTBOX_DCLICK, double)

    def GetKey(self):
        value = self.GetStringSelection()
        if value in self.key:
            return self.key[value]

    def GetItemsFromData(self, data):
        l, self.key = [], {}
        selected = self.GetStringSelection()
        if len(data)>0:
            if len(data[0])>1:
                for result in data:
                    value = result[1]
                    if len(result)>2:
                        for i in range(2,len(result)): value+=","+result[i]
                    self.key[value]=result[0]
                    l.append(value)
            else:
                for result in data: l.append(result[0])
        if self.GetItems()!=l:
            self.SetItems(l)
        if selected in l:
            self.SetSelection(l.index(selected))
        return l

class ComboBox(wx.ComboBox):
    """ Una lista de opciones
    """
    def __init__(self, parent, choices=None, call=None, edit=True,
                 sort=False, first=None):
        if sort: style = wx.CB_SORT
        else: style = 0
        if not edit: style = style | wx.CB_READONLY
        self.first = first
        if first is not None:
            if choices is None: choices=[first]
            else: choices=[first]+choices
        if choices is None: choices=[]
        super(ComboBox, self).__init__(parent, -1, "", style=style ,
                                       choices=choices)
        if call is not None:
            self.Bind(wx.EVT_KILL_FOCUS, call)
            self.Bind(wx.EVT_COMBOBOX, call)
        self.key = {}

    def GetKey(self):
        value = self.GetValue()
        if value in self.key:
            return self.key[value]
        else:
            return value

    def GetItemsFromData(self, data):
        #data = self.DB.result("SELECT DISTINCT type FROM sequences ORDER BY type")
        selected = self.GetValue()

        if self.first is None:
            l=[]
            self.key={}
        else:
            l = [self.first]
            self.key={self.first:None}
        if len(data)>0:
            if len(data[0])>1:
                for result in data:
                    value = result[1]
                    if len(result)>2:
                        for i in range(2,len(result)):
                            value+=", "+result[i]
                    self.key[value]=result[0]
                    l.append(value)
            else:
                for result in data: l.append(result[0])

        if "" in l: l.remove("")
        if self.GetItems()!=l: self.SetItems(l)
        if selected in l:
            self.SetSelection(l.index(selected))
        else:
            if self.first is not None:
                self.selected = l[0]
                self.SetSelection(0)
        return l

#def DatePicker(parent, call):
#    x = MyDatePickerCtrl(parent, style = wx.DP_DROPDOWN)
#    x.Bind(wx.EVT_DATE_CHANGED, call)
#    return x

class TimePicker(masked.TimeCtrl):
    def __init__(self, parent, call=None, *args,**kwargs):
        #wx.DatePickerCtrl.__init__(self, parent, *args,**kwargs)
        super(TimePicker, self).__init__(parent, style=adv.DP_DROPDOWN,
                                         *args, **kwargs)
        if call is not None:
            self.Bind(masked.EVT_TIMEUPDATE, call)

    def Now(self):
        t = datetime.datetime(2000,1,1).today()
        wxvalue=wx.DateTime()
        wxvalue.Set(year=t.year, month=t.month-1, day=t.day,
                    hour=t.hour, minute=t.minute)
        self.SetValue(wxvalue)

class DatePicker(adv.DatePickerCtrl):
    def __init__(self, parent, call=None, *args,**kwargs):
        #wx.DatePickerCtrl.__init__(self, parent, *args,**kwargs)
        super(DatePicker, self).__init__(parent, style=adv.DP_DROPDOWN,
                                         *args, **kwargs)
        if call is not None:
            self.Bind(wx.EVT_DATE_CHANGED, call)

    def SetValue(self,value):
        """Set either datetime.datetime or wx.DateTime"""
        if isinstance(value,(datetime.date,datetime.datetime)):
            wxvalue=wx.DateTime()
            wxvalue.Set(year=value.year,month=value.month-1,day=value.day)
            value=wxvalue
        elif value is None:
            value=wx.DateTime()
        wx.DatePickerCtrl.SetValue(self,value)

    def GetValue(self):
        """Returns datetime.datetime values"""
        value=wx.DatePickerCtrl.GetValue(self)
        if not value.IsValid():    #Manage null dates (useful when wx.DP_ALLOWNONE is set)
            return None
        else:
            return datetime.datetime(value.GetYear(),value.GetMonth()+1,value.GetDay())

# d88888b d8888b. d8888b.  .d88b.  d8888b. .d8888.
# 88'     88  `8D 88  `8D .8P  Y8. 88  `8D 88'  YP
# 88ooooo 88oobY' 88oobY' 88    88 88oobY' `8bo.
# 88~~~~~ 88`8b   88`8b   88    88 88`8b     `Y8b.
# 88.     88 `88. 88 `88. `8b  d8' 88 `88. db   8D
# Y88888P 88   YD 88   YD  `Y88P'  88   YD `8888Y'

class ErrorWindow(wx.Frame):
    def __init__(self, value, tb):
        # based on a frame, so set up the frame
        print("ERROR: %s" % value)
        #print(dir(value))

        title=value.__class__.__name__

        if hasattr(value, "filename"): title += " %s" % value.filename
        if hasattr(value, "lineno"):   title += " #%s" % value.lineno

        wx.Frame.__init__(self, None, -1, title, size=(720, 480))
        font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.NORMAL, wx.NORMAL)

        self.text = Text(self, multiline=True, font=font)
        #self.text = StyledText(self)
        self.text.SetBackgroundColour((255,255,255))
        self.text.SetForegroundColour((255,0,0))
        #self.text.echo("%s\n" % value)
        #self.text.echo("\n\nTraceback:\n\n", "fore:#FF0F0F,back:#0F0000,bold")
        self.text.write("%s\n" % value)
        self.text.write("\n\nTraceback:\n\n")
        #self.text.SetForegroundColour((0,0,0))

        traceback.print_tb(tb, file = self.text)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.text,1,wx.EXPAND)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        #self.sizer.Fit(self)
        self.Show()

ART = [
    "ART_ERROR",
    "ART_GOTO_LAST",
    "ART_FILE_SAVE_AS",
    "ART_QUESTION",
    "ART_PRINT",
    "ART_DELETE",
    "ART_WARNING",
    "ART_HELP",
    "ART_COPY",
    "ART_INFORMATION",
    "ART_TIP",
    "ART_CUT",
    "ART_ADD_BOOKMARK",
    "ART_REPORT_VIEW",
    "ART_PASTE",
    "ART_DEL_BOOKMARK",
    "ART_LIST_VIEW",
    "ART_UNDO",
    "ART_HELP_SIDE_PANEL",
    "ART_NEW_DIR",
    "ART_REDO",
    "ART_HELP_SETTINGS",
    "ART_FOLDER",
    "ART_PLUS",
    "ART_HELP_BOOK",
    "ART_FOLDER_OPEN",
    "ART_MINUS",
    "ART_HELP_FOLDER",
    "ART_GO_DIR_UP",
    "ART_CLOSE",
    "ART_HELP_PAGE",
    "ART_EXECUTABLE_FILE",
    "ART_QUIT",
    "ART_GO_BACK",
    "ART_NORMAL_FILE",
    "ART_FIND",
    "ART_GO_FORWARD",
    "ART_TICK_MARK",
    "ART_FIND_AND_REPLACE",
    "ART_GO_UP",
    "ART_CROSS_MARK",
    "ART_HARDDISK",
    "ART_GO_DOWN",
    "ART_MISSING_IMAGE",
    "ART_FLOPPY",
    "ART_GO_TO_PARENT",
    "ART_NEW",
    "ART_CDROM",
    "ART_GO_HOME",
    "ART_FILE_OPEN",
    "ART_GOTO_FIRST",
    "ART_FILE_SAVE"
]


import json
import matplotlib.pyplot as plt

def weight_normalization(data):
    weight = []
    for record in data:
        weight.append(record['weight'])
    weight_min = min(weight)
    weight_range = max(weight) - min(weight)
    weight_normalized = [(x - weight_min)/weight_range for x in weight]
    plt.plot(weight_normalized)
    plt.show()
    for i in range(len(weight_normalized)):
        data[i]['weight'] = weight_normalized[i]
    with open('/Users/haotong/attention-highlight/attention_weight.json', 'w') as f:
        f.write(json.dumps(data))

if __name__ == '__main__':
    with open('/Users/haotong/attention-highlight/data.json') as f:
        f_dict = json.load(f)
        weight_normalization(f_dict)


from sklearn.model_selection import train_test_split

#%%
def train_val_test_split(dataset, val_ratio, test_ratio):
    """
    splitting a dataset into training, validation and test sets
    """
    index_name = dataset.index.name
    train_val_sets, test_set = train_test_split(
        dataset, test_size=test_ratio, shuffle=True
    )
    train_set, val_set = train_test_split(
        train_val_sets, test_size=val_ratio, shuffle=True
    )

    train_set.reset_index(drop=True, inplace=True)
    train_set.index.name = index_name
    val_set.reset_index(drop=True, inplace=True)
    val_set.index.name = index_name
    test_set.reset_index(drop=True, inplace=True)
    test_set.index.name = index_name

    return train_set, val_set, test_set

#%%


from scipy import matrix, rand, linalg, double
from time import perf_counter
import numpy as np
import scipy.linalg as spLinalg

def matriz_laplaceana(N, d=double):
    L=-(np.eye(N, k=-1, dtype=d))+2*\
      (np.eye(N, dtype=d)) + -(np.eye(N, k=+1, dtype=d))
    return L

lista_N=[2,5, 10, 12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200, 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]
T_ensamble=[]
T_solucion=[]

for N in lista_N:
    t1=perf_counter()
    A=matriz_laplaceana(N)
    B=np.ones(N)
    t2=perf_counter()
    A_invB=spLinalg.solve(A, B, assume_a="pos", overwrite_b=True)
    t3=perf_counter()
    dt1=t2-t1
    dt2=t3-t2
    T_ensamble.append(dt1)
    T_solucion.append(dt2)

print(T_ensamble)
print(T_solucion)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
(c) 2018 under a MIT License (https://mit-license.org)

Authors:
- Lukas Brunner || lukas.brunner@env.ethz.ch

Abstract:

"""
import os
import regionmask
import numpy as np
import xarray as xr
import matplotlib
matplotlib.rc('text', usetex=True)
import matplotlib.pyplot as plt
from properscoring import crps_ensemble
import seaborn as sns
from glob import glob

from utils_python.xarray import area_weighted_mean, flip_antimeridian
from model_weighting.core.utils import read_config

from boxplot import boxplot

SAVEPATH = '/home/lukbrunn/Documents/Scripts/climWIP_clean_paper/model_weighting/scripts_paper/revision1/figures'
LOADPATH = '/net/h2o/climphys/lukbrunn/Data/ModelWeighting/CMIP6_r1'
FILENAMES = [
    'tas_global_pseudo_obs_ssp126_050_*-CMIP5-RCP26_41-60_ind',
    'tas_global_pseudo_obs_ssp585_050_*-CMIP5-RCP85_41-60_ind',
    '',
    'tas_global_pseudo_obs_ssp126_050_*-CMIP5-RCP26_81-00_ind',
    'tas_global_pseudo_obs_ssp585_050_*-CMIP5-RCP85_81-00_ind',
]
SAVENAME = 'figure3a.png'

# wether to calculate the CRPS on the full 2D field and only then take the average
MEAN_OF_CRPS = False

def get_skill(da, da_obs, weights, mean_of_crps):
    if mean_of_crps:
        crps_baseline = area_weighted_mean(xr.apply_ufunc(
            crps_ensemble, da_obs, da,
            input_core_dims=[['lat', 'lon'], ['lat', 'lon', 'model_ensemble']],
            output_core_dims=[['lat', 'lon']],
        ))

        crps_weighted = area_weighted_mean(xr.apply_ufunc(
            crps_ensemble, da_obs, da,
            input_core_dims=[['lat', 'lon'], ['lat', 'lon', 'model_ensemble']],
            output_core_dims=[['lat', 'lon']],
            kwargs={'weights': np.tile(weights, (da['lat'].size, da['lon'].size, 1))},
        ))
    else:
        crps_baseline = xr.apply_ufunc(
            crps_ensemble,
            area_weighted_mean(da_obs),
            area_weighted_mean(da),
            input_core_dims=[[], ['model_ensemble']],
        )

        crps_weighted = xr.apply_ufunc(
            crps_ensemble,
            area_weighted_mean(da_obs),
            area_weighted_mean(da),
            input_core_dims=[[], ['model_ensemble']],
            kwargs={'weights': weights},
        )

    return (crps_baseline - crps_weighted) / crps_baseline

def read_obs(ds, cfg):

    if cfg.obs_id is None:
        return None, None

    if isinstance(cfg.obs_id, str):
        cfg.obs_id = [cfg.obs_id]
        cfg.obs_path = [cfg.obs_path]

    ds_list = []
    for obs_path, obs_id in zip(cfg.obs_path, cfg.obs_id):

        filename = os.path.join(obs_path, '{}_mon_{}_g025.nc'.format(cfg.target_diagnostic, obs_id))
        ds_var = xr.open_dataset(filename, use_cftime=True)[cfg.target_diagnostic].load()

        if cfg.target_season != 'ANN':
            ds_var = ds_var.isel(time=ds_var['time.season'] == cfg.target_season)

        ds_var = (ds_var.sel(time=slice(str(cfg.target_startyear), str(cfg.target_endyear))).mean('time') -
                  ds_var.sel(time=slice(str(cfg.target_startyear_ref), str(cfg.target_endyear_ref))).mean('time'))

        ds_var = flip_antimeridian(ds_var)
        ds_var = ds_var.sel(lon=ds['lon'], lat=ds['lat'])

        if ds_var.max() > 100:  # assume Kelvin
            ds_var -= 273.15
            ds_var.attrs['unit'] = 'degC'

        ds_list.append(ds_var)

    ds_var = xr.concat(ds_list, dim='dataset')

    if cfg.target_mask == 'sea':
        sea_mask = regionmask.defined_regions.natural_earth.land_110.mask(ds_var, wrap_lon=180) == 0
        ds_var = ds_var.where(sea_mask)
    elif cfg.target_mask == 'land':
        land_mask = regionmask.defined_regions.natural_earth.land_110.mask(ds_var, wrap_lon=180) == 1
        ds_var = ds_var.where(land_mask)

    return ds_var.squeeze()

def main():
    fig, ax = plt.subplots()
    fig.subplots_adjust(left=.09, right=.99, bottom=.09, top=.94)
    c1, c2, _, c3 = sns.color_palette('colorblind', 4)
    colors = [c1, c3, ''] * 2
    alphas = [1, 1, ''] * 2

    #  skills = []
    for xx, filename_pattern in enumerate(FILENAMES):
        if filename_pattern == '':
            continue
        filename_pattern = os.path.join(LOADPATH, filename_pattern)
        if not filename_pattern.endswith('.nc'):
            filename_pattern += '.nc'
        filenames = glob(filename_pattern)
        skill_list = []
        assert len(filenames) > 0, filename_pattern
        for filename in filenames:
            ds = xr.open_dataset(filename)
            varn = ds.attrs['target']
            if 'weights_mean' in ds:
                ds = ds.drop_dims(('model_ensemble', 'perfect_model_ensemble'))
                ds = ds.rename({'model': 'model_ensemble', 'perfect_model': 'perfect_model_ensemble',
                                f'{varn}_mean': varn, 'weights_mean': 'weights'})
            cfg = read_config(ds.attrs['config'], ds.attrs['config_path'])
            # log_parser(cfg)
            ds_obs = read_obs(ds, cfg)
            skill = get_skill(ds[varn], ds_obs, ds['weights'], MEAN_OF_CRPS)
            skill_list.append(skill)

        skill = xr.concat(skill_list, dim='perfect_model_ensemble')
        boxplot(ax, xx, data=skill.data, showmean=False, showdots=False, color=colors[xx], alpha=alphas[xx])

        for fn, ss in zip(filenames, skill.data):
            pm = fn.split('_')[7]
            print(f'"{pm}": {ss},')

        # idxs = np.argsort(skill.data)[::-1]
        # print('---')
        # for idx in idxs[:]:
        #     if skill.data[idx] < 0:
        #         print(f'{os.path.basename(filenames[idx])}: {skill.data[idx]:.1%}')
        # # for idx in idxs[-3:]:
        # #     print(f'{os.path.basename(filenames[idx])}: {skill.data[idx]:.1%}')

        # print(skill.median().data)
    ax.grid(axis='y')
    ax.axhline(0, color='k', zorder=2)

    ax.set_xticks([.5, 3.5])
    ax.set_xticklabels(['2041-2060', '2081-2100'])

    h1 = boxplot(ax, [], data=skill.data, return_handle=True, showmean=False, showdots=False, color=c1, alpha=1)
    h3 = boxplot(ax, [], data=skill.data, return_handle=True, showmean=False, showdots=False, color=c3, alpha=1)
    leg = plt.legend([h1, h3], ['SSP1-2.6', 'SSP5-8.5'], loc='lower left', title='Median, 50\%, 90\%')
    leg._legend_box.align = 'left'

    ax.set_ylim(-1, 1)
    ax.set_yticklabels(np.around(ax.get_yticks() * 100).astype(int))
    ax.set_ylabel('CRPSS (\%)', labelpad=-3)

    ax.set_title('\\textbf{(a) Combined weighting perfect model test skill (CMIP5)}', loc='left',
                 fontdict={'size': 'large', 'weight': 'bold'})

    ax.annotate('Shown as map in (b)', (1, .22), (1.3, .65), arrowprops={'arrowstyle': '->'}, zorder=999)

    plt.savefig(os.path.join(SAVEPATH, SAVENAME), dpi=300)
    SAVEPATH2 = '/home/lukbrunn/Documents/Projects/Paper_CMIP6/figures'
    plt.savefig(os.path.join(SAVEPATH2, SAVENAME.replace('.png', '.pdf')), dpi=300)

if __name__ == '__main__':
    main()


#-------------------------------------------------------------------------
# AUTHOR: your name
# FILENAME: title of the source file
# SPECIFICATION: description of the program
# FOR: CS 4200- Assignment #2
# TIME SPENT: how long it took you to complete the assignment
#-----------------------------------------------------------*/

#IMPORTANT NOTE: DO NOT USE ANY ADVANCED PYTHON LIBRARY TO COMPLETE THIS CODE SUCH AS numpy OR pandas. You have to work here only with standard vectors and arrays

#importing some Python libraries
from sklearn.naive_bayes import GaussianNB
import csv
dbtraining =[]
target = {
    'Sunny':1,
    'Overcast':2,
    'Rain':3,
    'Hot':1,
    'Mild':2,
    'Cool':3,
    'High':1,
    'Normal':2,
    'Strong':1,
    'Weak':2
}
PT = {
    'Yes':1,
    'No':2
}
TP ={
    1:'Yes',
    2:'No'
}
#reading the training data
#--> add your Python code here
with open('weather_training.csv', 'r') as csvfile:
  reader = csv.reader(csvfile)
  for i, row in enumerate(reader):
      if i > 0: #skipping the header
         dbtraining.append (row)
#transform the original training features to numbers and add to the 4D array X. For instance Sunny = 1, Overcast = 2, Rain = 3, so X = [[3, 1, 1, 2], [1, 3, 2, 2], ...]]
#--> add your Python code here
# X =

X=[]
for item in dbtraining:
    temp=[]
    temp.append(target[item[1]])
    temp.append(target[item[2]])
    temp.append(target[item[3]])
    temp.append(target[item[4]])
    X.append(temp)
#transform the original training classes to numbers and add to the vector Y. For instance Yes = 1, No = 2, so Y = [1, 1, 2, 2, ...]
#--> add your Python code here
# Y =
Y=[]
for i in dbtraining:

    Y.append(PT[i[5]])
#fitting the naive bayes to the data
clf = GaussianNB()
clf.fit(X, Y)

#reading the data in a csv file
#--> add your Python code here
dbTest=[]
with open('weather_test.csv', 'r') as csvfile:
  reader = csv.reader(csvfile)
  for i, row in enumerate(reader):
      if i > 0: #skipping the header
         dbTest.append (row)
#printing the header os the solution
print ("Day".ljust(15) + "Outlook".ljust(15) + "Temperature".ljust(15) + "Humidity".ljust(15) + "Wind".ljust(15) + "PlayTennis".ljust(15) + "Confidence".ljust(15))

#use your test samples to make probabilistic predictions.
#--> add your Python code here
Z = []
for i in dbTest:
    temp = []
    temp.append(target[i[1]])
    temp.append(target[i[2]])
    temp.append(target[i[3]])
    temp.append(target[i[4]])
    Z.append(temp)
#-->predicted = clf.predict_proba([[3, 1, 2, 1]])[0]
    predicted_proba =clf.predict_proba([temp])[0]
    predicted = clf.predict([temp])[0]
    if predicted_proba[predicted-1] >=0.75:
     print(i[0].ljust(15) + i[1].ljust(15) + i[2].ljust(15) + i[3].ljust(15) + i[4].ljust(15) + TP[predicted].ljust(15) + str(predicted_proba[predicted-1]).ljust(15))


from typing import Optional

from geoalchemy2.types import Geometry
from sqlmodel import Column, Field, SQLModel

class Country(SQLModel, table=True):
    class Config:
        arbitrary_types_allowed = True

    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    population: int
    geometry: Geometry = Field(
        sa_column=Column(Geometry(geometry_type="POLYGON", srid=3035))
    )


import datetime as dt
import warnings
import re
import sys
from tempfile import NamedTemporaryFile

import pandas as pd
import requests
import camelot
from PyPDF2 import pdf as pdf2
from PyPDF2.utils import PdfReadWarning

def get_taxes_from_pdf(start_year: int = 2020) -> pd.DataFrame:
    base_url = "https://www.dgi.gub.uy/wdgi/page?2,principal,dgi--datos-y-series-estadisticas--informes-mensuales-de-la-recaudacion-"
    extra_url = ",O,es,0,"
    reports_year = range(start_year, dt.date.today().year + 1)
    data = []
    for year in reports_year:
        url = f"{base_url}{year}{extra_url}"
        r = requests.get(url)
        pdf_urls = re.findall("afiledownload\?2,4,[0-9]{4},O,S,0,[0-9]+"
                              "%[0-9A-z]{3}%[0-9A-z]{3}%3B108,", r.text)
        pdf_urls = list(dict.fromkeys(pdf_urls))
        if len(pdf_urls) == 0:
            continue
        dates = pd.date_range(start=dt.datetime(year, 1, 1), freq="M",
                              periods=len(pdf_urls))
        if sys.platform == "win32":
            delete = False
        else:
            delete = True
        for pdf, date in zip(pdf_urls, dates):
            with NamedTemporaryFile(suffix=".pdf", delete=delete) as f:
                r = requests.get(f"https://www.dgi.gub.uy/wdgi/{pdf}")
                f.write(r.content)
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=PdfReadWarning)
                    pages = pdf2.PdfFileReader(f.name).getNumPages()
                tables = camelot.read_pdf(f.name, flavor="stream",
                                          pages=str(pages), strip_text="%")
                table = tables[0].df.iloc[2:, [0, 3]]
                table.columns = ["Impuesto", date]
                table.set_index("Impuesto", inplace=True)
                table[date] = table[date].str.replace(",", ".", regex=False)
                table = (table.apply(pd.to_numeric, errors="coerce")
                         .dropna(how="any").T)
                table = table.loc[:,
                                  ["IVA",
                                   "IMESI",
                                   "IMEBA",
                                   "IRAE",
                                   "Categoría I",
                                   "Categoría II",
                                   "IASS",
                                   "IRNR",
                                   "Impuesto de Primaria",
                                   "6) Total Bruto (suma de (1) a (5))"]]
                # The may-21 table had hidden duplicate rows with different values
                # See https://www.dgi.gub.uy/wdgi/afiledownload?2,4,1879,O,S,0,36556%3BS%3B1%3B108,
                if table.shape[1] == 20:
                    table = table.iloc[:, 0:table.shape[1]:2]
                table.columns = [
                    'IVA - Valor Agregado',
                    'IMESI - Específico Interno',
                    'IMEBA - Enajenación de Bienes Agropecuarios',
                    'IRAE - Rentas de Actividades Económicas',
                    'IRPF Cat I - Renta de las Personas Físicas',
                    'IRPF Cat II - Rentas de las Personas Físicas',
                    'IASS - Asistencia a la Seguridad Social',
                    'IRNR - Rentas de No Residentes',
                    'Impuesto de Educación Primaria',
                    'Recaudación Total de la DGI']
                data.append(table)
    output = pd.concat(data)
    output.to_csv("econuy_extras/retrieval/taxes_pdf.csv")

    return output

if __name__=="__main__":
    get_taxes_from_pdf()


# coding: utf-8
# C04tk.py - Saisie utilisateur avec Entry

# importation du module tkinter
from tkinter import *

# création de la fenêtre avec son titre
maFenetre=Tk()
maFenetre.title('Première fenetre avec tkinter')

# définition de la taille de la fenêtre : 600x600 positionnée en x=150 et y=100
# sur l'écran
maFenetre.geometry('600x600+150+100')

# Création d'une étiquette texte - texte de couleur bleu (navy) et fond jaune
etiquette = Label(maFenetre, text="Exemple de widget Label",fg="navy",bg="yellow")

# Ajout de l'étiquette à la fenetre
etiquette.pack(side=TOP,padx=5,pady=5)

# Création d'un bouton Quitter pour fermer la fenetre
bouton_Quitter = Button(maFenetre,text="Quitter", command=maFenetre.destroy)

# Ajout du bouton dans la fenetre, en bas (BOTTOM), avec une marge de 5 de # chaque coté
bouton_Quitter.pack(side=BOTTOM,padx=5,pady=5)

# exécution de la boucle principale
maFenetre.mainloop()


import pickle as pkl
from flask import Flask
from flask_cors import CORS
from flask import request
from flask import jsonify

app = Flask('heart_model')
CORS(app)

file_dictVect = 'dict_vectorizer.bin'
with open(file_dictVect, 'rb') as dictVect:
    dv = pkl.load(dictVect)

file_model = 'logistic_regression.bin'
with open(file_model, 'rb') as model:
    lr = pkl.load(model)

@app.route('/predict', methods=['POST'])
def predict():
    user = request.get_json()
    X = dv.transform([user])
    y = lr.predict_proba(X)[0][1]
    danger = y >= 0.5

    result = {'danger': bool(danger),
              'probability':float(y)}
    return jsonify(result)

if __name__ == "__main__":
    app.run(debug=True, host='localhost', port=9696)


import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import keygen as kg
import numpy as np

def histogram (img):
    h = np.zeros((256,))
    for i in range(height):
        for j in range(width):
            h[img[i,j]] += 1
    return h

img1 = mpimg.imread('Ảnh/MRI-brain.jpeg')
img2 = mpimg.imread('Ảnh/ảnh mã hóa.bmp')
height = img1.shape[0]
width = img1.shape[1]

h1 = histogram(img1)
h2 = histogram(img2)

plt.subplot(1, 2, 1)
plt.bar(range(256), h1)
plt.subplot(1, 2, 2)
plt.bar(range(256), h2)
plt.show()


import numpy as np
import matplotlib.pyplot as plt
from utils import euler_method, graph_all, get_axis
from formulas import (
    power2force,
    force2acceleration,
    air_resistance_force,
    get_gravity_projections,
    friction_force,
)

def horse2watt(horsepower):
    return horsepower * 745.7

# Constants

GRAVITY = 9.81
RESISTANCE_COEFFICIENT = 0.9
FRONTAL_AREA = 0.3
AIR_DENSITY = 1.225
FRICTION_COEFFICIENT = 0.004

# Variables
power = horse2watt(0.4)
mass = 75

# Initial conditions
initial_position_x = np.array([0, 0, 0])
initial_velocity_x = np.array([1, 0, 0])
initial_acceleration_x = np.array([power / (mass * initial_velocity_x[0]), 0, 0])

# Time
TIME_STEP = 0.001
TIME_START, TIME_END = 0, 200
TIME = np.arange(TIME_START, TIME_END, TIME_STEP)
N = len(TIME)

def acceleration_formula(a, velocity, p):
    vx, vy, vz = velocity
    abs_velocity = abs(vx)
    abs_velocity_sqrd = abs_velocity * vx

    acceleration_x = (
        power / (mass * vx)
        - (RESISTANCE_COEFFICIENT * FRONTAL_AREA * AIR_DENSITY * abs_velocity_sqrd)
        / (2 * mass)
        - (FRICTION_COEFFICIENT * GRAVITY)
    )

    acceleration = np.array([acceleration_x, 0, 0])

    return acceleration

def acceleration_formula2(a, velocity, p):
    force = (
        power2force(power, velocity)
        + air_resistance_force(RESISTANCE_COEFFICIENT, FRONTAL_AREA, velocity)
        + friction_force(velocity, FRICTION_COEFFICIENT, GRAVITY)
    )

    acceleration = force2acceleration(force, mass)

    return acceleration

def main():
    p, v, a = euler_method(
        TIME,
        TIME_STEP,
        initial_acceleration=initial_acceleration_x,
        initial_velocity=initial_velocity_x,
        initial_position=initial_position_x,
        acceleration_formula=acceleration_formula2,
        cromer=True,
    )

    px = get_axis(p, 0)
    vx = get_axis(v, 0)
    ax = get_axis(a, 0)
    arrays = [px, vx, ax]

    print("Terminal velocity: ", np.max(vx))

    fig, ax = plt.subplots(1, 3, figsize=(16, 8))

    graph_all(ax, TIME, arrays, ["Position", "Velocity", "Acceleration"], grid=False)

    plt.show()

if __name__ == "__main__":
    main()


import numpy as np

class Table:
    def __init__(self, width, length, index):
        self.width = int(width*5)
        self.length = int(length*5)
        self.location = (-1,-1)

        self.table_number = index
        self.mass_center = (0, 0)
        self.min_distance = np.inf

    def shuffle(self):
        n = np.random.randint(0, 2)
        if n == 1:
            temp = self.length
            self.length = self.width
            self.width = temp


from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.types import InputMediaVideo
from aiogram.utils import executor
from aiogram.utils.markdown import bold

from config import TOKEN

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)

cities = {
    "Калининград" : ["Аптека №12 ул. Багратиона 53а","Здоровье Дзержинского 19"],
    "Багратионовск" : ["Аптека №11 ул. Центральная 5","Здоровье Багратиона 1"]
         }
@dp.message_handler(commands=["start"])
async def process_start_command(message: types.Message):
    await message.reply("Привет\nНапиши мне город")

@dp.message_handler()
async def process_multimedia_command(message: types.Message):
    data = cities[message.text]
    for item in data:
        await message.answer(item)

if __name__ == "__main__":
    executor.start_polling(dp)


"""
Srhmd.py
Daemon running on robot hosts that:
    - Extracts extrinsic data and keeps state
    - Extracts intrinsic data and aggregates with extrinsic data
    - Sends aggregated message to server
"""

from Comms import Comms, Message
import threading
import psutil
import time
import json
import socket

class Srhmd:
    def __init__(self, config_path="resources/srhmd_test_config.json"):
        """
        Attributes:
            - name: String
                Robot identifier
            - comms: Comms
                Message queue manager
                Set up producer to server IP on port 3000
                Set up consumer on port 3100 to accept sensor data
            - ext_states: Dict<String:Float>
                Extrinsic data states
            - update_interval: Float
                Extrinsic sensor read rate
            - agg_interval: Float
                Messaging rate to server
        """
        self.name = self.get_ip()
        self.comms = Comms()
        self.comms.add_subscriber_port('127.0.0.1', '3100', 'ext_sensors')

        self.ext_sensors = dict()

        with open(config_path) as f:
            config = json.load(f)
        self.comms.add_publisher_port('*', config['port'], self.name)
        self.update_interval = float(config['update_interval'])
        self.agg_interval = float(config['agg_interval'])

    @staticmethod
    def get_ip():
        """Grab host ip"""
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('10.255.255.255', 1))
            IP = s.getsockname()[0]
        except Exception:
            IP = '127.0.0.1'
        finally:
            s.close()
        return IP

    def update_ext(self):
        """
        Threaded
        Poll consumer for new sensor states and update ext_states
        :return:
            None
        """
        while True:
            # Poll all messages in buffer and substitute into ext_sensors
            msg = self.comms.get('ext_sensors')
            if msg is not None:
                key = next(iter(msg.payload))
                self.ext_sensors[key] = msg.payload.get(key)
                time.sleep(self.update_interval)

    def aggregator(self):
        """
        Threaded
        Extract intrinsic data and aggregate with ext_states
        Assemble message and publish to server
        :return:
            None
        """
        while True:
            # Payload dictionary
            payload = dict()

            # Core speed
            payload["cpu_freq"] = psutil.cpu_freq().current

            # Cpu usage
            for count, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
                payload["cpu_percent" + str(count)] = percentage
            payload["cpu_percent"] = psutil.cpu_percent()

            # Memory usage
            svmem = psutil.virtual_memory()
            payload["svmem_total"] = svmem.total
            payload["svmem_available"] = svmem.available
            payload["svmem_used"] = svmem.used
            payload["svmem_percentage"] = svmem.percent

            # Aggregate with external sensors
            payload.update(self.ext_sensors)

            # Send payload
            print(payload)
            self.comms.send(self.name, Message(self.name, payload))

            # Refresh rate
            time.sleep(self.agg_interval)

    def run(self):
        """
        Start update_ext and aggregator threads
        :return:
            None
        """
        threads = []
        t = threading.Thread(target=self.update_ext)
        threads.append(t)
        t = threading.Thread(target=self.aggregator)
        threads.append(t)

        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()

if __name__ == "__main__":
    # Local boilerplate
    srhmd = Srhmd("srhmd_conf/config.json")
    srhmd.run()


"Entada de dados"
'''
nome = str(input("Qual o seu nome? \n"))
idade = int(input("Qual sua idade? \n"))
'''

escolha = str(input("Escolha a operação\n + para soma\n - para subtração\n"))

print("Pronto, escolha os valores")
numero_1 = int(input("Digite um valor \n"))
numero_2 = int(input("Digite um valor \n"))

if escolha == "+":
    resultado = numero_1+numero_2
    print(resultado)

elif escolha == "-":
    resultado = numero_1-numero_2
    print(resultado)

else:
    print("Valor incorreto")

#ano_atual=2022

#nascimento = ano_atual-int(idade)

#print(f'Seu nome é: {nome} e nasceu em {nascimento}')


import pyflo.ports

import pytest
from unittest.mock import Mock

def test_invalid_event_type():
    port = pyflo.ports.Inport({"name": "test"})
    with pytest.raises(KeyError):
        port.on('dummy', print)

def test_decorator():
    port = pyflo.ports.Inport({"name": "test"})
    mock = Mock()

    @port.on("data")
    def some_function(data):
        mock(data)

    port.data("data")

    mock.assert_called_once_with("data")

def test_connect():
    inport = pyflo.ports.Inport({"name": "in"})
    mock = Mock()
    inport.on('connect', mock)
    outport = pyflo.ports.Outport({"name": "out"})

    outport.connect(inport)
    assert inport in outport.listeners
    mock.assert_called_once_with()
    assert inport.attached()

def test_begin_end_group():
    inport = pyflo.ports.Inport({"name": "in"})
    mock = Mock()
    mock2 = Mock()
    inport.on('beginGroup', mock)
    inport.on('endGroup', mock2)
    outport = pyflo.ports.Outport({"name": "out"})

    outport.connect(inport)
    outport.begin_group()
    mock.assert_called_once_with()
    mock2.assert_not_called()
    outport.end_group()
    mock2.assert_called_once_with()

def test_send_data():
    inport = pyflo.ports.Inport({"name": "in"})
    mock = Mock()
    inport.on('data', mock)
    outport = pyflo.ports.Outport({"name": "out"})

    outport.connect(inport)
    outport.send_data("data")
    mock.assert_called_once_with("data")

def test_disconnect():
    inport = pyflo.ports.Inport({"name": "in"})
    mock = Mock()
    inport.on('disconnect', mock)
    outport = pyflo.ports.Outport({"name": "out"})

    outport.connect(inport)
    outport.disconnect()
    mock.assert_called_once_with()

def test_pass_through():
    external_port = pyflo.ports.Outport({"name": "out"})
    ptp = pyflo.ports.PassThroughPort({"name": "pass"})
    internal_port = pyflo.ports.Inport({"name"})

    mock = Mock()
    internal_port.on("data", mock)

    external_port.connect(ptp)
    ptp.connect(internal_port)

    external_port.send_data("data")
    mock.assert_called_once_with("data")


import logging
import re
import tornado.escape
import tornado.web
import tornado.websocket
import uuid
from .main import BaseHandler
from tornado.web import authenticated
from utils.account import func

class RoomHandler(BaseHandler):
    """
    聊天室
    """

    @authenticated
    def get(self):
        ret = func(self.current_user)
        self.render('room.html', messages=ChatSocketHandler.cache, ret=ret)

class ChatSocketHandler(tornado.websocket.WebSocketHandler, BaseHandler):
    waiters = set()  # 等待接收消息的用户
    cache = []  # 存放消息
    cache_size = 200  # 消息列表的大小

    def get_compression_options(self):
        """
        非None的返回值开启压缩
        :return:
        """
        return {}

    def open(self):
        """
        新的WebSocke连接打开
        :return:
        """
        logging.info("new connection %s" % self)
        ChatSocketHandler.waiters.add(self)

    def on_close(self):
        """
        WebSocket连接断开
        :return:
        """
        return ChatSocketHandler.waiters.remove(self)

    @classmethod
    def update_cache(cls, chat):
        """
        跟新消息列表，加入新的消息
        :param chat:
        :return:
        """
        cls. \
            cache.append(chat)
        if len(cls.cache) > cls.cache_size:
            cls.cache = cls.cache[-cls.cache_size:]

    @classmethod
    def send_updates(cls, chat):
        """
        给每个等待接收的用户发新的消息
        :param chat:
        :return:
        """
        logging.info("sending message to %d waiters", len(cls.waiters))
        for waiter in cls.waiters:
            try:
                waiter.write_message(chat)
            except:
                logging.error("Error sending message", exc_info=True)

    def on_message(self, message):
        """WebSocket 服务器端接收到消息"""
        logging.info("got message %r", message)
        parsed = tornado.escape.json_decode(message)
        if parsed["body"] == '':
            return
        if re.findall(r'^http://.*.jpg$', parsed["body"]) != []:
            img_url = 'http://127.0.0.1:8000/save?url={}&from=room&user={}'.format(parsed["body"], self.current_user)
            from tornado.httpclient import AsyncHTTPClient
            from tornado.ioloop import IOLoop
            c = AsyncHTTPClient()
            IOLoop.current().spawn_callback(c.fetch, img_url)
            chat = {
                "id": str(uuid.uuid4()),
                "username": '--admin',
                "body": '{},url is processsing:{}'.format(self.current_user, parsed["body"]),
                "img": None,
            }
            chat["html"] = tornado.escape.to_basestring(self.render_string("message.html", message=chat))
            self.write_message(chat)
        else:
            chat = {
                "id": str(uuid.uuid4()),
                "body": parsed["body"],
                'username': '--{}'.format(self.current_user),
                "img": None,
            }
            chat["html"] = tornado.escape.to_basestring(self.render_string("message.html", message=chat))
            print(chat["html"])
            ChatSocketHandler.update_cache(chat)
            ChatSocketHandler.send_updates(chat)


import cv2 as cv

img = cv.imread('Photos/lady.jpg')
cv.imshow('Lady', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Graysclae', gray)

haar_cascade = cv.CascadeClassifier('haar_face.xml') # - reads
# cv.CascadeClassifier (xml file) reads the xml trained data

faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3 )
print(f'number of faces found = {len(faces_rect)}')
# number of faces found = 1

# - draw a rectangle
for (x,y,w,h) in faces_rect:
    cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)

cv.imshow('detected face', img)

# group 2
group =  cv.imread('Photos/group 2.jpg')
gray_group = cv.cvtColor(group, cv.COLOR_BGR2GRAY)
cv.imshow('Gray group 2', gray_group)
# faces_rect = haar_cascade.detectMultiScale(gray_group, scaleFactor=1.1, minNeighbors=3 )

# shows 7 ()additionally stomachs as faces
#  but true val is 5, it is because of the noise in the image
# -- so we increase min neighbours to 7
faces_rect = haar_cascade.detectMultiScale(gray_group, scaleFactor=1.1, minNeighbors=6)
print(f'number of faces found = {len(faces_rect)}')
# ---
for (x,y,w,h) in faces_rect:
    cv.rectangle(group, (x,y), (x+w,y+h), (0,255,0), thickness=2)

cv.imshow('Group', group)

# group 1
group1 =  cv.imread('Photos/group 1.jpg')
gray_group1 = cv.cvtColor(group1, cv.COLOR_BGR2GRAY)
faces_rect = haar_cascade.detectMultiScale(gray_group1, scaleFactor=1.1, minNeighbors=1)
print(f'number of faces found = {len(faces_rect)}')
# number of faces found = 14 with k=3
# number of faces found = 19 with k=1
# --- so by minimizing k, we are more prone to noise
for (x,y,w,h) in faces_rect:
    cv.rectangle(group1, (x,y), (x+w,y+h), (0,255,0), thickness=2)
    # some faces are not chosen bc they are not perpendicular to the camera

cv.imshow('Group 1', group1)

cv.waitKey(0)


from itertools import permutations
n = int(input())
k = int(input())
a = []
for i in range(1,n+1):
    a.append(i)
l= list(permutations(a,n))
l_ = []
for i in range(len(l)):
    s = ''
    for j in range(n):
        s += str(l[i][j])
    l_.append(s)
l_.sort()
print(l_[k-1])


# Sylvia Dee
# PSM d18O Speleothem Calcite
# SENSOR SUB-MODEL
# Created 07/02/2014 <sdee@usc.edu>
# Modified 10/28/2014 <julieneg@usc.edu>

# import necessary modules
import numpy as np
import scipy.integrate as si
import scipy.special as sp
import psm.aux_functions.butter_lowpass_filter as bwf
# define utility functions for lowpass filtering

def adv_disp_transit(tau,tau0,Pe):
    #  advection-dispersion model [3]
    z0 = -0.5*np.sqrt(Pe*tau/tau0)   #(Eq 12a)
    zL = np.sqrt(Pe/tau*tau0) + z0   #(Eq 12b)
    h  = np.sqrt(1/(Pe*4*np.pi*tau/tau0))*np.exp(-0.25*Pe*tau/tau0)*(1 - np.exp(z0**2-zL**2)) + 0.25*(sp.erf(zL) - sp.erf(z0))  # Eq(11)
    return h

#  this is the sensor model
def speleo_sensor(t,d18O,T,dt,model='Adv-Disp',tau0=1.0,Pe=1.0):
    '''
    Speleothem Calcite [Sensor] Model
    Converts environmental signals to d18O calcite/dripwater using
    various models of karst aquifer recharge and calcification.

    INPUTS:
        dt        time step [years]                         (int or float, 1=1 year, 1./12. for months. etc.)
        t        time axis [years]                          (numpy array, length n)
        T        Average Annual Temperature     [K]         (numpy array, length n)
        d18O    delta-18-O (precip or soil water) [permil]  (numpy array, length n)
        NB: make sure these are precipitation weighted

    MODEL PARAMETERS
    ================
        model:  aquifer recharge model. possible values 'Well-Mixed'[1,2] or 'Adv-Disp' [3]
        tau0: mean transit time, [years]    (default = 0.5)
        Pe: Peclet number [non-dimensional] (default = 1.0) ('Adv-Disp' only)

     OUTPUTS:
         d18Oc  cave dripwater delta-18-O
         d18OK  delta-18-O of water after passage through karst
         h      transit time distribution

    REFERNCES:
        [1] Gelhar and Wilson: Ground Water Quality Modeling, Ground Water, 12(6):399--408
        [2] Partin et al., Geology, 2013, doi:10.1130/G34718.1  (SI)
        [3] Kirchner, J. W., X. Feng, and C. Neal (2001), Catchment-scale advection and dispersion as a mechanism for fractal scaling in stream
        [4] Wackerbarth et al. Modelling the d18O value of cave drip water and speleothem calcite, EPSL, 2010    doi:10.1016/j.epsl.2010.09.019
    '''
    #======================================================================
    # 1. Karst Model
    #======================================================================
    # ensure that tau0 is scaled correctly
    # (n.b. if in units of months, scale to years, *1/12)

    tau0=tau0*dt

    # Check to make sure mean residence time does not exceed 0.5 x [time series length]
    # It makes little sense to compute mixing with a long residence time with an extremely short timeseries.

    timeseries_len=len(d18O)#*dt
    if (tau0>=(0.5*timeseries_len)):
        print("Warning: mean residence time (tau0) is too close to half of the length of the timeseries.")

    # establish kernel length for transit time distribution
    # tau=np.arange(20.*tau0) {SDEE: revised 11/17/15}

    h_s=1E-4                        # ensure kernel approaches 0
    tau_s=-tau0*np.log(tau0*h_s)
    tau=np.arange(tau_s)

    # np.convolve method will freakout if the length of the kernel approaches that of the series.
    #return an error message and not perform the calculation: the effect of a kernel
    #of length L is roughly felt over 2*L +1, so 7 years in this case, which is the the length of the series.
    #Physically, it makes little sense to try and compute this in the first place,
    #so it would be better to explain to the user why this shouldn’t be attempted rather than return a meaningless estimate.

    if (len(tau)>=(0.5*timeseries_len)):
        print("Error: kernel length is too close to half of the length of the timeseries. This will result in spurious numerical effects: the effect of a kernel of length L is roughly felt over 2*L+1. Consider revising.")

    # define the transit time distribution h(tau) owing to several models
    if model == 'Well-Mixed':  # well-mixed reservoir model as in [1,2]
        h = (1./tau0) * np.exp(-tau/tau0)
    elif model == 'Adv-Disp':  #  advection-dispersion model [3]
        h = adv_disp_transit(tau,tau0,Pe)
        h[0] = adv_disp_transit(1e-3,tau0,Pe) # fix the pathological case at tau = 0
    else:
        print("Error: model " + model + " not found")

    # obtain normalization constant using Simpson's rule
    hint = si.simps(h,tau)
    # normalize transit time distribution
    h = h/hint

    # Normalize h to the min value of the timeseries
    #mindiff=min(np.abs(d18O-d18Om))

    # Remove mean to avoid boundary effects. (then put it back)
    d18Om = np.mean(d18O)

    # Shrink the exponential such that it doesn't add spurious variance to the resulting dripwater signal.
    hmax=max(np.abs(d18O-d18Om))
    #h=h/hmax
    h = h/np.sum(h)

    #convolve d18O input with the transit time distribution (Green's function of the problem)
    # this yields the d18O of aquifer water, after passage through the karst

    #d18OK = np.convolve((d18O-d18Om),h,mode='same') + d18Om
    d18OK = np.convolve((d18O-d18Om),h,mode='full') + d18Om

    # return to original shape
    #d18OK = d18OK[0:Ldata]
    #======================================================================
    #   2. Dripwater Model
    #======================================================================
    # NB: right now this is only temperature-Dependent Fractionation, but one could
    #    add any number of relevant processes here, as in [4]
    # NB: we assume yearly data, so T is the yearly average temperature for each time step.
    #   the "average temperature" used for the thermal fractionation calculation is
    #   somewhat arbitrarily the decadal average.
    #======================================================================
    # SDEE: use next part for yearly data/longer term speleos only.
    #avg_period = 10.0
    #Tm = np.mean(T)  # extract mean
    # lowpass filter the  temperature
    #Tl = bwf.filter(T-Tm,1.0/avg_period) + Tm
    #Tl = filter(T-Tm,1.0/avg_period) + Tm
    #======================================================================
    # apply thermal fractionation (Eq 11 in [4])
    Tl = T
    d18Oc = (d18OK + 1000)/1.03086*np.exp(2780/Tl**2 - 0.00289)-1000.0
#======================================================================
    return (d18Oc, d18OK, h, tau)


f=open("input.text",'r')
read_data=f.readlines()
for i in range(len(read_data)):
    read_data[i]=read_data[i].strip()

if '' in read_data:
    while '' in read_data:
        read_data.remove('')
read_data_copy=read_data
print(read_data_copy)
list1=["~$",'$~','AND',"OR","NOT",'~','<','>','<=','>=','==','IF','CURL','S@','E@',"G@",':','(',')','[',']','REST_ALL','=',"+","-",'*','/','^','NOT=']
'''
i=0
k=0
t1=t2=t3=t4=t5=t6=t7=t8=t9=t10=t11=t12=t13=t14=t15=t16=t17=t18=t19=t20=t21=t22=t23=t24=t25=t26=t27=0
for i in range(len(read_data)):
    str1=read_data[i]
    for k in range(len(str1)):
        if '~$' in str1:
            print('~$      :      opening symbol of programme ')
            read_data[i].replace("~$",'')
            print(read_data[i])
        if '$~' in str1:
            print('$~      :       closing symbol of programme ')
        if '~' in str1:
            if(t1==0):
               print('~    :      closing statement ')
               t1=t1+1
        if '(' in str1:
            if(t2==0):
               print('(    :      opening bracket ')
               t2=t2+1
        if ')' in str1:
            if(t3==0):
               print(')    :      closing bracket ')
               t3=t3+1
        if ':' in str1:
            if(t4==0):
               print(':    :      colon ')
               t4=t4+1
        if '[' in str1:
            if(t5==0):
               print('[    :      opening bracket ')
               t5=t5+1
        if ']' in str1:
            if(t6==0):
               print(']    :      closing statement ')
               t6=t6+1
        if 'NOT' in str1:
            if(t7==0):
               print('NOT  :      logic operator ')
               t7=t7+1
        if 'AND' in str1:
            if(t8==0):
               print('AND    :      logic operator ')
               t8=t8+1
        if 'OR' in str1:
            if(t9==0):
               print('OR    :      logic operator ')
               t9=t9+1
        if '==' in str1:
            if(t10==0):
               print('==    :      logic operator ')
               t10=t10+1
        if '<' in str1:
            if(t11==0):
               print('>    :      logic operator ')
               t11=t11+1
        if '>' in str1:
            if(t12==0):
               print('>    :      logic operator ')
               t12=t12+1
        if 'NOT=' in str1:
            if(t13==0):
               print('NOT=    :      logic operator ')
               t13=t13+1
        if '>=' in str1:
            if(t14==0):
               print('>=    :      logic operator ')
               t14=t14+1
        if '<=' in str1:
            if(t15==0):
               print('<=    :      logic operator ')
               t15=t15+1
        if '+' in str1:
            if(t16==0):
               print('+    :      arithmetic operator ')
               t16=t16+1
        if '-' in str1:
            if(t17==0):
               print('-    :      arithmetic operator ')
               t17=t17+1
        if '*' in str1:
            if(t18==0):
               print('*    :      arithmetic operator ')
               t18=t18+1
        if '/' in str1:
            if(t19==0):
               print('/    :      arithmetic operator ')
               t19=t19+1
        if '^' in str1:
            if(t20==0):
               print('^    :      arithmetic operator ')
               t20=t20+1
        if 'CURL' in str1:
            if(t21==0):
               print('CURL    :      loop keyword ')
               t21=t21+1
        if 'IF' in str1:
            if(t22==0):
               print('IF    :      IF keyword ')
               t22=t22+1
        if 'REST_ALL' in str1:
            if(t23==0):
               print('REST_ALL    :      ELSE keyword ')
               t23=t23+1
        if 'S@' in str1:
            if(t24==0):
               print('S@    :       keyword ')
               t24=t24+1
        if 'E@' in str1:
            if(t25==0):
               print('E@    :       keyword ')
               t25=t25+1
        if 'G@' in str1:
            if(t26==0):
               print('G@    :       keyword ')
               t26=t26+1
        if '='  in str1:
            if(t27==0):
                print('=    :    assignment operator')
                t27=t27+1
print(read_data1)
   '''
my_list=['~','$','[',']','(',')',':','=','>','<','+','-','/','*','^']
i=0
k=0
for i in range(len(read_data)):
    str=read_data[i]
    for k in range(len(str)):
        if str[k] in my_list:
            str=str.replace(str[k],' ')
    read_data[i]=str

i=0
k=0
for i in range(len(read_data)):
    str=read_data[i]
    if "G@" in str:
        str=str.replace("G@",' ')
    if "E@" in str:
        str=str.replace("E@",' ')
    if "S@" in str:
        str=str.replace("S@",' ')
    if "REST_ALL" in str:
        str=str.replace("REST_ALL",' ')
    if "IF" in str:
        str=str.replace("IF",' ')
    if "CURL" in str:
        str=str.replace("CURL",' ')
    if "AND" in str:
        str=str.replace("AND",' ')
    if "OR" in str:
        str=str.replace("OR",' ')
    if "NOT" in str:
        str=str.replace("NOT",' ')
    read_data[i]=str

print("final",read_data)

i=0
k=0
IsDigit=0
for i in range(len(read_data)):
    str=read_data[i]
    temp_list=str.split()
    #print(temp_list)
    for k in range(len(temp_list)):
        if temp_list[k].isdigit():
            IsDigit=1
            print(temp_list[k],":CONSTANT")
        if temp_list[k].isalnum() and IsDigit!=1:
            print(temp_list[k],':VARIABLE')


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import relationship

Base = declarative_base()
metadata = MetaData()

# Don't forget to add password attribut on users table

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    firstname = Column(String)
    addresses = relationship('Address', backref='user')

    def __init__(self, name, firstname, addresses=[]):
        self.name = name
        self.firstname = firstname
        self.addresses = addresses

    def __repr__(self):
        return "<User(name='%s', firstname'%s', email='%s')>" % (
            self.name, self.firstname)

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('user.id'))

    def __repr__(self):
        return "<Address(email='%s')>" % (
            self.email)

if __name__ == '__main__':
    engine = create_engine('postgresql://localhost/ingredients_db')

    print("--- Construct all tables for the database (here just one table) ---")
    Base.metadata.create_all(engine)

    print("--- Create three new contacts and push its into the database ---")
    Session = sessionmaker(bind=engine)
    session = Session()
    a = Address(email='fred@aol.com')
    session.add(User(name='wendy', firstname='Williams'))
    # p.addresses.append(a)
    session.add(a)
    # session.add(p)
    session.commit()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/30 0030 20:42
# @Author  : Letao
# @Site    :
# @File    : 二进制中1的个数.py
# @Software: PyCharm
# @desc    :

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        while n:
            if n & 1:
                res += 1
            n = n >> 1
        return res


import re

sourceText =""

def convert(text):
    mphPattern = r"\d+\.?\d*\smph"
    floatPattern = r"\d+\.?\d*"
    match = re.finall(mphPattern, text)
    for item in match:
        value = re.finall(floatPattern, item)
        kmValue = float(value[0])*1.60934
        kmph = format(kmValue, ".1f") + "km/h"
        text = text.replace(item, kmph)
    return text

print(sourceText)
convertedText = convert(sourceText)
print(convertedText)


class Solution:
    def binary_search(self, nums, target, left, right):
        if left > right:
            return [-1,-1]

        mid = (left + right) // 2

        if nums[mid] == target:
            start = mid
            end = mid
            for i in range(1,(right-left)//2+2):
                start_check = start
                end_check = end

                if mid-i >= left and nums[mid-i] == nums[mid]:
                    start = mid - i
                if mid+i <= right and nums[mid+i] == nums[mid]:
                    end = mid + i

                if start_check == start and end_check == end:
                    return [start,end]

            return [start,end]

        if target > nums[mid]:
            return self.binary_search(nums,target,mid+1,right)
        else:
            return self.binary_search(nums,target,left,mid-1)

    def searchRange(self, nums: List[int], target: int) -> List[int]:

        return self.binary_search(nums,target,0,len(nums)-1)


# CLI to scrape TrendMicro encyclopedia & display malware severity rating in terminal
# requires BeautifulSoup & lxml parser & textwrap

## usage:
##   python malware_severity.py
##

import urllib2
import sys
import textwrap
from StringIO import StringIO
from bs4 import BeautifulSoup, Comment

class TrendMicroRiskAssessment:
	def __init__(self, keyword):
		self.keyword = keyword

	def search(self, fuzzySearch = False):

		url = 'http://www.trendmicro.com/vinfo/us/threat-encyclopedia/search/' + self.keyword
		r = urllib2.urlopen(url)
		h = r.read()
		p = BeautifulSoup(h, "lxml")

		# strip out comments & head tag
		comments = p.findAll(text=lambda text:isinstance(text, Comment))
		[comment.extract() for comment in comments]
		p.head.extract()

		# Check whether the term is found by searching for "0 Search Result" in the page.
		# If this string does not exist on the page, it means some results are found;
		# otherwise, there is no result found.
		found_result = False if p.find("div", class_ = "listContent").contents[7].get_text().find("0 Search Result") >= 0 else True

		if found_result:

			try:
				first_result_url = p.find("div", class_ = "resultbox_title").a.get('href')
				first_result_page = urllib2.urlopen(first_result_url)
				malware_page = BeautifulSoup(first_result_page.read(), "lxml")
				risk_rating_element = malware_page.find("div", class_ = "malwareHeader").find("div", class_="headerRight").contents[0].find("div", class_="ratingImage").find("img").get("src")

				risk_rating = risk_rating_element.split("/")[-1][:-4]
				return risk_rating
			except AttributeError:
				print("Failure to load assessment for {0} due to page format issue.".format(self.keyword))
				return "Page Error"

		# try to search for malwares in the same category and return the average rating of these malwares
		elif fuzzySearch:
			return "NA"
		# return no result
		else:
			return "NA"

class TrendMicroRiskAssessmentTest:
	def __init__(self):
		self.risk_rating = dict()

	# Read the test file
	def readTestFile(self, filename):
		with open(filename) as f:
			for line in f:
				key, value  = line.split(",")
				self.risk_rating[key] = value[:-1]

	# return whether or not our script returns the same rating as the ratings on file
	def test(self, fuzzySearch):
		failed_set = []
		for risk in self.risk_rating.keys():
			print("Checking {}".format(risk))
			script_rating = TrendMicroRiskAssessment(risk).search(fuzzySearch)
			if script_rating == "Page Error":
				pass
			elif not script_rating.lower() == self.risk_rating[risk].lower():
				print("{0} should be {1}, but was identified as {2}".format(risk, self.risk_rating[risk], script_rating))
				failed_set.append(risk)

		return len(failed_set) == 0

while True:
	mode = raw_input('Enter 1 for malware risk assessment. \nEnter 2 to run test for this script. \nEnter 3 to exist\n')

	# single assessment mode
	if mode == "1":
		ref = "%20".join(raw_input("Enter the name of the malware.\n"))
		fuzzy = True if (raw_input("Enter 1 to enable fuzzy search. 0 to disable\n") == "1") else False
		risk = TrendMicroRiskAssessment(ref).search(fuzzy)
		print(risk)
	# testing mode
	elif mode == "2":
		testObject = TrendMicroRiskAssessmentTest()
		fileName = raw_input("Enter test file name. Default: test.csv\n")
		fuzzy = True if (raw_input("Enter 1 to enable fuzzy search. 0 to disable\n") == "1") else False
		risk = TrendMicroRiskAssessment(ref).search(fuzzy)
		# use "test.csv" by default
		if fileName == None or fileName == "":
			fileName = "test.csv"
		testObject.readTestFile(fileName)
		print(testObject.test(fuzzy))
	# exit mode
	elif mode == "3":
		print("Goodbye!")
		break;
	else:
		print("Sorry, your input is invalid. Try again!")


import pandas as pd
import numpy as np

class Dataset:
    def __init__(self, name):
        self.name = name
        train = pd.read_csv(f'logistic_regression/data/{name}_train.csv', index_col=0)
        self.X_train = np.array(train.iloc[:, :-1])
        self.y_train = self._change_class_to_0_1(train.iloc[:, -1])
        test = pd.read_csv(f'logistic_regression/data/{name}_test.csv', index_col=0)
        self.X_test = np.array(test.iloc[:, :-1])
        self.y_test = self._change_class_to_0_1(test.iloc[:, -1])

    @staticmethod
    def _change_class_to_0_1(df):
        array = np.array(df)
        if np.sum(array==2) > 0:
            array[array==1] = 0
            array[array==2] = 1
        return array

names = ['banknote', 'diabetes', 'madelon', 'ozone', 'steel']
datasets = []
for name in names:
    datasets.append(Dataset(name))


import argparse
import glob
import subprocess
import os

# cuDNN package list from https://developer.nvidia.com/rdp/cudnn-download
cudadict = [{"ver": "7.1", "cudver": "9.1", "uri": "cudnn-9.1-linux-x64-v7.1.tgz"},
            {"ver": "7.1", "cudver": "9.0", "uri": "cudnn-9.0-linux-x64-v7.1.tgz"},
            {"ver": "7.1", "cudver": "8.0", "uri": "cudnn-8.0-linux-x64-v7.1.tgz"},
            {"ver": "7.0", "cudver": "9.1", "uri": "cudnn-9.1-linux-x64-v7.tgz"},
            {"ver": "7.0", "cudver": "9.0", "uri": "cudnn-9.0-linux-x64-v7.tgz"},
            {"ver": "7.0", "cudver": "8.0", "uri": "cudnn-8.0-linux-x64-v7.tgz"},
            {"ver": "6.0", "cudver": "8.0", "uri": "cudnn-8.0-linux-x64-v6.0.tgz"},
            {"ver": "6.0", "cudver": "7.5", "uri": "cudnn-7.5-linux-x64-v6.0.tgz"},
            {"ver": "5.1", "cudver": "8.0", "uri": "cudnn-8.0-linux-x64-v5.1.tgz"},
            {"ver": "5.1", "cudver": "7.5", "uri": "cudnn-7.5-linux-x64-v5.1.tgz"},
            {"ver": "5.0", "cudver": "8.0", "uri": "cudnn-8.0-linux-x64-v5.0-ga.tgz"},
            {"ver": "5.0", "cudver": "7.5", "uri": "cudnn-7.5-linux-x64-v5.0-ga.tgz"},
            {"ver": "4.0", "cudver": "7.0",
                "uri": "cudnn-7.0-linux-x64-v4.0-prod.tgz"},
            {"ver": "3.0", "cudver": "7.0",
                "uri": "cudnn-7.0-linux-x64-v3.0.8-prod.tgz"},
            {"ver": "2.0", "cudver": "6.5", "uri": "cudnn-6.5-linux-x64-v2.tgz"},
            {"ver": "1.0", "cudver": "6.5", "uri": "cudnn-6.5-linux-R1.tgz"}]

def runprocess(command):
    try:
        subprocess.call(command, shell=True)
    except Exception as e:
        print(e)

def versionSelector(version, cudaver):
    uri = ""
    for i, k in enumerate(cudadict):
        if cudadict[i]['ver'] == str(version) and cudadict[i]['cudver'] == str(cudaver):
            print(cudadict[i]['uri'])
            uri = cudadict[i]['uri']
    if uri != "":
        return uri

def switchCudnn(version, cudadir, cudaver):
    packagename = versionSelector(version, cudaver)
    if packagename != None:
        packages = glob.glob("packages/{}".format(packagename))
        lenfiles = len(packages)
        print("cudnn version {}".format(version))
        print("cuda dir path : {}".format(cudadir))
        if lenfiles:
            print("Switching cudnn version {}".format(version))
            runprocess('mkdir packages/cudnn')
            runprocess(
                'tar xf {} -C packages/cudnn --strip-components 1'.format(packages[0]))
            runprocess('sudo rm -rf {}/include/cudnn.h'.format(cudadir))
            runprocess('sudo rm -rf {}/lib64/*libcudnn*'.format(cudadir))
            runprocess(
                'sudo cp -P packages/cudnn/include/cudnn.h {}/include'.format(cudadir))
            runprocess(
                'sudo cp -P packages/cudnn/lib64/libcudnn* {}/lib64'.format(cudadir))
            runprocess(
                'sudo chmod a+r {}/include/cudnn.h {}/lib64/libcudnn*'.format(cudadir, cudadir))
            runprocess('rm -rf packages/cudnn')
            runprocess('sudo ldconfig')
            print("Sucessfully switched to version {}".format(version))
        else:
            print(
                "Please download cudnn first here\nhttps://developer.nvidia.com/rdp/cudnn-download")
    else:
        print("Can not found suitable packages.\nCheck available cudnn package -> https://developer.nvidia.com/rdp/cudnn-download")

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-v', '--version',
                        help='select cudnn version ( 4.0, 5.1, 6.0', type=str, required=True)
    parser.add_argument('-d', '--cudadir',
                        help='set cuda dir path', required=True)
    parser.add_argument('-c', '--cudaver',
                        help='set cuda version of cudnn', type=str, required=True)

    args = parser.parse_args()
    switchCudnn(args.version, args.cudadir, args.cudaver)

if __name__ == '__main__':
    main()