<commit_before>//==========================================================================
// Name:            fdmdv2_plot_waterfall.cpp
// Purpose:         Implements a waterfall plot derivative of fdmdv2_plot.
// Created:         June 22, 2012
// Initial author:  David Witten
// Derived from:    code written by David Rowe
// License:
//
//  Copyright (C) 2012 David Witten
//
//  All rights reserved.
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License version 2.1,
//  as published by the Free Software Foundation.  This program is
//  distributed in the hope that it will be useful, but WITHOUT ANY
//  WARRANTY; without even the implied warranty of MERCHANTABILITY or
//  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
//  License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program; if not, see <http://www.gnu.org/licenses/>.
//
//==========================================================================
#include <string.h>
#include "wx/wx.h"
#include "fdmdv2_main.h"
#include "fdmdv2_plot_waterfall.h"

/*

  Notes:

  The height h() pixels represents WATERFALL_SECS_Y of data.  Every DT
  seconds we get a vector of FDMDV_NSPEC spectrum samples which we use
  to update the last row.  The height of each row is dy pixels, which
  maps to DT seconds.  We call each dy high rectangle of pixels a
  block.

*/

extern float g_avmag[];

BEGIN_EVENT_TABLE(PlotWaterfall, PlotPanel)
    EVT_PAINT           (PlotWaterfall::OnPaint)
    EVT_MOTION          (PlotWaterfall::OnMouseMove)
    EVT_LEFT_DOWN       (PlotWaterfall::OnMouseDown)
    EVT_LEFT_UP         (PlotWaterfall::OnMouseUp)
    EVT_MOUSEWHEEL      (PlotWaterfall::OnMouseWheelMoved)
    EVT_SIZE            (PlotWaterfall::OnSize)
    EVT_SHOW            (PlotWaterfall::OnShow)
//    EVT_ERASE_BACKGROUND(PlotWaterfall::OnErase)
END_EVENT_TABLE()

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
// Class WaterfallPlot
//
// @class   WaterfallPlot
// @author  David Witten
// @date    $(Date)
// @file    $(CurrentFileName).$(CurrentFileExt)
// @brief
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
PlotWaterfall::PlotWaterfall(wxFrame* parent): PlotPanel(parent)
{
    for(int i = 0; i < 255; i++)
    {
        m_heatmap_lut[i] = heatmap((float)i, 0.0, 255.0);
    }
    m_greyscale     = 0;
    m_Bufsz         = GetMaxClientSize();
    m_newdata       = false;
    m_firstPass     = true;
    m_line_color    = 0;
    SetLabelSize(10.0);
}

//----------------------------------------------------------------
// paintEvent()
//
// @class $(Name)
// @author $(User)
// @date $(Date)
// @file $(CurrentFileName).$(CurrentFileExt)
// @brief
//
// Called by the system of by wxWidgets when the panel needs
// to be redrawn. You can also trigger this call by calling
// Refresh()/Update().
//----------------------------------------------------------------
void PlotWaterfall::OnPaint(wxPaintEvent & evt)
{
    wxAutoBufferedPaintDC pdc(this);
    draw(pdc);
}

//----------------------------------------------------------------
// OnShow()
//----------------------------------------------------------------
void PlotWaterfall::OnShow(wxShowEvent& event)
{
}

//----------------------------------------------------------------
// ~PlotWaterfall()
//----------------------------------------------------------------
PlotWaterfall::~PlotWaterfall()
{
}

//----------------------------------------------------------------
// heatmap()
// map val to a rgb colour
// from http://eddiema.ca/2011/01/21/c-sharp-heatmaps/
//----------------------------------------------------------------
unsigned PlotWaterfall::heatmap(float val, float min, float max)
{
    unsigned r = 0;
    unsigned g = 0;
    unsigned b = 0;

    val = (val - min) / (max - min);
    if(val <= 0.2)
    {
        b = (unsigned)((val / 0.2) * 255);
    }
    else if(val >  0.2 &&  val <= 0.7)
    {
        b = (unsigned)((1.0 - ((val - 0.2) / 0.5)) * 255);
    }
    if(val >= 0.2 &&  val <= 0.6)
    {
        g = (unsigned)(((val - 0.2) / 0.4) * 255);
    }
    else if(val >  0.6 &&  val <= 0.9)
    {
        g = (unsigned)((1.0 - ((val - 0.6) / 0.3)) * 255);
    }
    if(val >= 0.5)
    {
        r = (unsigned)(((val - 0.5) / 0.5) * 255);
    }
    //printf("%f %x %x %x\n", val, r, g, b);
    return  (b << 16) + (g << 8) + r;
}

#define PLOT_BOTTOM     0
#define PLOT_TOP        1

//static long paint_count;

//----------------------------------------------------------------
// draw()
//----------------------------------------------------------------
void PlotWaterfall::draw(wxAutoBufferedPaintDC& pDC)
{
    wxMemoryDC m_mDC;
    m_mDC.SelectObject(*m_pBmp);
    m_rCtrl  = GetClientRect();
    m_rGrid  = m_rCtrl;

    m_rGrid = m_rGrid.Deflate(PLOT_BORDER + (XLEFT_OFFSET/2), (PLOT_BORDER + (YBOTTOM_OFFSET/2)));
    m_rGrid.Offset(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER);

    pDC.Clear();
//    m_mDC.Clear();
    m_rPlot = wxRect(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER, m_rGrid.GetWidth(), m_rGrid.GetHeight());
//    if(m_firstPass)
//    {
//        m_firstPass = false;
//        m_mDC.FloodFill(0, 0, VERY_LTGREY_COLOR);

        // Draw a filled rectangle with aborder
//        wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);
//        m_mDC.SetBrush(ltGraphBkgBrush);
//        m_mDC.SetPen(wxPen(BLACK_COLOR, 0));
//        m_mDC.DrawRectangle(m_rPlot);

//    }
    wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);
    pDC.SetBrush(ltGraphBkgBrush);
    pDC.SetPen(wxPen(BLACK_COLOR, 0));
    pDC.DrawRectangle(m_rPlot);
    drawGraticule(pDC);
    if(m_newdata)
    {
        m_newdata = false;
        plotPixelData(pDC);
//#ifdef _USE_TIMER
        int t = m_rPlot.GetTop();
        int l = m_rPlot.GetLeft();
        int h = m_rPlot.GetHeight();
        int w = m_rPlot.GetWidth();
        int t2 = t + 1;
        int w2 = w - 1;
        int ht = (h - DATA_LINE_HEIGHT);

        //drawData();     //  m_mDC, PLOT_BOTTOM);
        m_mDC.StretchBlit(l, t2, w2, ht, &m_mDC, l, t2 + DATA_LINE_HEIGHT, w2, ht - 2);
//        pDC.Blit(l, t, w, h, &m_mDC, l, t);                                                   // Scroll Up from Bottom
        pDC.StretchBlit(l, (h - t) + 4, w, (-h) + 4, &m_mDC, l, t, w, h);                       // Scroll Down from top
//#endif
        drawGraticule(pDC);
    }
    m_mDC.SetBrush(wxNullBrush);
    m_mDC.SelectObject(wxNullBitmap);
}

//-------------------------------------------------------------------------
// drawData()
//-------------------------------------------------------------------------
void PlotWaterfall::drawData()  //wxMemoryDC&  pDC)
{
    wxNativePixelData dPix = wxNativePixelData(*m_pBmp, m_rCtrl);
    m_pPix = &dPix;
    if(m_pPix == NULL)
    {
        return;
    }
    wxNativePixelData::Iterator p(*m_pPix);

    int w = m_rPlot.GetWidth();
    int h = m_rPlot.GetHeight();
    p.Offset(*m_pPix, XLEFT_OFFSET + 3, h - (DATA_LINE_HEIGHT - 2));
    for(int y = 0; y < DATA_LINE_HEIGHT; ++y)
    {
        wxNativePixelData::Iterator rowStart = p;
        for(int x = 0; x < (w - 1); ++x, ++p)
        {
//            p.Red()     = m_pTopFrame->m_rxPa->m_av_mag[x];
//            p.Green()   = m_pTopFrame->m_rxPa->m_av_mag[x];
//            p.Blue()    = m_pTopFrame->m_rxPa->m_av_mag[x];

            p.Red()     = g_avmag[x];
            p.Green()   = g_avmag[x];
            p.Blue()    = g_avmag[x];
        }
        p = rowStart;
        p.OffsetY(*m_pPix, 1);
    }
}

//-------------------------------------------------------------------------
// drawGraticule()
//-------------------------------------------------------------------------
void PlotWaterfall::drawGraticule(wxAutoBufferedPaintDC&  pDC)
{
    int p;
    char buf[15];

    wxString s;

    wxBrush ltGraphBkgBrush;
    ltGraphBkgBrush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
    ltGraphBkgBrush.SetColour(*wxBLACK);
    pDC.SetBrush(ltGraphBkgBrush);
    pDC.SetPen(wxPen(BLACK_COLOR, 1));

    // Vertical gridlines
    pDC.SetPen(m_penShortDash);
    for(p = (PLOT_BORDER + XLEFT_OFFSET + GRID_INCREMENT); p < ((m_rGrid.GetWidth() - XLEFT_OFFSET) + GRID_INCREMENT); p += GRID_INCREMENT)
    {
        pDC.DrawLine(p, (m_rGrid.GetHeight() + PLOT_BORDER), p, PLOT_BORDER);
    }
    // Horizontal gridlines
    pDC.SetPen(m_penDotDash);
    for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)
    {
        pDC.DrawLine(PLOT_BORDER + XLEFT_OFFSET, (p + PLOT_BORDER), (m_rGrid.GetWidth() + PLOT_BORDER + XLEFT_OFFSET), (p + PLOT_BORDER));
    }
    // Label the X-Axis
    pDC.SetPen(wxPen(GREY_COLOR, 1));
    for(p = GRID_INCREMENT; p < (m_rGrid.GetWidth() - YBOTTOM_OFFSET); p += GRID_INCREMENT)
    {
        sprintf(buf, "%1.1f Hz",(double)(p / 10));
        pDC.DrawText(buf, p - PLOT_BORDER + XLEFT_OFFSET, m_rGrid.GetHeight() + YBOTTOM_OFFSET/3);
    }
    // Label the Y-Axis
    for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)
    {
        sprintf(buf, "%1.0f", (double)((m_rGrid.GetHeight() - p) * -10));
        pDC.DrawText(buf, XLEFT_TEXT_OFFSET, p);
    }
}

//-------------------------------------------------------------------------
// plotPixelData()
//-------------------------------------------------------------------------
void PlotWaterfall::plotPixelData(wxAutoBufferedPaintDC&  dc)
{
    float       spec_index_per_px;
    float       intensity_per_dB;
    int         px_per_sec;
    int         index;
    int         dy;
    int         dy_blocks;
    int         bytes_in_row_of_blocks;
    int         b;
    int         px;
    int         py;
    int         intensity;
    unsigned    *last_row;
    unsigned    *pdest;
    unsigned    *psrc;

    // determine dy, the height of one "block"
    px_per_sec = (float)m_rCtrl.GetHeight() / WATERFALL_SECS_Y;
    dy = DT * px_per_sec;
    // number of dy high blocks in spectrogram
    dy_blocks = m_rCtrl.GetHeight()/ dy;
    // shift previous bit map
    bytes_in_row_of_blocks = dy * m_rCtrl.GetWidth() * sizeof(unsigned);
    for(b = 0; b < dy_blocks - 1; b++)
    {
        pdest = (unsigned int *)m_pBmp + b * m_rCtrl.GetWidth() * dy;
        psrc  = (unsigned int *)m_pBmp + (b + 1) * m_rCtrl.GetWidth() * dy;
        memcpy(pdest, psrc, bytes_in_row_of_blocks);
    }
    // create a new row of blocks at bottom
    spec_index_per_px = (float)FDMDV_NSPEC / (float) m_rCtrl.GetWidth();
    intensity_per_dB  = (float)256 /(MAX_DB - MIN_DB);
    last_row = (unsigned int *)m_pBmp + dy *(dy_blocks - 1)* m_rCtrl.GetWidth();

    wxNativePixelData data(*m_pBmp);
    if(!data)
    {
        wxMessageBox(wxT("Unable to access Bitmap Data"), wxT("Error"));
        return;
    }
    if(data.GetWidth() < 20 || data.GetHeight() < 20)
    {
        wxMessageBox(wxT("Bitmap is too small to use"), wxT("Warning"));
        return;
    }
    wxNativePixelData::Iterator p(data);
    // we draw a (10, 10)-(20, 20) rect manually using the given r, g, b
    p.Offset(data, 10, 10);
    for(px = 0; px < m_rCtrl.GetWidth(); px++)
    {
        index = px * spec_index_per_px;
        // intensity = intensity_per_dB * (m_av_mag[index] - MIN_DB);
        intensity = intensity_per_dB * (g_avmag[index] - MIN_DB);
//        intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_rxPa->m_av_mag[index] - MIN_DB);
//        intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_av_mag[index] - MIN_DB);
        if(intensity > 255)
        {
            intensity = 255;
        }
        if(intensity > 255)
        {
            intensity = 255;
        }
        if (intensity < 0)
        {
            intensity = 0;
        }
        if(m_greyscale)
        {
            for(py = 0; py < dy; py++)
            {
                last_row[px + py * m_rCtrl.GetWidth()] = intensity << 8;
            }
        }
        else
        {
            for(py = 0; py < dy; py++)
            {
                last_row[px + py * m_rCtrl.GetWidth()] = m_heatmap_lut[intensity];
            }
        }
    }
}
<commit_msg><commit_after>//==========================================================================
// Name:            fdmdv2_plot_waterfall.cpp
// Purpose:         Implements a waterfall plot derivative of fdmdv2_plot.
// Created:         June 22, 2012
// Initial author:  David Witten
// Derived from:    code written by David Rowe
// License:
//
//  Copyright (C) 2012 David Witten
//
//  All rights reserved.
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License version 2.1,
//  as published by the Free Software Foundation.  This program is
//  distributed in the hope that it will be useful, but WITHOUT ANY
//  WARRANTY; without even the implied warranty of MERCHANTABILITY or
//  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
//  License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program; if not, see <http://www.gnu.org/licenses/>.
//
//==========================================================================
#include <string.h>
#include "wx/wx.h"
#include "fdmdv2_main.h"
#include "fdmdv2_plot_waterfall.h"

/*

  Notes:

  The height h() pixels represents WATERFALL_SECS_Y of data.  Every DT
  seconds we get a vector of FDMDV_NSPEC spectrum samples which we use
  to update the last row.  The height of each row is dy pixels, which
  maps to DT seconds.  We call each dy high rectangle of pixels a
  block.

*/

extern float g_avmag[];

BEGIN_EVENT_TABLE(PlotWaterfall, PlotPanel)
    EVT_PAINT           (PlotWaterfall::OnPaint)
    EVT_MOTION          (PlotWaterfall::OnMouseMove)
    EVT_LEFT_DOWN       (PlotWaterfall::OnMouseDown)
    EVT_LEFT_UP         (PlotWaterfall::OnMouseUp)
    EVT_MOUSEWHEEL      (PlotWaterfall::OnMouseWheelMoved)
    EVT_SIZE            (PlotWaterfall::OnSize)
    EVT_SHOW            (PlotWaterfall::OnShow)
//    EVT_ERASE_BACKGROUND(PlotWaterfall::OnErase)
END_EVENT_TABLE()

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
// Class WaterfallPlot
//
// @class   WaterfallPlot
// @author  David Witten
// @date    $(Date)
// @file    $(CurrentFileName).$(CurrentFileExt)
// @brief
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
PlotWaterfall::PlotWaterfall(wxFrame* parent): PlotPanel(parent)
{
    for(int i = 0; i < 255; i++)
    {
        m_heatmap_lut[i] = heatmap((float)i, 0.0, 255.0);
    }
    m_greyscale     = 0;
    m_Bufsz         = GetMaxClientSize();
    m_newdata       = false;
    m_firstPass     = true;
    m_line_color    = 0;
    SetLabelSize(10.0);
}

//----------------------------------------------------------------
// paintEvent()
//
// @class $(Name)
// @author $(User)
// @date $(Date)
// @file $(CurrentFileName).$(CurrentFileExt)
// @brief
//
// Called by the system of by wxWidgets when the panel needs
// to be redrawn. You can also trigger this call by calling
// Refresh()/Update().
//----------------------------------------------------------------
void PlotWaterfall::OnPaint(wxPaintEvent & evt)
{
    wxAutoBufferedPaintDC pdc(this);
    draw(pdc);
}

//----------------------------------------------------------------
// OnShow()
//----------------------------------------------------------------
void PlotWaterfall::OnShow(wxShowEvent& event)
{
}

//----------------------------------------------------------------
// ~PlotWaterfall()
//----------------------------------------------------------------
PlotWaterfall::~PlotWaterfall()
{
}

//----------------------------------------------------------------
// heatmap()
// map val to a rgb colour
// from http://eddiema.ca/2011/01/21/c-sharp-heatmaps/
//----------------------------------------------------------------
unsigned PlotWaterfall::heatmap(float val, float min, float max)
{
    unsigned r = 0;
    unsigned g = 0;
    unsigned b = 0;

    val = (val - min) / (max - min);
    if(val <= 0.2)
    {
        b = (unsigned)((val / 0.2) * 255);
    }
    else if(val >  0.2 &&  val <= 0.7)
    {
        b = (unsigned)((1.0 - ((val - 0.2) / 0.5)) * 255);
    }
    if(val >= 0.2 &&  val <= 0.6)
    {
        g = (unsigned)(((val - 0.2) / 0.4) * 255);
    }
    else if(val >  0.6 &&  val <= 0.9)
    {
        g = (unsigned)((1.0 - ((val - 0.6) / 0.3)) * 255);
    }
    if(val >= 0.5)
    {
        r = (unsigned)(((val - 0.5) / 0.5) * 255);
    }
    //printf("%f %x %x %x\n", val, r, g, b);
    return  (b << 16) + (g << 8) + r;
}

#define PLOT_BOTTOM     0
#define PLOT_TOP        1

//static long paint_count;

//----------------------------------------------------------------
// draw()
//----------------------------------------------------------------
void PlotWaterfall::draw(wxAutoBufferedPaintDC& pDC)
{
    wxMemoryDC m_mDC;
    m_mDC.SelectObject(*m_pBmp);
    m_rCtrl  = GetClientRect();
    m_rGrid  = m_rCtrl;

    m_rGrid = m_rGrid.Deflate(PLOT_BORDER + (XLEFT_OFFSET/2), (PLOT_BORDER + (YBOTTOM_OFFSET/2)));
    m_rGrid.Offset(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER);

    pDC.Clear();
//    m_mDC.Clear();
    m_rPlot = wxRect(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER, m_rGrid.GetWidth(), m_rGrid.GetHeight());
//    if(m_firstPass)
//    {
//        m_firstPass = false;
//        m_mDC.FloodFill(0, 0, VERY_LTGREY_COLOR);

        // Draw a filled rectangle with aborder
//        wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);
//        m_mDC.SetBrush(ltGraphBkgBrush);
//        m_mDC.SetPen(wxPen(BLACK_COLOR, 0));
//        m_mDC.DrawRectangle(m_rPlot);

//    }
    wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);
    pDC.SetBrush(ltGraphBkgBrush);
    pDC.SetPen(wxPen(BLACK_COLOR, 0));
    pDC.DrawRectangle(m_rPlot);
    drawGraticule(pDC);
    if(m_newdata)
    {
        m_newdata = false;
        //plotPixelData(pDC);
//#ifdef _USE_TIMER
        int t = m_rPlot.GetTop();
        int l = m_rPlot.GetLeft();
        int h = m_rPlot.GetHeight();
        int w = m_rPlot.GetWidth();
        int t2 = t + 1;
        int w2 = w - 1;
        int ht = (h - DATA_LINE_HEIGHT);

        drawData();     //  m_mDC, PLOT_BOTTOM);
        m_mDC.StretchBlit(l, t2, w2, ht, &m_mDC, l, t2 + DATA_LINE_HEIGHT, w2, ht - 2);
        // pDC.Blit(l, t, w, h, &m_mDC, l, t);                                                  // Scroll Up from Bottom
        pDC.StretchBlit(l, (h - t) + 4, w, (-h) + 4, &m_mDC, l, t, w, h);                       // Scroll Down from top
//#endif
        drawGraticule(pDC);
    }
    m_mDC.SetBrush(wxNullBrush);
    m_mDC.SelectObject(wxNullBitmap);
}

//-------------------------------------------------------------------------
// drawData()
//-------------------------------------------------------------------------
void PlotWaterfall::drawData()  //wxMemoryDC&  pDC)
{
    wxNativePixelData dPix = wxNativePixelData(*m_pBmp, m_rCtrl);
    m_pPix = &dPix;
    if(m_pPix == NULL)
    {
        return;
    }
    wxNativePixelData::Iterator p(*m_pPix);

    int w = m_rPlot.GetWidth();
    int h = m_rPlot.GetHeight();
    p.Offset(*m_pPix, XLEFT_OFFSET + 3, h - (DATA_LINE_HEIGHT - 2));
    for(int y = 0; y < DATA_LINE_HEIGHT; ++y)
    {
        wxNativePixelData::Iterator rowStart = p;
        for(int x = 0; x < (w - 1); ++x, ++p)
        {
//            p.Red()     = m_pTopFrame->m_rxPa->m_av_mag[x];
//            p.Green()   = m_pTopFrame->m_rxPa->m_av_mag[x];
//            p.Blue()    = m_pTopFrame->m_rxPa->m_av_mag[x];

            p.Red()     = g_avmag[x];
            p.Green()   = g_avmag[x];
            p.Blue()    = g_avmag[x];
        }
        p = rowStart;
        p.OffsetY(*m_pPix, 1);
    }
}

//-------------------------------------------------------------------------
// drawGraticule()
//-------------------------------------------------------------------------
void PlotWaterfall::drawGraticule(wxAutoBufferedPaintDC&  pDC)
{
    int p;
    char buf[15];

    wxString s;

    wxBrush ltGraphBkgBrush;
    ltGraphBkgBrush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
    ltGraphBkgBrush.SetColour(*wxBLACK);
    pDC.SetBrush(ltGraphBkgBrush);
    pDC.SetPen(wxPen(BLACK_COLOR, 1));

    // Vertical gridlines
    pDC.SetPen(m_penShortDash);
    for(p = (PLOT_BORDER + XLEFT_OFFSET + GRID_INCREMENT); p < ((m_rGrid.GetWidth() - XLEFT_OFFSET) + GRID_INCREMENT); p += GRID_INCREMENT)
    {
        pDC.DrawLine(p, (m_rGrid.GetHeight() + PLOT_BORDER), p, PLOT_BORDER);
    }
    // Horizontal gridlines
    pDC.SetPen(m_penDotDash);
    for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)
    {
        pDC.DrawLine(PLOT_BORDER + XLEFT_OFFSET, (p + PLOT_BORDER), (m_rGrid.GetWidth() + PLOT_BORDER + XLEFT_OFFSET), (p + PLOT_BORDER));
    }
    // Label the X-Axis
    pDC.SetPen(wxPen(GREY_COLOR, 1));
    for(p = GRID_INCREMENT; p < (m_rGrid.GetWidth() - YBOTTOM_OFFSET); p += GRID_INCREMENT)
    {
        sprintf(buf, "%1.1f Hz",(double)(p / 10));
        pDC.DrawText(buf, p - PLOT_BORDER + XLEFT_OFFSET, m_rGrid.GetHeight() + YBOTTOM_OFFSET/3);
    }
    // Label the Y-Axis
    for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)
    {
        sprintf(buf, "%1.0f", (double)((m_rGrid.GetHeight() - p) * -10));
        pDC.DrawText(buf, XLEFT_TEXT_OFFSET, p);
    }
}

//-------------------------------------------------------------------------
// plotPixelData()
//-------------------------------------------------------------------------
void PlotWaterfall::plotPixelData(wxAutoBufferedPaintDC&  dc)
{
    float       spec_index_per_px;
    float       intensity_per_dB;
    int         px_per_sec;
    int         index;
    int         dy;
    int         dy_blocks;
    int         bytes_in_row_of_blocks;
    int         b;
    int         px;
    int         py;
    int         intensity;
    unsigned    *last_row;
    unsigned    *pdest;
    unsigned    *psrc;

    // determine dy, the height of one "block"
    px_per_sec = (float)m_rCtrl.GetHeight() / WATERFALL_SECS_Y;
    dy = DT * px_per_sec;
    // number of dy high blocks in spectrogram
    dy_blocks = m_rCtrl.GetHeight()/ dy;
    // shift previous bit map
    bytes_in_row_of_blocks = dy * m_rCtrl.GetWidth() * sizeof(unsigned);
    for(b = 0; b < dy_blocks - 1; b++)
    {
        pdest = (unsigned int *)m_pBmp + b * m_rCtrl.GetWidth() * dy;
        psrc  = (unsigned int *)m_pBmp + (b + 1) * m_rCtrl.GetWidth() * dy;
        memcpy(pdest, psrc, bytes_in_row_of_blocks);
    }
    // create a new row of blocks at bottom
    spec_index_per_px = (float)FDMDV_NSPEC / (float) m_rCtrl.GetWidth();
    intensity_per_dB  = (float)256 /(MAX_DB - MIN_DB);
    last_row = (unsigned int *)m_pBmp + dy *(dy_blocks - 1)* m_rCtrl.GetWidth();

    wxNativePixelData data(*m_pBmp);
    if(!data)
    {
        wxMessageBox(wxT("Unable to access Bitmap Data"), wxT("Error"));
        return;
    }
    if(data.GetWidth() < 20 || data.GetHeight() < 20)
    {
        wxMessageBox(wxT("Bitmap is too small to use"), wxT("Warning"));
        return;
    }
    wxNativePixelData::Iterator p(data);
    // we draw a (10, 10)-(20, 20) rect manually using the given r, g, b
    p.Offset(data, 10, 10);
    for(px = 0; px < m_rCtrl.GetWidth(); px++)
    {
        index = px * spec_index_per_px;
        // intensity = intensity_per_dB * (m_av_mag[index] - MIN_DB);
        intensity = intensity_per_dB * (g_avmag[index] - MIN_DB);
//        intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_rxPa->m_av_mag[index] - MIN_DB);
//        intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_av_mag[index] - MIN_DB);
        if(intensity > 255)
        {
            intensity = 255;
        }
        if(intensity > 255)
        {
            intensity = 255;
        }
        if (intensity < 0)
        {
            intensity = 0;
        }
        if(m_greyscale)
        {
            for(py = 0; py < dy; py++)
            {
                last_row[px + py * m_rCtrl.GetWidth()] = intensity << 8;
            }
        }
        else
        {
            for(py = 0; py < dy; py++)
            {
                last_row[px + py * m_rCtrl.GetWidth()] = m_heatmap_lut[intensity];
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <test/util/setup_common.h>
#include <util/strencodings.h>

#include <boost/test/unit_test.hpp>
#include <string>

using namespace std::literals;

BOOST_FIXTURE_TEST_SUITE(base32_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(base32_testvectors)
{
    static const std::string vstrIn[]  = {"","f","fo","foo","foob","fooba","foobar"};
    static const std::string vstrOut[] = {"","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"};
    static const std::string vstrOutNoPadding[] = {"","my","mzxq","mzxw6","mzxw6yq","mzxw6ytb","mzxw6ytboi"};
    for (unsigned int i=0; i<std::size(vstrIn); i++)
    {
        std::string strEnc = EncodeBase32(vstrIn[i]);
        BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);
        strEnc = EncodeBase32(vstrIn[i], false);
        BOOST_CHECK_EQUAL(strEnc, vstrOutNoPadding[i]);
        std::string strDec = DecodeBase32(vstrOut[i]);
        BOOST_CHECK_EQUAL(strDec, vstrIn[i]);
    }

    // Decoding strings with embedded NUL characters should fail
    bool failure;
    (void)DecodeBase32("invalid\0"s, &failure); // correct size, invalid due to \0
    BOOST_CHECK(failure);
    (void)DecodeBase32("AWSX3VPP"s, &failure); // valid
    BOOST_CHECK(!failure);
    (void)DecodeBase32("AWSX3VPP\0invalid"s, &failure); // correct size, invalid due to \0
    BOOST_CHECK(failure);
    (void)DecodeBase32("AWSX3VPPinvalid"s, &failure); // invalid size
    BOOST_CHECK(failure);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test: remove BasicTestingSetup from base32 unit tests<commit_after>// Copyright (c) 2012-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util/strencodings.h>

#include <boost/test/unit_test.hpp>
#include <string>

using namespace std::literals;

BOOST_AUTO_TEST_SUITE(base32_tests)

BOOST_AUTO_TEST_CASE(base32_testvectors)
{
    static const std::string vstrIn[]  = {"","f","fo","foo","foob","fooba","foobar"};
    static const std::string vstrOut[] = {"","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"};
    static const std::string vstrOutNoPadding[] = {"","my","mzxq","mzxw6","mzxw6yq","mzxw6ytb","mzxw6ytboi"};
    for (unsigned int i=0; i<std::size(vstrIn); i++)
    {
        std::string strEnc = EncodeBase32(vstrIn[i]);
        BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);
        strEnc = EncodeBase32(vstrIn[i], false);
        BOOST_CHECK_EQUAL(strEnc, vstrOutNoPadding[i]);
        std::string strDec = DecodeBase32(vstrOut[i]);
        BOOST_CHECK_EQUAL(strDec, vstrIn[i]);
    }

    // Decoding strings with embedded NUL characters should fail
    bool failure;
    (void)DecodeBase32("invalid\0"s, &failure); // correct size, invalid due to \0
    BOOST_CHECK(failure);
    (void)DecodeBase32("AWSX3VPP"s, &failure); // valid
    BOOST_CHECK(!failure);
    (void)DecodeBase32("AWSX3VPP\0invalid"s, &failure); // correct size, invalid due to \0
    BOOST_CHECK(failure);
    (void)DecodeBase32("AWSX3VPPinvalid"s, &failure); // invalid size
    BOOST_CHECK(failure);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before><commit_msg>testing the interval munching functions too<commit_after><|endoftext|>


<commit_before>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>

#include <gtest/gtest.h>

#include <spii/solver.h>

// "An analysis of the behavior of a glass of genetic adaptive systems."
// K.A. De Jong.  Ph.D. thesis, University of Michigan, 1975.
struct GeneralizedRosenbrockTerm
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		R d0 =  (*x1) * (*x1) - (*x2);
		R d1 =  1 - (*x1);
		return 100 * d0*d0 + d1*d1;
	}
};

// An easier variant.
struct EasyRosenbrockTerm
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		R d0 =  (*x1) * (*x1) - (*x2);
		R d1 =  1 - (*x1);
		return d0*d0 + d1*d1;
	}
};

template<typename Functor, size_t n>
void test_rosenbrock()
{
	Function f;
	std::vector<double> x(n);
	for (size_t i = 0; i < n; ++i) {
		f.add_variable(&x[i], 1);
	}

	// Initial values.
	for (size_t i = 0; i < n; ++i) {
		if (i % 2 == 0) {
			x[i] = -1.2;
		}
		else {
			x[i] = 1.0;
		}
	}

	// Add all diagonal terms.
	for (size_t i = 0; i < n - 1; ++i) {
		f.add_term(new AutoDiffTerm<Functor, 1, 1>
		               (new Functor()), &x[i], &x[i+1]);
	}

	Solver solver;
	solver.maximum_iterations = 10000;
	SolverResults results;
	solver.Solve(f, &results);
	std::cerr << results;

	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);

	EXPECT_LT( std::abs(f.evaluate()), 1e-9);

	for (size_t i = 0; i < n - 1; ++i) {
		ASSERT_LT( std::abs(x[i] - 1.0), 1e-9);
	}
}

TEST(Solver, EasyRosenbrock1000)
{
	test_rosenbrock<EasyRosenbrockTerm, 1000>();
}

TEST(Solver, EasyRosenbrock10000)
{
	test_rosenbrock<EasyRosenbrockTerm, 10000>();
}

struct LennardJones
{
	template<typename R>
	R operator()(const R* const p1, const R* const p2)
	{
		R dx = p1[0] - p2[0];
		R dy = p1[1] - p2[1];
		R dz = p1[2] - p2[2];
		R r2 = dx*dx + dy*dy + dz*dz;
		R r6  = r2*r2*r2;
		R r12 = r6*r6;
		return 1.0 / r12 - 1.0 / r6;
	}
};

TEST(Solver, LennardJones)
{
	std::mt19937 prng(0);
	std::normal_distribution<double> normal;
	std::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);

	int n = 5;

	Function potential;

	std::vector<Eigen::Vector3d> points(n*n*n);
	for (int x = 0; x < n; ++x) {
		for (int y = 0; y < n; ++y) {
			for (int z = 0; z < n; ++z) {
				points[x + y*n + z*n*n][0] = x + 0.05 * randn();
				points[x + y*n + z*n*n][1] = y + 0.05 * randn();
				points[x + y*n + z*n*n][2] = z + 0.05 * randn();

				potential.add_variable(&points[x + y*n + z*n*n][0], 3);
			}
		}
	}

	// Add all pairwise terms
	for (int i = 0; i < n*n*n; ++i) {
		for (int j = i + 1; j < n*n*n; ++j) {
			potential.add_term(
				new AutoDiffTerm<LennardJones, 3, 3>(
					new LennardJones),
					&points[i][0],
					&points[j][0]);
		}
	}

	Solver solver;
	solver.maximum_iterations = 100;
	// All points interact with all points, so the Hessian
	// will be dense.
	solver.sparsity_mode = Solver::DENSE;
	SolverResults results;
	solver.Solve(potential, &results);
	std::cerr << results;

	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}

struct Trid1
{
	template<typename R>
	R operator()(const R* const x)
	{
		R d = *x - 1.0;
		return d*d;
	}
};

struct Trid2
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		return - (*x1) * (*x2);
	}
};

template<size_t n>
void test_trid()
{
	std::mt19937 prng(0);
	std::normal_distribution<double> normal;
	std::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);

	Function f;

	std::vector<double> x(n, 1.0);
	for (size_t i = 0; i < n; ++i) {
		f.add_variable(&x[i], 1);
	}

	for (size_t i = 0; i < n; ++i) {
		f.add_term( new AutoDiffTerm<Trid1, 1>(
			new Trid1),
			&x[i]);
	}

	for (size_t i = 1; i < n; ++i) {
		f.add_term( new AutoDiffTerm<Trid2, 1, 1>(
			new Trid2),
			&x[i],
			&x[i-1]);
	}

	Solver solver;
	solver.maximum_iterations = 100;
	//solver.argument_improvement_tolerance = 1e-16;
	//solver.gradient_tolerance = 1e-16;
	SolverResults results;
	solver.Solve(f, &results);
	std::cerr << results;

	double fval = f.evaluate();
	EXPECT_LT(std::abs(fval + n * (n+4) * (n-1) / 6.0) / std::abs(fval), 1e-9);
	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}

TEST(Solver, Trid10)
{
	test_trid<10>();
}

TEST(Solver, Trid1000)
{
	test_trid<1000>();
}

TEST(Solver, Trid10000)
{
	test_trid<10000>();
}

TEST(Solver, Trid100000)
{
	test_trid<100000>();
}<commit_msg>More tests in large test suite<commit_after>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>

#include <gtest/gtest.h>

#include <spii/auto_diff_term.h>
#include <spii/solver.h>

// "An analysis of the behavior of a glass of genetic adaptive systems."
// K.A. De Jong.  Ph.D. thesis, University of Michigan, 1975.
struct GeneralizedRosenbrockTerm
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		R d0 =  (*x1) * (*x1) - (*x2);
		R d1 =  1 - (*x1);
		return 100 * d0*d0 + d1*d1;
	}
};

// An easier variant.
struct EasyRosenbrockTerm
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		R d0 =  (*x1) * (*x1) - (*x2);
		R d1 =  1 - (*x1);
		return d0*d0 + d1*d1;
	}
};

template<typename Functor, size_t n>
void test_rosenbrock()
{
	Function f;
	std::vector<double> x(n);
	for (size_t i = 0; i < n; ++i) {
		f.add_variable(&x[i], 1);
	}

	// Initial values.
	for (size_t i = 0; i < n; ++i) {
		if (i % 2 == 0) {
			x[i] = -1.2;
		}
		else {
			x[i] = 1.0;
		}
	}

	// Add all diagonal terms.
	for (size_t i = 0; i < n - 1; ++i) {
		f.add_term(new AutoDiffTerm<Functor, 1, 1>
		               (new Functor()), &x[i], &x[i+1]);
	}

	Solver solver;
	solver.maximum_iterations = 10000;
	SolverResults results;
	solver.Solve(f, &results);
	std::cerr << results;

	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);

	EXPECT_LT( std::abs(f.evaluate()), 1e-9);

	for (size_t i = 0; i < n - 1; ++i) {
		ASSERT_LT( std::abs(x[i] - 1.0), 1e-9);
	}
}

TEST(Solver, EasyRosenbrock1000)
{
	test_rosenbrock<EasyRosenbrockTerm, 1000>();
}

TEST(Solver, EasyRosenbrock10000)
{
	test_rosenbrock<EasyRosenbrockTerm, 10000>();
}

struct LennardJones
{
	template<typename R>
	R operator()(const R* const p1, const R* const p2)
	{
		R dx = p1[0] - p2[0];
		R dy = p1[1] - p2[1];
		R dz = p1[2] - p2[2];
		R r2 = dx*dx + dy*dy + dz*dz;
		R r6  = r2*r2*r2;
		R r12 = r6*r6;
		return 1.0 / r12 - 1.0 / r6;
	}
};

TEST(Solver, LennardJones)
{
	std::mt19937 prng(0);
	std::normal_distribution<double> normal;
	std::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);

	int n = 5;

	Function potential;

	std::vector<Eigen::Vector3d> points(n*n*n);
	for (int x = 0; x < n; ++x) {
		for (int y = 0; y < n; ++y) {
			for (int z = 0; z < n; ++z) {
				points[x + y*n + z*n*n][0] = x + 0.05 * randn();
				points[x + y*n + z*n*n][1] = y + 0.05 * randn();
				points[x + y*n + z*n*n][2] = z + 0.05 * randn();

				potential.add_variable(&points[x + y*n + z*n*n][0], 3);
			}
		}
	}

	// Add all pairwise terms
	for (int i = 0; i < n*n*n; ++i) {
		for (int j = i + 1; j < n*n*n; ++j) {
			potential.add_term(
				new AutoDiffTerm<LennardJones, 3, 3>(
					new LennardJones),
					&points[i][0],
					&points[j][0]);
		}
	}

	Solver solver;
	solver.maximum_iterations = 100;
	// All points interact with all points, so the Hessian
	// will be dense.
	solver.sparsity_mode = Solver::DENSE;
	SolverResults results;
	solver.Solve(potential, &results);
	std::cerr << results;

	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}

struct Trid1
{
	template<typename R>
	R operator()(const R* const x)
	{
		R d = *x - 1.0;
		return d*d;
	}
};

struct Trid2
{
	template<typename R>
	R operator()(const R* const x1, const R* const x2)
	{
		return - (*x1) * (*x2);
	}
};

template<size_t n>
void test_trid()
{
	Function f;

	std::vector<double> x(n, 1.0);
	for (size_t i = 0; i < n; ++i) {
		f.add_variable(&x[i], 1);
	}

	for (size_t i = 0; i < n; ++i) {
		f.add_term( new AutoDiffTerm<Trid1, 1>(
			new Trid1),
			&x[i]);
	}

	for (size_t i = 1; i < n; ++i) {
		f.add_term( new AutoDiffTerm<Trid2, 1, 1>(
			new Trid2),
			&x[i],
			&x[i-1]);
	}

	Solver solver;
	solver.maximum_iterations = 100;
	//solver.argument_improvement_tolerance = 1e-16;
	//solver.gradient_tolerance = 1e-16;
	SolverResults results;
	solver.Solve(f, &results);
	std::cerr << results;

	double fval = f.evaluate();
	// Global optimum is
	//
	//   x[i] = (i + 1) * (n - i)
	//
	// Therefore, it is hard to calulate the optimal function
	// value for large n.
	//
	double tol  = 1e-9;
	if (n >= 10000) {
		tol = 1e-6;
	}
	if (n >= 100000) {
		tol = 1e-4;
	}
	EXPECT_LT(std::abs(fval + n * (n+4) * (n-1) / 6.0) / std::abs(fval), tol);
	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);

	if (n <= 10) {
		for (size_t i = 0; i < n; ++i) {
			std::cerr << "x[" << i << "] = " << x[i] << '\n';
		}
	}
}

TEST(Solver, Trid10)
{
	test_trid<10>();
}

TEST(Solver, Trid1000)
{
	test_trid<1000>();
}

TEST(Solver, Trid10000)
{
	test_trid<10000>();
}

struct LogBarrier01
{
	template<typename R>
	R operator()(const R* const x)
	{
		return -log(x[0]) - log(1.0 - x[0]);
	}
};

struct QuadraticFunction1
{
	QuadraticFunction1(double b)
	{
		this->b = b;
	}

	template<typename R>
	R operator()(const R* const x)
	{
		R d = x[0] - b;
		return d * d;
	}

	double b;
};

TEST(Solver, Barrier)
{
	std::mt19937 prng(0);
	std::normal_distribution<double> normal;
	std::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);

	const int n = 10000;
	Function f;

	std::vector<double> x(n, 0.5);
	for (size_t i = 0; i < n; ++i) {
		f.add_variable(&x[i], 1);
		f.add_term( new AutoDiffTerm<QuadraticFunction1, 1>(
			new QuadraticFunction1(0.5 + randn())),
			&x[i]);
		f.add_term( new AutoDiffTerm<LogBarrier01, 1>(
			new LogBarrier01),
			&x[i]);
	}

	Solver solver;
	solver.maximum_iterations = 100;
	SolverResults results;
	solver.Solve(f, &results);
	std::cerr << results;

	std::cerr << results;
	std::cerr << "-----------------------------------\n";
	std::cerr << "Function evaluate time                : " << f.evaluate_time << '\n';
	std::cerr << "Function evaluate time (with hessian) : " << f.evaluate_with_hessian_time << '\n';
	std::cerr << "Function write hessian time           : " << f.write_gradient_hessian_time << '\n';
	std::cerr << "Function copy data time               : " << f.copy_time << '\n';

	EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
	            results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
	            results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>

#include <list>
#include <string>

#include <process/gmock.hpp>
#include <process/gtest.hpp>

#include <stout/check.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>

#ifdef __linux__
#include "linux/cgroups.hpp"
#endif

#include "logging/logging.hpp"

#include "tests/environment.hpp"
#include "tests/flags.hpp"

using std::list;
using std::string;

namespace mesos {
namespace internal {
namespace tests {

// Storage for the global environment instance.
Environment* environment;

// Returns true if we should enable the provided test. Similar to how
// tests can be disabled using the 'DISABLED_' prefix on a test case
// name or test name, we use:
//
//   'ROOT_' : Disable test if current user isn't root.
//   'CGROUPS_' : Disable test if cgroups support isn't present.
//   'NOHIERARCHY_' : Disable test if there is already a cgroups
//       hierarchy mounted.
//
// These flags can be composed in any order, but must come after
// 'DISABLED_'. In addition, we disable tests that attempt to use the
// CgroupsIsolator type parameter if the current user is not root or
// cgroups is not supported.
// TODO(benh): Provide a generic way to enable/disable tests by
// registering "filter" functions.
static bool enable(const ::testing::TestInfo& test)
{
  // First check the test case name and test name.
  list<string> names;
  names.push_back(test.test_case_name());
  names.push_back(test.name());

  foreach (const string& name, names) {
    if (strings::contains(name, "ROOT_") && os::user() != "root") {
      return false;
    }

    if (strings::contains(name, "CGROUPS_") && !os::exists("/proc/cgroups")) {
      return false;
    }

#ifdef __linux__
    if (strings::contains(name, "NOHIERARCHY_")) {
      Try<std::set<std::string> > hierarchies = cgroups::hierarchies();
      CHECK_SOME(hierarchies);
      if (!hierarchies.get().empty()) {
        std::cerr
          << "-------------------------------------------------------------\n"
          << "We cannot run any cgroups tests that require mounting\n"
          << "hierarchies because you have the following hierarchies mounted:\n"
          << strings::trim(stringify(hierarchies.get()), " {},") << "\n"
          << "We'll disable the CgroupsNoHierarchyTest test fixture for now.\n"
          << "-------------------------------------------------------------"
          << std::endl;

        return false;
      }
    }
#endif
  }

  // Now check the type parameter.
  if (test.type_param() != NULL) {
    const string& type = test.type_param();
    if (strings::contains(type, "CgroupsIsolator") &&
        (os::user() != "root" || !os::exists("/proc/cgroups"))) {
      return false;
    }
#ifdef __APPLE__
    if (strings::contains(test.test_case_name(), "IsolatorTest") &&
        strings::contains(test.name(), "Usage") &&
        strings::contains(type, "ProcessIsolator") &&
        os::user() != "root") {
      // We can't run the Isolator resource usage test when we're not
      // the root user on OSX because proc_pidinfo() only returns
      // memory and CPU usage reliably when running as root.
      return false;
    }
#endif
  }

  return true;
}

// We use the constructor to setup specific tests by updating the
// gtest filter. We do this so that we can selectively run tests that
// require root or specific OS support (e.g., cgroups). Note that this
// should not effect any other filters that have been put in place
// either on the command line or via an environment variable.
// N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.
Environment::Environment()
{
  // First we split the current filter into enabled and disabled tests
  // (which are separated by a '-').
  const string& filter = ::testing::GTEST_FLAG(filter);

  // An empty filter indicates no tests should be run.
  if (filter.empty()) {
    return;
  }

  string enabled;
  string disabled;

  size_t dash = filter.find('-');
  if (dash != string::npos) {
    enabled = filter.substr(0, dash);
    disabled = filter.substr(dash + 1);
  } else {
    enabled = filter;
  }

  // Use universal filter if not specified.
  if (enabled.empty()) {
    enabled = "*";
  }

  // Ensure disabled tests end with ":" separator before we add more.
  if (!disabled.empty() && !strings::endsWith(disabled, ":")) {
    disabled += ":";
  }

  // Construct the filter string to handle system or platform specific tests.
  ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();
  for (int i = 0; i < unitTest->total_test_case_count(); i++) {
    const ::testing::TestCase* testCase = unitTest->GetTestCase(i);
    for (int j = 0; j < testCase->total_test_count(); j++) {
      const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);

      if (!enable(*testCase->GetTestInfo(j))) {
        // Append 'TestCase.TestName:'.
        disabled.append(testInfo->test_case_name());
        disabled.append(".");
        disabled.append(testInfo->name());
        disabled.append(":");
      }
    }
  }

  // Now update the gtest flag.
  ::testing::GTEST_FLAG(filter) = enabled + "-" + disabled;

  // Add our test event listeners.
  ::testing::TestEventListeners& listeners =
    ::testing::UnitTest::GetInstance()->listeners();

  listeners.Append(process::FilterTestEventListener::instance());
  listeners.Append(process::ClockTestEventListener::instance());
}

Environment::~Environment()
{
  foreach (const string& directory, directories) {
    Try<Nothing> rmdir = os::rmdir(directory);
    if (rmdir.isError()) {
      LOG(ERROR) << "Failed to remove '" << directory
                 << "': " << rmdir.error();
    }
  }
}

void Environment::SetUp()
{
  // Clear any MESOS_ environment variables so they don't affect our tests.
  char** environ = os::environ();
  for (int i = 0; environ[i] != NULL; i++) {
    std::string variable = environ[i];
    if (variable.find("MESOS_") == 0) {
      string key;
      size_t eq = variable.find_first_of("=");
      if (eq == string::npos) {
        continue; // Not expecting a missing '=', but ignore anyway.
      }
      os::unsetenv(variable.substr(strlen("MESOS_"), eq - strlen("MESOS_")));
    }
  }

  if (!GTEST_IS_THREADSAFE) {
    EXIT(1) << "Testing environment is not thread safe, bailing!";
  }
}

Try<string> Environment::mkdtemp()
{
  const ::testing::TestInfo* const testInfo =
    ::testing::UnitTest::GetInstance()->current_test_info();

  if (testInfo == NULL) {
    return Error("Failed to determine the current test information");
  }

  // We replace any slashes present in the test names (e.g. TYPED_TEST),
  // to make sure the temporary directory resides under '/tmp/'.
  const string& testCase =
    strings::replace(testInfo->test_case_name(), "/", "_");

  string testName = strings::replace(testInfo->name(), "/", "_");

  // Adjust the test name to remove any 'DISABLED_' prefix (to make
  // things easier to read). While this might seem alarming, if we are
  // "running" a disabled test it must be the case that the test was
  // explicitly enabled (e.g., via 'gtest_filter').
  if (strings::startsWith(testName, "DISABLED_")) {
    testName = strings::remove(testName, "DISABLED_", strings::PREFIX);
  }

  const string& path =
    path::join("/tmp", strings::join("_", testCase, testName, "XXXXXX"));

  return os::mkdtemp(path);
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {

<commit_msg>Set MESOS_NATIVE_LIBRARY in the testing environment.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>

#include <list>
#include <string>

#include <process/gmock.hpp>
#include <process/gtest.hpp>

#include <stout/check.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>

#ifdef __linux__
#include "linux/cgroups.hpp"
#endif

#include "logging/logging.hpp"

#include "tests/environment.hpp"
#include "tests/flags.hpp"

using std::list;
using std::string;

namespace mesos {
namespace internal {
namespace tests {

// Storage for the global environment instance.
Environment* environment;

// Returns true if we should enable the provided test. Similar to how
// tests can be disabled using the 'DISABLED_' prefix on a test case
// name or test name, we use:
//
//   'ROOT_' : Disable test if current user isn't root.
//   'CGROUPS_' : Disable test if cgroups support isn't present.
//   'NOHIERARCHY_' : Disable test if there is already a cgroups
//       hierarchy mounted.
//
// These flags can be composed in any order, but must come after
// 'DISABLED_'. In addition, we disable tests that attempt to use the
// CgroupsIsolator type parameter if the current user is not root or
// cgroups is not supported.
// TODO(benh): Provide a generic way to enable/disable tests by
// registering "filter" functions.
static bool enable(const ::testing::TestInfo& test)
{
  // First check the test case name and test name.
  list<string> names;
  names.push_back(test.test_case_name());
  names.push_back(test.name());

  foreach (const string& name, names) {
    if (strings::contains(name, "ROOT_") && os::user() != "root") {
      return false;
    }

    if (strings::contains(name, "CGROUPS_") && !os::exists("/proc/cgroups")) {
      return false;
    }

#ifdef __linux__
    if (strings::contains(name, "NOHIERARCHY_")) {
      Try<std::set<std::string> > hierarchies = cgroups::hierarchies();
      CHECK_SOME(hierarchies);
      if (!hierarchies.get().empty()) {
        std::cerr
          << "-------------------------------------------------------------\n"
          << "We cannot run any cgroups tests that require mounting\n"
          << "hierarchies because you have the following hierarchies mounted:\n"
          << strings::trim(stringify(hierarchies.get()), " {},") << "\n"
          << "We'll disable the CgroupsNoHierarchyTest test fixture for now.\n"
          << "-------------------------------------------------------------"
          << std::endl;

        return false;
      }
    }
#endif
  }

  // Now check the type parameter.
  if (test.type_param() != NULL) {
    const string& type = test.type_param();
    if (strings::contains(type, "CgroupsIsolator") &&
        (os::user() != "root" || !os::exists("/proc/cgroups"))) {
      return false;
    }
#ifdef __APPLE__
    if (strings::contains(test.test_case_name(), "IsolatorTest") &&
        strings::contains(test.name(), "Usage") &&
        strings::contains(type, "ProcessIsolator") &&
        os::user() != "root") {
      // We can't run the Isolator resource usage test when we're not
      // the root user on OSX because proc_pidinfo() only returns
      // memory and CPU usage reliably when running as root.
      return false;
    }
#endif
  }

  return true;
}

// We use the constructor to setup specific tests by updating the
// gtest filter. We do this so that we can selectively run tests that
// require root or specific OS support (e.g., cgroups). Note that this
// should not effect any other filters that have been put in place
// either on the command line or via an environment variable.
// N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.
Environment::Environment()
{
  // First we split the current filter into enabled and disabled tests
  // (which are separated by a '-').
  const string& filter = ::testing::GTEST_FLAG(filter);

  // An empty filter indicates no tests should be run.
  if (filter.empty()) {
    return;
  }

  string enabled;
  string disabled;

  size_t dash = filter.find('-');
  if (dash != string::npos) {
    enabled = filter.substr(0, dash);
    disabled = filter.substr(dash + 1);
  } else {
    enabled = filter;
  }

  // Use universal filter if not specified.
  if (enabled.empty()) {
    enabled = "*";
  }

  // Ensure disabled tests end with ":" separator before we add more.
  if (!disabled.empty() && !strings::endsWith(disabled, ":")) {
    disabled += ":";
  }

  // Construct the filter string to handle system or platform specific tests.
  ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();
  for (int i = 0; i < unitTest->total_test_case_count(); i++) {
    const ::testing::TestCase* testCase = unitTest->GetTestCase(i);
    for (int j = 0; j < testCase->total_test_count(); j++) {
      const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);

      if (!enable(*testCase->GetTestInfo(j))) {
        // Append 'TestCase.TestName:'.
        disabled.append(testInfo->test_case_name());
        disabled.append(".");
        disabled.append(testInfo->name());
        disabled.append(":");
      }
    }
  }

  // Now update the gtest flag.
  ::testing::GTEST_FLAG(filter) = enabled + "-" + disabled;

  // Add our test event listeners.
  ::testing::TestEventListeners& listeners =
    ::testing::UnitTest::GetInstance()->listeners();

  listeners.Append(process::FilterTestEventListener::instance());
  listeners.Append(process::ClockTestEventListener::instance());
}

Environment::~Environment()
{
  foreach (const string& directory, directories) {
    Try<Nothing> rmdir = os::rmdir(directory);
    if (rmdir.isError()) {
      LOG(ERROR) << "Failed to remove '" << directory
                 << "': " << rmdir.error();
    }
  }
}

void Environment::SetUp()
{
  // Clear any MESOS_ environment variables so they don't affect our tests.
  char** environ = os::environ();
  for (int i = 0; environ[i] != NULL; i++) {
    std::string variable = environ[i];
    if (variable.find("MESOS_") == 0) {
      string key;
      size_t eq = variable.find_first_of("=");
      if (eq == string::npos) {
        continue; // Not expecting a missing '=', but ignore anyway.
      }
      os::unsetenv(variable.substr(strlen("MESOS_"), eq - strlen("MESOS_")));
    }
  }

  // Set the path to the native library for running JVM tests.
  if (!os::hasenv("MESOS_NATIVE_LIBRARY")) {
    string path = path::join(tests::flags.build_dir, "src", ".libs");
#ifdef __APPLE__
    path = path::join(path, "libmesos-" VERSION ".dylib");
#else
    path = path::join(path, "libmesos-" VERSION ".so");
#endif
    os::setenv("MESOS_NATIVE_LIBRARY", path);
  }

  if (!GTEST_IS_THREADSAFE) {
    EXIT(1) << "Testing environment is not thread safe, bailing!";
  }
}

Try<string> Environment::mkdtemp()
{
  const ::testing::TestInfo* const testInfo =
    ::testing::UnitTest::GetInstance()->current_test_info();

  if (testInfo == NULL) {
    return Error("Failed to determine the current test information");
  }

  // We replace any slashes present in the test names (e.g. TYPED_TEST),
  // to make sure the temporary directory resides under '/tmp/'.
  const string& testCase =
    strings::replace(testInfo->test_case_name(), "/", "_");

  string testName = strings::replace(testInfo->name(), "/", "_");

  // Adjust the test name to remove any 'DISABLED_' prefix (to make
  // things easier to read). While this might seem alarming, if we are
  // "running" a disabled test it must be the case that the test was
  // explicitly enabled (e.g., via 'gtest_filter').
  if (strings::startsWith(testName, "DISABLED_")) {
    testName = strings::remove(testName, "DISABLED_", strings::PREFIX);
  }

  const string& path =
    path::join("/tmp", strings::join("_", testCase, testName, "XXXXXX"));

  return os::mkdtemp(path);
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {

<|endoftext|>


<commit_before><commit_msg>frame length time ramp up fix<commit_after><|endoftext|>


<commit_before><commit_msg>gtk: Add GtkTreeView inside GtkScrollableWindow [PERFECTIVE]<commit_after><|endoftext|>


<commit_before>#include "signalutil.h"

#include <cstring>
#include <cmath>
#include "bussignaldef.h"

namespace
{

inline bool is_fraction(double val)
{
  double integral;
  auto fractional = std::modf(val, &integral);
  return std::abs(fractional) != 0;
}

template<typename T> tin::phys_val calc_phys(T val, double factor, double offset)
{
  // Nothing to be done, raw and physical value are identical
  if (factor == 1 && offset == 0)
    return val;

  // We need a floating point value to represent the result
  if (is_fraction(factor) || is_fraction(offset))
    return static_cast<double>(val) * factor + offset;

  // Let's squeeze the result into an integer and hope it fits (sue me)
  return static_cast<std::int64_t>(val * factor + offset);
}
template tin::phys_val calc_phys(std::uint64_t, double, double);
template tin::phys_val calc_phys(std::int64_t, double, double);

}

tin::raw_val tin::build_raw_value(const std::array<std::uint8_t, 8>& buffer, std::uint32_t pos,
    std::uint32_t len, Byte_order order, Value_sign sign)
{
  std::uint64_t raw;
  std::memcpy(&raw, &buffer, sizeof(raw));

  if (order == tin::Byte_order::Moto) {
    raw = __builtin_bswap64(raw);
    pos = pswap64(pos) - len + 1;  // Set position to least significant bit
  }

  // Using unsigned since shift operations on signed values aren't well-defined
  raw <<= 64 - (pos + len);
  bool is_negative = raw & (1ull << 63);
  if (sign == tin::Value_sign::Signed && is_negative)
    raw = ~raw;  // Prepare negative values for zero-insertions due to right shift
  raw >>= 64 - len;
  if (sign == tin::Value_sign::Signed) {
    if (is_negative)
      raw = ~raw;  // Flipping back to proper value (all inserted zeros are now one)
    std::int64_t raw_signed;
    std::memcpy(&raw_signed, &raw, sizeof(raw_signed));
    return raw_signed;
  }
  return raw;
}

tin::phys_val tin::calc_phys_value(raw_val raw, double factor, double offset)
{
  if (std::holds_alternative<std::uint64_t>(raw))
    return calc_phys(std::get<std::uint64_t>(raw), factor, offset);
  return calc_phys(std::get<std::int64_t>(raw), factor, offset);
}
<commit_msg>Improve portability<commit_after>#include "signalutil.h"

#include <cstring>
#include <cmath>

#ifdef _MSC_VER
  #include <stdlib.h>
#endif

#include "bussignaldef.h"

namespace
{

inline bool is_fraction(double val)
{
  double integral;
  auto fractional = std::modf(val, &integral);
  return std::abs(fractional) != 0;
}

template<typename T> tin::phys_val calc_phys(T val, double factor, double offset)
{
  // Nothing to be done, raw and physical value are identical
  if (factor == 1 && offset == 0)
    return val;

  // We need a floating point value to represent the result
  if (is_fraction(factor) || is_fraction(offset))
    return static_cast<double>(val) * factor + offset;

  // Let's squeeze the result into an integer and hope it fits (sue me)
  return static_cast<std::int64_t>(val * factor + offset);
}
template tin::phys_val calc_phys(std::uint64_t, double, double);
template tin::phys_val calc_phys(std::int64_t, double, double);

}  // namespace

tin::raw_val tin::build_raw_value(const std::array<std::uint8_t, 8>& buffer, std::uint32_t pos,
    std::uint32_t len, Byte_order order, Value_sign sign)
{
  std::uint64_t raw;
  std::memcpy(&raw, &buffer, sizeof(raw));

  if (order == tin::Byte_order::Moto) {
#ifdef __GNUC__
    raw = __builtin_bswap64(raw);
#elif _MSC_VER
    raw = _byteswap_uint64(raw);
#else
    #error "Byte swap required"
#endif
    pos = pswap64(pos) - len + 1;  // Set position to least significant bit
  }

  // Using unsigned since shift operations on signed values aren't well-defined
  raw <<= 64 - (pos + len);
  bool is_negative = raw & (1ull << 63);
  if (sign == tin::Value_sign::Signed && is_negative)
    raw = ~raw;  // Prepare negative values for zero-insertions due to right shift
  raw >>= 64 - len;
  if (sign == tin::Value_sign::Signed) {
    if (is_negative)
      raw = ~raw;  // Flipping back to proper value (all inserted zeros are now one)
    std::int64_t raw_signed;
    std::memcpy(&raw_signed, &raw, sizeof(raw_signed));
    return raw_signed;
  }
  return raw;
}

tin::phys_val tin::calc_phys_value(raw_val raw, double factor, double offset)
{
  if (std::holds_alternative<std::uint64_t>(raw))
    return calc_phys(std::get<std::uint64_t>(raw), factor, offset);
  return calc_phys(std::get<std::int64_t>(raw), factor, offset);
}
<|endoftext|>


<commit_before>#include "InternalStructFeature.h"

using namespace std;

namespace MosesTraining
{

InternalStructFeature::InternalStructFeature()
	:m_type(0){
	//cout<<"InternalStructFeature: Construct "<<m_type<<"\n";
}

bool InternalStructFeature::equals(const PhraseAlignment& lhs, const PhraseAlignment& rhs) const{
	cout<<"InternalStructFeature: Equals\n";
	//don't know what it's used for and what we should compare
	//-> if the dense score is the same
	//-> if the sparse feature is set
	// compare phrases? with the internalStrucutre string?
	/** Return true if the two phrase pairs are equal from the point of this feature. Assume
	      that they already compare true according to PhraseAlignment.equals()
	   **/
	return true;
}

void InternalStructFeature::add(const ScoreFeatureContext& context,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	for(size_t i=0; i<context.phrasePair.size(); i++) {
		add(&context.phrasePair[i]->ghkmParse, denseValues, sparseValues);
	}

}

void InternalStructFeatureDense::add(std::string *internalStruct,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	//cout<<"Dense: "<<*internalStruct<<endl;
	size_t start=0;
	int countNP=0;
	while((start = internalStruct->find("NP", start)) != string::npos) {
		countNP++;
		start+=2; //length of "NP"
	}
	//should add e^countNP so in the decoder I get log(e^countNP)=countNP -> but is log or ln?
	//should use this but don't know what it does? -> maybeLog( (bitmap == i) ? 2.718 : 1 )
	denseValues.push_back(exp(countNP));

}

void InternalStructFeatureSparse::add(std::string *internalStruct,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	//cout<<"Sparse: "<<*internalStruct<<endl;
	if(internalStruct->find("VBZ")!=std::string::npos)
		sparseValues["NTVBZ"] = 1;
	if(internalStruct->find("VBD")!=std::string::npos)
			sparseValues["NTVBD"] = 1;
	if(internalStruct->find("VBP")!=std::string::npos)
				sparseValues["NTVBP"] = 1;
	if(internalStruct->find("PP")!=std::string::npos)
				sparseValues["NTPP"] = 1;
	if(internalStruct->find("SBAR")!=std::string::npos)
				sparseValues["NTSBAR"] = 1;

}

}
<commit_msg>comment for Equal implementation<commit_after>#include "InternalStructFeature.h"

using namespace std;

namespace MosesTraining
{

InternalStructFeature::InternalStructFeature()
	:m_type(0){
	//cout<<"InternalStructFeature: Construct "<<m_type<<"\n";
}

bool InternalStructFeature::equals(const PhraseAlignment& lhs, const PhraseAlignment& rhs) const{
	//cout<<"InternalStructFeature: Equals\n";
	//don't know what it's used for and what we should compare
	//-> if the dense score is the same
	//-> if the sparse feature is set
	// compare phrases? with the internalStrucutre string?
	/** Return true if the two phrase pairs are equal from the point of this feature. Assume
	      that they already compare true according to PhraseAlignment.equals()
	   **/

/*	if(lhs.ghkmParse==rhs.ghkmParse)
		return true;
	else
		return false;
*/
	//return true;
}

void InternalStructFeature::add(const ScoreFeatureContext& context,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	for(size_t i=0; i<context.phrasePair.size(); i++) {
		add(&context.phrasePair[i]->ghkmParse, denseValues, sparseValues);
	}

}

void InternalStructFeatureDense::add(std::string *internalStruct,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	//cout<<"Dense: "<<*internalStruct<<endl;
	size_t start=0;
	int countNP=0;
	while((start = internalStruct->find("NP", start)) != string::npos) {
		countNP++;
		start+=2; //length of "NP"
	}
	//should add e^countNP so in the decoder I get log(e^countNP)=countNP -> but is log or ln?
	//should use this but don't know what it does? -> maybeLog( (bitmap == i) ? 2.718 : 1 )
	denseValues.push_back(exp(countNP));

}

void InternalStructFeatureSparse::add(std::string *internalStruct,
	                   std::vector<float>& denseValues,
	                   std::map<std::string,float>& sparseValues) const{
	//cout<<"Sparse: "<<*internalStruct<<endl;
	if(internalStruct->find("VBZ")!=std::string::npos)
		sparseValues["NTVBZ"] = 1;
	if(internalStruct->find("VBD")!=std::string::npos)
			sparseValues["NTVBD"] = 1;
	if(internalStruct->find("VBP")!=std::string::npos)
				sparseValues["NTVBP"] = 1;
	if(internalStruct->find("PP")!=std::string::npos)
				sparseValues["NTPP"] = 1;
	if(internalStruct->find("SBAR")!=std::string::npos)
				sparseValues["NTSBAR"] = 1;

}

}
<|endoftext|>


<commit_before>#pragma once
#include "detect_type.hpp"
#include "lubee/meta/enable_if.hpp"
#include "lubee/none.hpp"
#include "argholder.hpp"
#include <utility>
#include "none.hpp"

namespace spi {
	template <class... Ts>
	auto construct(Ts&&... ts) {
		return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);
	}
	template <class P>
	using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;
	namespace opt_tmp {
		template <class T>
		struct alignas(alignof(T)) Buffer {
			uint8_t		_data[sizeof(T)];

			Buffer() = default;
			template <class T2>
			Buffer(T2&& t) {
				new(ptr()) T(std::forward<T2>(t));
			}

			T* ptr() noexcept {
				// Debug時は中身が有効かチェック
				#ifdef DEBUG
				#endif
				return reinterpret_cast<T*>(_data);
			}
			const T* ptr() const noexcept {
				// Debug時は中身が有効かチェック
				#ifdef DEBUG
				#endif
				return reinterpret_cast<const T*>(_data);
			}
			T& get() noexcept {
				return *ptr();
			}
			const T& get() const noexcept {
				return *ptr();
			}
			template <class... Ts>
			void ctor(Ts&&... ts) noexcept(noexcept(new T(std::forward<Ts>(ts)...))) {
				new(ptr()) T(std::forward<Ts>(ts)...);
			}
			void dtor() noexcept {
				ptr()->~T();
			}
			#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))
			template <class T2>
			Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {
				get() = std::forward<T2>(t);
				return *this;
			}
			#undef NOEXCEPT_WHEN_RAW
			template <class Ar, class T2>
			friend void serialize(Ar&, Buffer<T2>&);
		};
		template <class T>
		struct Buffer<T&> {
			T*	_data;

			Buffer() = default;
			Buffer(T& t) noexcept: _data(&t) {}
			T* ptr() noexcept {
				return _data;
			}
			const T* ptr() const noexcept {
				return _data;
			}
			T& get() noexcept {
				return *ptr();
			}
			const T& get() const noexcept {
				return *ptr();
			}
			void ctor() noexcept {}
			void ctor(T& t) noexcept{
				_data = &t;
			}
			void dtor() noexcept {}
			Buffer& operator = (T& t) noexcept {
				_data = &t;
				return *this;
			}
			template <class Ar, class T2>
			friend void serialize(Ar&, opt_tmp::Buffer<T2&>&);
		};
		template <class T>
		struct Buffer<T*> {
			T*	_data;

			Buffer() = default;
			Buffer(T* t) noexcept: _data(t) {}
			T* ptr() noexcept {
				return _data;
			}
			const T* ptr() const noexcept {
				return _data;
			}
			T*& get() noexcept {
				return _data;
			}
			T* const& get() const noexcept {
				return _data;
			}
			void ctor() noexcept {}
			void ctor(T* t) noexcept {
				_data = t;
			}
			void dtor() noexcept {}
			Buffer& operator = (T* t) noexcept {
				_data = t;
				return *this;
			}
			template <class Ar, class T2>
			friend void serialize(Ar&, opt_tmp::Buffer<T2*>&);
		};
	}

	template <class T>
	class Optional {
		private:
			using value_t = T;
			constexpr static bool Is_RP = IsRP<T>{};
			using Buffer = opt_tmp::Buffer<T>;
			Buffer	_buffer;
			bool	_bInit;

			void _force_release() noexcept {
				D_Assert0(_bInit);
				_buffer.dtor();
				_bInit = false;
			}
			void _release() noexcept {
				if(_bInit)
					_force_release();
			}
			constexpr bool isRvalue() && noexcept {
				return true;
			}
			constexpr bool isRvalue() const& noexcept {
				return false;
			}
			template <class T2>
			bool _construct(std::true_type, T2&& t) {
				_buffer.ctor(std::forward<T2>(t));
				return true;
			}
			template <class T2>
			bool _construct(std::false_type, T2&&) {
				_buffer.ctor();
				return false;
			}

		public:
			const static struct _AsInitialized{} AsInitialized;
			//! コンストラクタは呼ばないが初期化された物として扱う
			/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */
			Optional(_AsInitialized) noexcept:
				_bInit(true)
			{}

			Optional(const Optional& opt):
				_bInit(opt._bInit)
			{
				if(_bInit) {
					_buffer.ctor(opt._buffer.get());
				}
			}
			Optional(Optional&& opt) noexcept:
				_bInit(opt._bInit)
			{
				if(_bInit) {
					_buffer.ctor(std::move(opt).get());
					opt._bInit = false;
				}
			}
			template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>
			Optional(T2&& v) noexcept(noexcept(Buffer(std::forward<T2>(v)))):
				_buffer(std::forward<T2>(v)),
				_bInit(true)
			{}
			template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
			Optional(T2&& v) noexcept(noexcept(std::declval<Buffer>().ctor(std::forward<T2>(v).get()))):
				_bInit(v._bInit)
			{
				if(_bInit) {
					const bool bR = std::forward<T2>(v).isRvalue();
					_buffer.ctor(std::forward<T2>(v).get());
					if(bR)
						v._bInit = false;
				}
			}
			//! デフォルト初期化: 中身は無効
			Optional() noexcept:
				_bInit(false)
			{}
			//! none_tを渡して初期化するとデフォルトと同じ挙動
			Optional(none_t) noexcept:
				Optional()
			{}
			~Optional() {
				_release();
			}
			decltype(auto) get() & noexcept {
				return _buffer.get();
			}
			decltype(auto) get() const& noexcept {
				return _buffer.get();
			}
			decltype(auto) get() && noexcept {
				return std::move(_buffer.get());
			}
			decltype(auto) operator * () & noexcept {
				return get();
			}
			decltype(auto) operator * () const& noexcept {
				return get();
			}
			decltype(auto) operator * () && noexcept {
				return std::move(get());
			}
			explicit operator bool () const noexcept {
				return _bInit;
			}
			decltype(auto) operator -> () noexcept {
				return _buffer.ptr();
			}
			decltype(auto) operator -> () const noexcept {
				return _buffer.ptr();
			}
			bool operator == (const Optional& t) const noexcept {
				const bool b = _bInit;
				if(b == t._bInit) {
					if(b)
						return get() == t.get();
					return true;
				}
				return false;
			}
			bool operator != (const Optional& t) const noexcept {
				return !(this->operator == (t));
			}
			Optional& operator = (none_t) noexcept {
				_release();
				return *this;
			}
			template <
				class T2,
				ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))
			>
			Optional& operator = (T2&& t) {
				if(!_bInit) {
					_bInit = true;
					using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;
					if(_construct(CanConstruct{}, std::forward<T2>(t)))
						return *this;
				}
				_buffer = std::forward<T2>(t);
				return *this;
			}
			template <class... Ts>
			Optional& operator = (ArgHolder<Ts...>&& ah) {
				if(_bInit)
					_release();
				const auto fn = [&buff = _buffer](auto&&... ts) {
					buff.ctor(std::forward<decltype(ts)>(ts)...);
				};
				ah.inorder(fn);
				_bInit = true;
				return *this;
			}
			template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
			Optional& operator = (T2&& t) noexcept(Is_RP) {
				if(!t)
					_release();
				else {
					_bInit = true;
					_buffer = std::forward<T2>(t).get();
				}
				return *this;
			}
			template <class Ar, class T2>
			friend void load(Ar&, Optional<T2>&);
			template <class Ar, class T2>
			friend void save(Ar&, const Optional<T2>&);
	};
	template <class T>
	const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};
}
<commit_msg>Optional: noneを持っている時にassignすると内部値のコンストラクタが呼ばれない不具合を修正<commit_after>#pragma once
#include "detect_type.hpp"
#include "lubee/meta/enable_if.hpp"
#include "lubee/none.hpp"
#include "argholder.hpp"
#include <utility>
#include "none.hpp"

namespace spi {
	template <class... Ts>
	auto construct(Ts&&... ts) {
		return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);
	}
	template <class P>
	using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;
	namespace opt_tmp {
		template <class T>
		struct alignas(alignof(T)) Buffer {
			uint8_t		_data[sizeof(T)];

			Buffer() = default;
			template <class T2>
			Buffer(T2&& t) {
				new(ptr()) T(std::forward<T2>(t));
			}

			T* ptr() noexcept {
				// Debug時は中身が有効かチェック
				#ifdef DEBUG
				#endif
				return reinterpret_cast<T*>(_data);
			}
			const T* ptr() const noexcept {
				// Debug時は中身が有効かチェック
				#ifdef DEBUG
				#endif
				return reinterpret_cast<const T*>(_data);
			}
			T& get() noexcept {
				return *ptr();
			}
			const T& get() const noexcept {
				return *ptr();
			}
			template <class... Ts>
			void ctor(Ts&&... ts) noexcept(noexcept(new T(std::forward<Ts>(ts)...))) {
				new(ptr()) T(std::forward<Ts>(ts)...);
			}
			void dtor() noexcept {
				ptr()->~T();
			}
			#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))
			template <class T2>
			Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {
				get() = std::forward<T2>(t);
				return *this;
			}
			#undef NOEXCEPT_WHEN_RAW
			template <class Ar, class T2>
			friend void serialize(Ar&, Buffer<T2>&);
		};
		template <class T>
		struct Buffer<T&> {
			T*	_data;

			Buffer() = default;
			Buffer(T& t) noexcept: _data(&t) {}
			T* ptr() noexcept {
				return _data;
			}
			const T* ptr() const noexcept {
				return _data;
			}
			T& get() noexcept {
				return *ptr();
			}
			const T& get() const noexcept {
				return *ptr();
			}
			void ctor() noexcept {}
			void ctor(T& t) noexcept{
				_data = &t;
			}
			void dtor() noexcept {}
			Buffer& operator = (T& t) noexcept {
				_data = &t;
				return *this;
			}
			template <class Ar, class T2>
			friend void serialize(Ar&, opt_tmp::Buffer<T2&>&);
		};
		template <class T>
		struct Buffer<T*> {
			T*	_data;

			Buffer() = default;
			Buffer(T* t) noexcept: _data(t) {}
			T* ptr() noexcept {
				return _data;
			}
			const T* ptr() const noexcept {
				return _data;
			}
			T*& get() noexcept {
				return _data;
			}
			T* const& get() const noexcept {
				return _data;
			}
			void ctor() noexcept {}
			void ctor(T* t) noexcept {
				_data = t;
			}
			void dtor() noexcept {}
			Buffer& operator = (T* t) noexcept {
				_data = t;
				return *this;
			}
			template <class Ar, class T2>
			friend void serialize(Ar&, opt_tmp::Buffer<T2*>&);
		};
	}

	template <class T>
	class Optional {
		private:
			using value_t = T;
			constexpr static bool Is_RP = IsRP<T>{};
			using Buffer = opt_tmp::Buffer<T>;
			Buffer	_buffer;
			bool	_bInit;

			void _force_release() noexcept {
				D_Assert0(_bInit);
				_buffer.dtor();
				_bInit = false;
			}
			void _release() noexcept {
				if(_bInit)
					_force_release();
			}
			template <class T2>
			bool _construct(std::true_type, T2&& t) {
				_buffer.ctor(std::forward<T2>(t));
				return true;
			}
			template <class T2>
			bool _construct(std::false_type, T2&&) {
				_buffer.ctor();
				return false;
			}
			void _invalidate_if_rvalue() const& noexcept {}
			void _invalidate_if_rvalue() && noexcept {
				_bInit = false;
			}

		public:
			const static struct _AsInitialized{} AsInitialized;
			//! コンストラクタは呼ばないが初期化された物として扱う
			/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */
			Optional(_AsInitialized) noexcept:
				_bInit(true)
			{}

			Optional(const Optional& opt):
				_bInit(opt._bInit)
			{
				if(_bInit) {
					_buffer.ctor(opt._buffer.get());
				}
			}
			Optional(Optional&& opt) noexcept:
				_bInit(opt._bInit)
			{
				if(_bInit) {
					_buffer.ctor(std::move(opt).get());
					opt._bInit = false;
				}
			}
			template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>
			Optional(T2&& v) noexcept(noexcept(Buffer(std::forward<T2>(v)))):
				_buffer(std::forward<T2>(v)),
				_bInit(true)
			{}
			template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
			Optional(T2&& v) noexcept(noexcept(std::declval<Buffer>().ctor(std::forward<T2>(v).get()))):
				_bInit(v._bInit)
			{
				if(_bInit) {
					_buffer.ctor(std::forward<T2>(v).get());
					v._invalidate_if_rvalue();
				}
			}
			//! デフォルト初期化: 中身は無効
			Optional() noexcept:
				_bInit(false)
			{}
			//! none_tを渡して初期化するとデフォルトと同じ挙動
			Optional(none_t) noexcept:
				Optional()
			{}
			~Optional() {
				_release();
			}
			decltype(auto) get() & noexcept {
				return _buffer.get();
			}
			decltype(auto) get() const& noexcept {
				return _buffer.get();
			}
			decltype(auto) get() && noexcept {
				return std::move(_buffer.get());
			}
			decltype(auto) operator * () & noexcept {
				return get();
			}
			decltype(auto) operator * () const& noexcept {
				return get();
			}
			decltype(auto) operator * () && noexcept {
				return std::move(get());
			}
			explicit operator bool () const noexcept {
				return _bInit;
			}
			decltype(auto) operator -> () noexcept {
				return _buffer.ptr();
			}
			decltype(auto) operator -> () const noexcept {
				return _buffer.ptr();
			}
			bool operator == (const Optional& t) const noexcept {
				const bool b = _bInit;
				if(b == t._bInit) {
					if(b)
						return get() == t.get();
					return true;
				}
				return false;
			}
			bool operator != (const Optional& t) const noexcept {
				return !(this->operator == (t));
			}
			Optional& operator = (none_t) noexcept {
				_release();
				return *this;
			}
			template <
				class T2,
				ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))
			>
			Optional& operator = (T2&& t) {
				if(!_bInit) {
					_bInit = true;
					using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;
					if(_construct(CanConstruct{}, std::forward<T2>(t)))
						return *this;
				}
				_buffer = std::forward<T2>(t);
				return *this;
			}
			template <class... Ts>
			Optional& operator = (ArgHolder<Ts...>&& ah) {
				if(_bInit)
					_release();
				const auto fn = [&buff = _buffer](auto&&... ts) {
					buff.ctor(std::forward<decltype(ts)>(ts)...);
				};
				ah.inorder(fn);
				_bInit = true;
				return *this;
			}
			template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
			Optional& _assign_operator(T2&& t) noexcept(Is_RP) {
				if(!t)
					_release();
				else {
					if(!_bInit) {
						_bInit = true;
						_buffer.ctor();
					}
					_buffer = std::forward<T2>(t).get();
				}
				return *this;
			}
			template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>
			Optional& operator = (T2&& t) noexcept(Is_RP) {
				return _assign_operator(std::forward<T2>(t));
			}
			Optional& operator = (const Optional& opt) {
				return _assign_operator(opt);
			}
			Optional& operator = (Optional&& opt) noexcept {
				return _assign_operator(std::move(opt));
			}
			template <class Ar, class T2>
			friend void load(Ar&, Optional<T2>&);
			template <class Ar, class T2>
			friend void save(Ar&, const Optional<T2>&);
	};
	template <class T>
	const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};
}
<|endoftext|>


<commit_before><commit_msg>added bounding frame<commit_after><|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef NET_TCP_WRITE_BUFFER_HPP
#define NET_TCP_WRITE_BUFFER_HPP

#include "common.hpp"

namespace net {
namespace tcp {
/*
  Wrapper around a buffer that contains data to be written.
*/
struct WriteBuffer {
  buffer_t buffer;
  size_t remaining;
  size_t offset;
  size_t acknowledged;
  bool push;

  WriteBuffer(buffer_t buf, size_t length, bool PSH, size_t offs = 0)
    : buffer(buf), remaining(length-offs), offset(offs), acknowledged(0), push(PSH) {}

  size_t length() const { return remaining + offset; }

  bool done() const { return acknowledged == length(); }

  uint8_t* begin() const { return buffer.get(); }

  uint8_t* pos() const { return buffer.get() + offset; }

  uint8_t* end() const { return buffer.get() + length(); }

  bool advance(size_t length) {
    assert(length <= remaining);
    offset += length;
    remaining -= length;
    return length > 0;
  }

  size_t acknowledge(size_t bytes) {
    auto acked = std::min(bytes, length()-acknowledged);
    acknowledged += acked;
    return acked;
  }

  operator buffer_t() const noexcept
  { return buffer; }

  bool operator==(const WriteBuffer& wb) const
  { return buffer == wb.buffer && length() == wb.length(); }

}; // < struct WriteBuffer

} // < namespace net
} // < namespace tcp

#endif // < NET_TCP_WRITE_BUFFER_HPP

<commit_msg>tcp: changed assert to Expects for better testing<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef NET_TCP_WRITE_BUFFER_HPP
#define NET_TCP_WRITE_BUFFER_HPP

#include "common.hpp"
#include <common>

namespace net {
namespace tcp {
/*
  Wrapper around a buffer that contains data to be written.
*/
struct WriteBuffer {
  buffer_t buffer;
  size_t remaining;
  size_t offset;
  size_t acknowledged;
  bool push;

  WriteBuffer(buffer_t buf, size_t length, bool PSH, size_t offs = 0)
    : buffer(buf), remaining(length-offs), offset(offs), acknowledged(0), push(PSH) {}

  size_t length() const { return remaining + offset; }

  bool done() const { return acknowledged == length(); }

  uint8_t* begin() const { return buffer.get(); }

  uint8_t* pos() const { return buffer.get() + offset; }

  uint8_t* end() const { return buffer.get() + length(); }

  bool advance(size_t length) {
    Expects(length <= remaining);
    offset += length;
    remaining -= length;
    return length > 0;
  }

  size_t acknowledge(size_t bytes) {
    auto acked = std::min(bytes, length()-acknowledged);
    acknowledged += acked;
    return acked;
  }

  operator buffer_t() const noexcept
  { return buffer; }

  bool operator==(const WriteBuffer& wb) const
  { return buffer == wb.buffer && length() == wb.length(); }

}; // < struct WriteBuffer

} // < namespace net
} // < namespace tcp

#endif // < NET_TCP_WRITE_BUFFER_HPP
<|endoftext|>


<commit_before>class Solution {
    public:
        int numDistinct(string S, string T) {
            if(T.size() == 0) return 1;
            if(S.size() < T.size()) return 0;
            int count = 0;
            for(int i = 0; i != S.size(); ++i){
                if(T[0] == S[i]){
                    count += numDistinct(S.substr(i+1), T.substr(1));
                }
            }
            return count;
        }
};
<commit_msg>add a DP solution, accepted<commit_after>class Solution {
    public:
        int numDistinct(string S, string T) {
            int *matrix = new int[T.size()+1];
            memset((void*)matrix, 0, sizeof(int)*(T.size()+1));
            matrix[0] = 1;
            int count = 0;
            for(int i = 1; i != S.size()+1; ++i){
                for(int j = T.size(); j >= 1; --j){
                    if(S[i-1] == T[j-1]){
                        matrix[j] += matrix[j-1];
                    }
                }
            }
            count = matrix[T.size()];
            delete []matrix;
            return count;
        }
};
<|endoftext|>


<commit_before>/*
 *  about_dialog.cpp
 *  PHD Guiding
 *
 *  Created by Sylvain Girard.
 *  Copyright (c) 2013 Sylvain Girard.
 *  All rights reserved.
 *
 *  This source code is distributed under the following "BSD" license
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *    Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *    Neither the name of Craig Stark, Stark Labs nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>

BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
    EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()

AboutDialog::AboutDialog(void) :
wxDialog(pFrame, wxID_ANY, _T("About ") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
    #include "icons/phd.xpm"  // defines prog_icon[]

    SetBackgroundColour(*wxWHITE);

    wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
    wxBitmap bmp(prog_icon);
    wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);

    wxFileSystem::AddHandler(new wxMemoryFSHandler);
    wxMemoryFSHandler::AddFile("about.html", wxString::Format(
        ""
        "
%s %s
"
        "Open PHD Guiding
"
        "www.stark-labs.com

"
        "Credits:
"
        "    Craig Stark
"
        "    Bret McKee
"
        "    Bernhard Reutner-Fischer
"
        "    Stefan Elste
"
        "    Geoffrey Hausheer
"
        "    Jared Wellman
"
        "    John Wainwright
"
        "    Sylvain Girard
"
        "    Andy Galasso
"
        "    Bruce Waddington
"
        "
"
        "Copyright 2006-2013 Craig Stark
"
        "Copyright 2009 Geoffrey Hausheer
"
        "Copyright 2012-2013 Bret McKee
"
        "Copyright 2013 Sylvain Girard
"
        "Copyright 2013 Andy Galasso
"
        "Copyright 2013 Bruce Waddington
"
        "", APPNAME, FULLVER));
    wxHtmlWindow *pHtml;
    pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 400), wxHW_SCROLLBAR_AUTO);
    pHtml->SetBorders(0);
    pHtml->LoadPage("memory:about.html");
    pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());

    pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
    pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));

    wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
    pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
    pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));
    SetSizerAndFit(pTopLevelSizer);
}

AboutDialog::~AboutDialog(void)
{
    wxMemoryFSHandler::RemoveFile("about.html");
}

void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
    wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<commit_msg>Add Max Chen to about dialog<commit_after>/*
 *  about_dialog.cpp
 *  PHD Guiding
 *
 *  Created by Sylvain Girard.
 *  Copyright (c) 2013 Sylvain Girard.
 *  All rights reserved.
 *
 *  This source code is distributed under the following "BSD" license
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *    Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *    Neither the name of Craig Stark, Stark Labs nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>

BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
    EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()

AboutDialog::AboutDialog(void) :
wxDialog(pFrame, wxID_ANY, _T("About ") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
    #include "icons/phd.xpm"  // defines prog_icon[]

    SetBackgroundColour(*wxWHITE);

    wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
    wxBitmap bmp(prog_icon);
    wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);

    wxFileSystem::AddHandler(new wxMemoryFSHandler);
    wxMemoryFSHandler::AddFile("about.html", wxString::Format(
        ""
        "
%s %s
"
        "Open PHD Guiding
"
        "www.stark-labs.com

"
        "Credits:
"
        "    Craig Stark
"
        "    Bret McKee
"
        "    Bernhard Reutner-Fischer
"
        "    Stefan Elste
"
        "    Geoffrey Hausheer
"
        "    Jared Wellman
"
        "    John Wainwright
"
        "    Sylvain Girard
"
        "    Andy Galasso
"
        "    Bruce Waddington
"
        "    Max Chen
"
        "
"
        "Copyright 2006-2013 Craig Stark
"
        "Copyright 2009 Geoffrey Hausheer
"
        "Copyright 2012-2013 Bret McKee
"
        "Copyright 2013 Sylvain Girard
"
        "Copyright 2013 Andy Galasso
"
        "Copyright 2013 Bruce Waddington
"
        "", APPNAME, FULLVER));
    wxHtmlWindow *pHtml;
    pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 440), wxHW_SCROLLBAR_AUTO);
    pHtml->SetBorders(0);
    pHtml->LoadPage("memory:about.html");
    pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());

    pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
    pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));

    wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
    pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
    pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));
    SetSizerAndFit(pTopLevelSizer);
}

AboutDialog::~AboutDialog(void)
{
    wxMemoryFSHandler::RemoveFile("about.html");
}

void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
    wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<|endoftext|>