<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include "ns3/object.h"
#include "ns3/global-value.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include <ns3/gnuplot.h>
#include <sstream>

#include "Observador.h"

#define STARTTIME 2.0
#define STOPTIME  10000.0
#define T_STUDENT_VALUE 2.2622

typedef struct datos {
    double mediaNumIntentosTotales;
    double mediaTiempoEcoTotal;
    double mediaPorcentajeErrorClientes;
} DATOS;

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("practica05");

DATOS simulacion (uint32_t nCsma, Time retardoProp, DataRate capacidad,
        uint32_t tamPaquete, Time intervalo, uint32_t maxReintentos) {

    NodeContainer csmaNodes;
    csmaNodes.Create (nCsma);

    CsmaHelper csma;
    csma.SetChannelAttribute ("DataRate", DataRateValue (capacidad));
    csma.SetChannelAttribute ("Delay", TimeValue (retardoProp));

    NetDeviceContainer csmaDevices;
    csmaDevices = csma.Install (csmaNodes);
    // Instalamos la pila TCP/IP en todos los nodos
    InternetStackHelper stack;
    stack.Install (csmaNodes);
    // Y les asignamos direcciones
    Ipv4AddressHelper address;
    address.SetBase ("10.1.2.0", "255.255.255.0");
    Ipv4InterfaceContainer csmaInterfaces = address.Assign (csmaDevices);

    /////////// Instalación de las aplicaciones
    // Servidor
    UdpEchoServerHelper echoServer (9);
    ApplicationContainer serverApp = echoServer.Install (csmaNodes.Get (nCsma - 1));
    serverApp.Start (Seconds (STARTTIME));
    serverApp.Stop (Seconds (STOPTIME));
    // Clientes
    UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma - 1), 9);
    echoClient.SetAttribute ("MaxPackets", UintegerValue (10000));
    echoClient.SetAttribute ("Interval", TimeValue (intervalo));
    echoClient.SetAttribute ("PacketSize", UintegerValue (tamPaquete));
    NodeContainer clientes;

    for (uint32_t i = 0; i < nCsma - 1; i++)
    {
        clientes.Add (csmaNodes.Get (i));
    }
    NS_LOG_FUNCTION ("Fin bucle de creacion de observadores");

    ApplicationContainer clientApps = echoClient.Install (clientes);
    NS_LOG_FUNCTION ("Instalacion de clientes de echo realizada");
    clientApps.Start (Seconds (STARTTIME));
    clientApps.Stop (Seconds (STOPTIME));

    // Cálculo de rutas
    Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

    csma.EnablePcap ("practica05", csmaDevices.Get (nCsma - 1), true);

    Observador observadores[nCsma];
    for (uint32_t i = 0; i < nCsma; i++) {
        csmaDevices.Get(i)->TraceConnectWithoutContext ("PhyTxEnd",     MakeCallback(&Observador::PaqueteEnviado,              &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("PhyTxDrop",    MakeCallback(&Observador::PaquetePerdido,              &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacTxBackoff", MakeCallback(&Observador::PaqueteEnBackoff,            &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacTx",        MakeCallback(&Observador::PaqueteParaEnviar,           &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacRx",        MakeCallback(&Observador::PaqueteRecibidoParaEntregar, &observadores[i]));

        Ptr<CsmaNetDevice> csma_device = csmaDevices.Get(i)->GetObject<CsmaNetDevice>();
        csma_device->SetBackoffParams (Time ("1us"), 10, 1000, 10, maxReintentos);
    }

    NS_LOG_FUNCTION ("Va a comenzar la simulacion");
    Simulator::Run ();
    Simulator::Destroy ();
    NS_LOG_FUNCTION ("Finalizada simulacion");

    Average<uint32_t> numIntentosTotales;
    Average<double>   tiempoEcoTotal;
    Average<double>   porcentajeErrorClientes;
    Average<double>   porcentajeErrorEscenario;

    for (uint32_t i = 0; i < nCsma; i++) {

        double mediaNumIntentos = observadores[i].GetMediaNumIntentos();
        double mediaTiempoEco = observadores[i].GetMediaTiempoEco();
        double porcentajeError = observadores[i].GetPorcentajePaquetesPerdidos();

        if (std::isnan(mediaNumIntentos)) {
            mediaNumIntentos = 0;
        }
        if (std::isnan(mediaTiempoEco)) {
            mediaTiempoEco = 0;
        }

        NS_LOG_INFO ("Media de intentos en nodo " << i << ": " << mediaNumIntentos);
        porcentajeErrorEscenario.Update(porcentajeError);
        if (i < nCsma - 1) {
           NS_LOG_INFO ("Tiempo medio de eco en nodo " << i << ": " << Time(mediaTiempoEco));
           if (i > 1) {
               porcentajeErrorClientes.Update(porcentajeError);
               tiempoEcoTotal.Update(mediaTiempoEco);
               numIntentosTotales.Update(mediaNumIntentos);
           }
        }
        NS_LOG_INFO ("Porcentaje de paquetes perdidos en nodo " << i << ": " << porcentajeError << " %");
        NS_LOG_INFO ("");
    }

    double mediaNumIntentosTotales = numIntentosTotales.Mean();
    double mediaTiempoEcoTotal = tiempoEcoTotal.Mean();
    double mediaPorcentajeErrorClientes = porcentajeErrorClientes.Mean();
    double mediaPorcentajeErrorEscenario = porcentajeErrorEscenario.Mean();

    if (std::isnan(mediaNumIntentosTotales)) {
        mediaNumIntentosTotales = 0;
    }
    if (std::isnan(mediaTiempoEcoTotal)) {
        mediaTiempoEcoTotal = 0;
    }
    if (std::isnan(mediaPorcentajeErrorClientes)) {
        mediaPorcentajeErrorClientes = 0;
    }
    if (std::isnan(mediaPorcentajeErrorEscenario)) {
        mediaPorcentajeErrorEscenario = 0;
    }

    NS_LOG_INFO ("--------------------------------------------------------");
    NS_LOG_INFO ("Media de intentos de transmision en el escenario: " << mediaNumIntentosTotales);
    NS_LOG_INFO ("Tiempo de eco medio en el escenario: " << Time(mediaTiempoEcoTotal));
    NS_LOG_INFO ("Porcentaje de paquetes perdidos por los clientes: " << mediaPorcentajeErrorClientes << " %");
    NS_LOG_INFO ("Porcentaje de paquetes perdidos en el escenario: " << mediaPorcentajeErrorEscenario << " %");
    NS_LOG_INFO ("--------------------------------------------------------");

    DATOS datos = { mediaNumIntentosTotales, mediaTiempoEcoTotal, mediaPorcentajeErrorClientes };
    return datos;
}

int
main (int argc, char *argv[])
{
    GlobalValue::Bind("ChecksumEnabled", BooleanValue(true));
    Time::SetResolution (Time::US);

    uint32_t seed = 1;

    uint32_t dni[8] = {3,1,4,8,2,2,0,3};
    NS_LOG_INFO ("DNI: " << dni[8]<<dni[7]<<dni[6]<<dni[5]<<dni[4]<<dni[3]<<dni[2]<<dni[1]);

    //Parametros de simulacion
    uint32_t nCsma             = 10-dni[0]/2;
    Time     retardoProp       = Time ("6560ns");
    DataRate capacidad         = DataRate ("100Mbps");
    uint32_t tamPaquete        = 500+100*dni[1];
    Time     intervalo         = Time ("1s");
    uint32_t reintentosInicial = 2;
    uint32_t reintentosFinal   = 12;

    CommandLine cmd;
    cmd.AddValue ("nCsma", "Número de nodos de la red local", nCsma);
    cmd.AddValue ("retardoProp", "retardo de propagación en el bus", retardoProp);
    cmd.AddValue ("capacidad", "capacidad del bus", capacidad);
    cmd.AddValue ("tamPaquete", "tamaño de las SDU de aplicación", tamPaquete);
    cmd.AddValue ("intervalo", "tiempo entre dos paquetes consecutivos enviados por el mismo cliente", intervalo);
    cmd.AddValue ("reintentosInicial", "valor inicial de reintentos", reintentosInicial);
    cmd.AddValue ("reintentosFinal", "valor final de reintentos", reintentosFinal);
    cmd.Parse (argc,argv);

    NS_LOG_FUNCTION("nCsma" << nCsma);
    NS_LOG_FUNCTION("retardoProp" << retardoProp);
    NS_LOG_FUNCTION("capacidad" << capacidad);
    NS_LOG_FUNCTION("tamPaquete" << tamPaquete);
    NS_LOG_FUNCTION("intervalo" << intervalo);
    NS_LOG_FUNCTION("reintentosInicial" << reintentosInicial);
    NS_LOG_FUNCTION("reintentosFinal" << reintentosFinal);

    Gnuplot plot[3];
    plot[0].SetTitle ("Evolución del número medio de intentos");
    plot[0].SetLegend ("maxReint", "numIntentos");
    plot[1].SetTitle ("Evolución del tiempo medio de eco");
    plot[1].SetLegend ("maxReint", "tEco (us)");
    plot[2].SetTitle ("Evolución del porcentaje de error");
    plot[2].SetLegend ("maxReint", "perror (%)");

    Gnuplot2dDataset dataset[3];
    for (int i = 0; i < 3 ; i++) {
        dataset[i].SetStyle (Gnuplot2dDataset::LINES_POINTS);
        dataset[i].SetErrorBars(Gnuplot2dDataset::Y);
    }

    for (uint32_t maxReintentos = reintentosInicial; maxReintentos <= reintentosFinal; maxReintentos++) {
        Average<double> numIntentosTotales;
        Average<double> tiempoEcoTotal;
        Average<double> porcentajeErrorClientes;
        for (int i = 0; i < 10; i++) {
            DATOS datos;
            //Modificamos la semilla de la simulacion
            SeedManager::SetRun (seed++);
            datos = simulacion(nCsma, retardoProp, capacidad, tamPaquete, intervalo, maxReintentos);
            numIntentosTotales.Update (datos.mediaNumIntentosTotales);
            tiempoEcoTotal.Update (datos.mediaTiempoEcoTotal);
            porcentajeErrorClientes.Update (datos.mediaPorcentajeErrorClientes);
        }
        double z[3];
        z[0] = T_STUDENT_VALUE * std::sqrt (numIntentosTotales.Var() / 10);
        dataset[0].Add(maxReintentos, numIntentosTotales.Mean(), 2 * z[0]);
        z[1] = T_STUDENT_VALUE * std::sqrt (tiempoEcoTotal.Var() / 10);
        dataset[1].Add(maxReintentos, tiempoEcoTotal.Mean(), 2 * z[1]);
        z[2] = T_STUDENT_VALUE * std::sqrt (porcentajeErrorClientes.Var() / 10);
        dataset[2].Add(maxReintentos, porcentajeErrorClientes.Mean(), 2 * z[2]);
        NS_LOG_DEBUG (numIntentosTotales.Mean() - z[0] << " < numIntentosTotales < " << numIntentosTotales.Mean() + z[0]);
        NS_LOG_DEBUG (tiempoEcoTotal.Mean() - z[1] << " < tiempoEcoTotal < " << tiempoEcoTotal.Mean() + z[1]);
        NS_LOG_DEBUG (porcentajeErrorClientes.Mean() - z[2] << " < porcentajeErrorClientes < " << porcentajeErrorClientes.Mean() + z[2]);
        NS_LOG_DEBUG ("");
    }

        plot[0].AddDataset (dataset[0]);
        std::ofstream plotFile1 ("practica05-01.plt");
        plot[0].GenerateOutput (plotFile1);
        plotFile1 << "pause -1" << std::endl;
        plotFile1.close ();

        plot[1].AddDataset (dataset[1]);
        std::ofstream plotFile2 ("practica05-02.plt");
        plot[1].GenerateOutput (plotFile2);
        plotFile2 << "pause -1" << std::endl;
        plotFile2.close ();

        plot[2].AddDataset (dataset[2]);
        std::ofstream plotFile3 ("practica05-03.plt");
        plot[2].GenerateOutput (plotFile3);
        plotFile3 << "pause -1" << std::endl;
        plotFile3.close ();

    return 0;
}
<commit_msg>P05 añadido tiempo de simulacion como parametro<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include "ns3/object.h"
#include "ns3/global-value.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include <ns3/gnuplot.h>
#include <sstream>

#include "Observador.h"

#define STARTTIME 2.0
#define STOPTIME  10000.0
#define T_STUDENT_VALUE 2.2622

typedef struct datos {
    double mediaNumIntentosTotales;
    double mediaTiempoEcoTotal;
    double mediaPorcentajeErrorClientes;
} DATOS;

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("practica05");

DATOS simulacion (uint32_t nCsma, Time retardoProp, DataRate capacidad,
        uint32_t tamPaquete, Time intervalo, uint32_t maxReintentos, double tSimulacion) {

    NodeContainer csmaNodes;
    csmaNodes.Create (nCsma);

    CsmaHelper csma;
    csma.SetChannelAttribute ("DataRate", DataRateValue (capacidad));
    csma.SetChannelAttribute ("Delay", TimeValue (retardoProp));

    NetDeviceContainer csmaDevices;
    csmaDevices = csma.Install (csmaNodes);
    // Instalamos la pila TCP/IP en todos los nodos
    InternetStackHelper stack;
    stack.Install (csmaNodes);
    // Y les asignamos direcciones
    Ipv4AddressHelper address;
    address.SetBase ("10.1.2.0", "255.255.255.0");
    Ipv4InterfaceContainer csmaInterfaces = address.Assign (csmaDevices);

    /////////// Instalación de las aplicaciones
    // Servidor
    UdpEchoServerHelper echoServer (9);
    ApplicationContainer serverApp = echoServer.Install (csmaNodes.Get (nCsma - 1));
    serverApp.Start (Seconds (STARTTIME));
    serverApp.Stop (Seconds (STARTTIME + tSimulacion));
    // Clientes
    UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma - 1), 9);
    echoClient.SetAttribute ("MaxPackets", UintegerValue (10000));
    echoClient.SetAttribute ("Interval", TimeValue (intervalo));
    echoClient.SetAttribute ("PacketSize", UintegerValue (tamPaquete));
    NodeContainer clientes;

    for (uint32_t i = 0; i < nCsma - 1; i++)
    {
        clientes.Add (csmaNodes.Get (i));
    }
    NS_LOG_FUNCTION ("Fin bucle de creacion de observadores");

    ApplicationContainer clientApps = echoClient.Install (clientes);
    NS_LOG_FUNCTION ("Instalacion de clientes de echo realizada");
    clientApps.Start (Seconds (STARTTIME));
    clientApps.Stop (Seconds (STARTTIME + tSimulacion));

    // Cálculo de rutas
    Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

    csma.EnablePcap ("practica05", csmaDevices.Get (nCsma - 1), true);

    Observador observadores[nCsma];
    for (uint32_t i = 0; i < nCsma; i++) {
        csmaDevices.Get(i)->TraceConnectWithoutContext ("PhyTxEnd",     MakeCallback(&Observador::PaqueteEnviado,              &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("PhyTxDrop",    MakeCallback(&Observador::PaquetePerdido,              &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacTxBackoff", MakeCallback(&Observador::PaqueteEnBackoff,            &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacTx",        MakeCallback(&Observador::PaqueteParaEnviar,           &observadores[i]));
        csmaDevices.Get(i)->TraceConnectWithoutContext ("MacRx",        MakeCallback(&Observador::PaqueteRecibidoParaEntregar, &observadores[i]));

        Ptr<CsmaNetDevice> csma_device = csmaDevices.Get(i)->GetObject<CsmaNetDevice>();
        csma_device->SetBackoffParams (Time ("1us"), 10, 1000, 10, maxReintentos);
    }

    NS_LOG_FUNCTION ("Va a comenzar la simulacion");
    Simulator::Run ();
    Simulator::Destroy ();
    NS_LOG_FUNCTION ("Finalizada simulacion");

    Average<uint32_t> numIntentosTotales;
    Average<double>   tiempoEcoTotal;
    Average<double>   porcentajeErrorClientes;
    Average<double>   porcentajeErrorEscenario;

    for (uint32_t i = 0; i < nCsma; i++) {

        double mediaNumIntentos = observadores[i].GetMediaNumIntentos();
        double mediaTiempoEco = observadores[i].GetMediaTiempoEco();
        double porcentajeError = observadores[i].GetPorcentajePaquetesPerdidos();

        if (std::isnan(mediaNumIntentos)) {
            mediaNumIntentos = 0;
        }
        if (std::isnan(mediaTiempoEco)) {
            mediaTiempoEco = 0;
        }

        NS_LOG_INFO ("Media de intentos en nodo " << i << ": " << mediaNumIntentos);
        porcentajeErrorEscenario.Update(porcentajeError);
        if (i < nCsma - 1) {
           NS_LOG_INFO ("Tiempo medio de eco en nodo " << i << ": " << Time(mediaTiempoEco));
           if (i > 1) {
               porcentajeErrorClientes.Update(porcentajeError);
               tiempoEcoTotal.Update(mediaTiempoEco);
               numIntentosTotales.Update(mediaNumIntentos);
           }
        }
        NS_LOG_INFO ("Porcentaje de paquetes perdidos en nodo " << i << ": " << porcentajeError << " %");
        NS_LOG_INFO ("");
    }

    double mediaNumIntentosTotales = numIntentosTotales.Mean();
    double mediaTiempoEcoTotal = tiempoEcoTotal.Mean();
    double mediaPorcentajeErrorClientes = porcentajeErrorClientes.Mean();
    double mediaPorcentajeErrorEscenario = porcentajeErrorEscenario.Mean();

    if (std::isnan(mediaNumIntentosTotales)) {
        mediaNumIntentosTotales = 0;
    }
    if (std::isnan(mediaTiempoEcoTotal)) {
        mediaTiempoEcoTotal = 0;
    }
    if (std::isnan(mediaPorcentajeErrorClientes)) {
        mediaPorcentajeErrorClientes = 0;
    }
    if (std::isnan(mediaPorcentajeErrorEscenario)) {
        mediaPorcentajeErrorEscenario = 0;
    }

    NS_LOG_INFO ("--------------------------------------------------------");
    NS_LOG_INFO ("Media de intentos de transmision en el escenario: " << mediaNumIntentosTotales);
    NS_LOG_INFO ("Tiempo de eco medio en el escenario: " << Time(mediaTiempoEcoTotal));
    NS_LOG_INFO ("Porcentaje de paquetes perdidos por los clientes: " << mediaPorcentajeErrorClientes << " %");
    NS_LOG_INFO ("Porcentaje de paquetes perdidos en el escenario: " << mediaPorcentajeErrorEscenario << " %");
    NS_LOG_INFO ("--------------------------------------------------------");

    DATOS datos = { mediaNumIntentosTotales, mediaTiempoEcoTotal, mediaPorcentajeErrorClientes };
    return datos;
}

int
main (int argc, char *argv[])
{
    GlobalValue::Bind("ChecksumEnabled", BooleanValue(true));
    Time::SetResolution (Time::US);

    uint32_t seed = 1;

    uint32_t dni[8] = {3,1,4,8,2,2,0,3};
    NS_LOG_INFO ("DNI: " << dni[8]<<dni[7]<<dni[6]<<dni[5]<<dni[4]<<dni[3]<<dni[2]<<dni[1]);

    //Parametros de simulacion
    uint32_t nCsma             = 10-dni[0]/2;
    Time     retardoProp       = Time ("6560ns");
    DataRate capacidad         = DataRate ("100Mbps");
    uint32_t tamPaquete        = 500+100*dni[1];
    Time     intervalo         = Time ("1s");
    uint32_t reintentosInicial = 2;
    uint32_t reintentosFinal   = 12;
    double   tSimulacion       = 1000;

    CommandLine cmd;
    cmd.AddValue ("nCsma", "Número de nodos de la red local", nCsma);
    cmd.AddValue ("retardoProp", "retardo de propagación en el bus", retardoProp);
    cmd.AddValue ("capacidad", "capacidad del bus", capacidad);
    cmd.AddValue ("tamPaquete", "tamaño de las SDU de aplicación", tamPaquete);
    cmd.AddValue ("intervalo", "tiempo entre dos paquetes consecutivos enviados por el mismo cliente", intervalo);
    cmd.AddValue ("reintentosInicial", "valor inicial de reintentos", reintentosInicial);
    cmd.AddValue ("reintentosFinal", "valor final de reintentos", reintentosFinal);
    cmd.AddValue ("tSimulacion", "tiempo de cada simulacion", tSimulacion);
    cmd.Parse (argc,argv);

    NS_LOG_FUNCTION("nCsma" << nCsma);
    NS_LOG_FUNCTION("retardoProp" << retardoProp);
    NS_LOG_FUNCTION("capacidad" << capacidad);
    NS_LOG_FUNCTION("tamPaquete" << tamPaquete);
    NS_LOG_FUNCTION("intervalo" << intervalo);
    NS_LOG_FUNCTION("reintentosInicial" << reintentosInicial);
    NS_LOG_FUNCTION("reintentosFinal" << reintentosFinal);

    Gnuplot plot[3];
    plot[0].SetTitle ("Evolución del número medio de intentos");
    plot[0].SetLegend ("maxReint", "numIntentos");
    plot[1].SetTitle ("Evolución del tiempo medio de eco");
    plot[1].SetLegend ("maxReint", "tEco (us)");
    plot[2].SetTitle ("Evolución del porcentaje de error");
    plot[2].SetLegend ("maxReint", "perror (%)");

    Gnuplot2dDataset dataset[3];
    for (int i = 0; i < 3 ; i++) {
        dataset[i].SetStyle (Gnuplot2dDataset::LINES_POINTS);
        dataset[i].SetErrorBars(Gnuplot2dDataset::Y);
    }

    for (uint32_t maxReintentos = reintentosInicial; maxReintentos <= reintentosFinal; maxReintentos++) {
        Average<double> numIntentosTotales;
        Average<double> tiempoEcoTotal;
        Average<double> porcentajeErrorClientes;
        for (int i = 0; i < 10; i++) {
            DATOS datos;
            //Modificamos la semilla de la simulacion
            SeedManager::SetRun (seed++);
            datos = simulacion(nCsma, retardoProp, capacidad, tamPaquete, intervalo, maxReintentos, tSimulacion);
            numIntentosTotales.Update (datos.mediaNumIntentosTotales);
            tiempoEcoTotal.Update (datos.mediaTiempoEcoTotal);
            porcentajeErrorClientes.Update (datos.mediaPorcentajeErrorClientes);
        }
        double z[3];
        z[0] = T_STUDENT_VALUE * std::sqrt (numIntentosTotales.Var() / 10);
        dataset[0].Add(maxReintentos, numIntentosTotales.Mean(), 2 * z[0]);
        z[1] = T_STUDENT_VALUE * std::sqrt (tiempoEcoTotal.Var() / 10);
        dataset[1].Add(maxReintentos, tiempoEcoTotal.Mean(), 2 * z[1]);
        z[2] = T_STUDENT_VALUE * std::sqrt (porcentajeErrorClientes.Var() / 10);
        dataset[2].Add(maxReintentos, porcentajeErrorClientes.Mean(), 2 * z[2]);
        NS_LOG_DEBUG (numIntentosTotales.Mean() - z[0] << " < numIntentosTotales < " << numIntentosTotales.Mean() + z[0]);
        NS_LOG_DEBUG (tiempoEcoTotal.Mean() - z[1] << " < tiempoEcoTotal < " << tiempoEcoTotal.Mean() + z[1]);
        NS_LOG_DEBUG (porcentajeErrorClientes.Mean() - z[2] << " < porcentajeErrorClientes < " << porcentajeErrorClientes.Mean() + z[2]);
        NS_LOG_DEBUG ("");
    }

        plot[0].AddDataset (dataset[0]);
        std::ofstream plotFile1 ("practica05-01.plt");
        plot[0].GenerateOutput (plotFile1);
        plotFile1 << "pause -1" << std::endl;
        plotFile1.close ();

        plot[1].AddDataset (dataset[1]);
        std::ofstream plotFile2 ("practica05-02.plt");
        plot[1].GenerateOutput (plotFile2);
        plotFile2 << "pause -1" << std::endl;
        plotFile2.close ();

        plot[2].AddDataset (dataset[2]);
        std::ofstream plotFile3 ("practica05-03.plt");
        plot[2].GenerateOutput (plotFile3);
        plotFile3 << "pause -1" << std::endl;
        plotFile3.close ();

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>coverity#708296 Uninitialized pointer field<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(), m_type(type), m_status(status)
{

}

QXmppPresence::~QXmppPresence()
{

}

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    m_vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0153: vCard-Based Avatars
        if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                m_photoHash = photoElement.text().toUtf8();
                if(m_photoHash.isEmpty())
                    m_vCardUpdateType = PhotoNotAdvertized;
                else
                    m_vCardUpdateType = PhotoAdvertised;
            }
            else
            {
                m_photoHash = "";
                m_vCardUpdateType = PhotoNotReady;
            }
        }
        else
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);

    // XEP-0153: vCard-Based Avatars
    if(m_vCardUpdateType != VCardUpdateNone)
    {
        xmlWriter->writeStartElement("x");
        helperToXmlAddAttribute(xmlWriter, "xmlns", ns_vcard_update);
        switch(m_vCardUpdateType)
        {
        case PhotoNotAdvertized:
            helperToXmlAddTextElement(xmlWriter, "photo", "");
            break;
        case PhotoAdvertised:
            helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash);
            break;
        case PhotoNotReady:
            break;
        default:
            break;
        }
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Error:
        text = "error";
        break;
    case QXmppPresence::Available:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Unavailable:
        text = "unavailable";
        break;
    case QXmppPresence::Subscribe:
        text = "subscribe";
        break;
    case QXmppPresence::Subscribed:
        text = "subscribed";
        break;
    case QXmppPresence::Unsubscribe:
        text = "unsubscribe";
        break;
    case QXmppPresence::Unsubscribed:
        text = "unsubscribed";
        break;
    case QXmppPresence::Probe:
        text = "probe";
        break;
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        break;
    }
    return text;
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    QXmppPresence::Type type;
    if(str == "error")
    {
        type = QXmppPresence::Error;
        setType(type);
        return;
    }
    else if(str == "unavailable")
    {
        type = QXmppPresence::Unavailable;
        setType(type);
        return;
    }
    else if(str == "subscribe")
    {
        type = QXmppPresence::Subscribe;
        setType(type);
        return;
    }
    else if(str == "subscribed")
    {
        type = QXmppPresence::Subscribed;
        setType(type);
        return;
    }
    else if(str == "unsubscribe")
    {
        type = QXmppPresence::Unsubscribe;
        setType(type);
        return;
    }
    else if(str == "unsubscribed")
    {
        type = QXmppPresence::Unsubscribed;
        setType(type);
        return;
    }
    else if(str == "probe")
    {
        type = QXmppPresence::Probe;
        setType(type);
        return;
    }
    else if(str == "")
    {
        type = QXmppPresence::Available;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Type>(-1);
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        setType(type);
        return;
    }
}

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // there is no keyword for Offline

    QXmppPresence::Status::Type type;
    if(str == "")   // not type-attribute means online
    {
        type = QXmppPresence::Status::Online;
        setType(type);
        return;
    }
    else if(str == "away")
    {
        type = QXmppPresence::Status::Away;
        setType(type);
        return;
    }
    else if(str == "xa")
    {
        type = QXmppPresence::Status::XA;
        setType(type);
        return;
    }
    else if(str == "dnd")
    {
        type = QXmppPresence::Status::DND;
        setType(type);
        return;
    }
    else if(str == "chat")
    {
        type = QXmppPresence::Status::Chat;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Status::Type>(-1);
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        setType(type);
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Status::Online:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Status::Offline:
        text = "";
        break;
    case QXmppPresence::Status::Away:
        text = "away";
        break;
    case QXmppPresence::Status::XA:
        text = "xa";
        break;
    case QXmppPresence::Status::DND:
        text = "dnd";
        break;
    case QXmppPresence::Status::Chat:
        text = "chat";
        break;
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        break;
    }
    return text;
}

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    const QString show = getTypeStr();
    if (!show.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    if (!m_statusText.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}

QByteArray QXmppPresence::photoHash() const
{
    return m_photoHash;
}

void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
    m_photoHash = photoHash;
}

QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()
{
    return m_vCardUpdateType;
}

void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
    m_vCardUpdateType = type;
}

/// \cond

QXmppPresence::Type QXmppPresence::getType() const
{
    return m_type;
}

const QXmppPresence::Status& QXmppPresence::getStatus() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::getStatus()
{
    return m_status;
}

QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
    return m_type;
}

QString QXmppPresence::Status::getStatusText() const
{
    return m_statusText;
}

int QXmppPresence::Status::getPriority() const
{
    return m_priority;
}

/// \endcond
<commit_msg>the "error" element in a presence stanza is already handled by QXmppStanza::parse(), don't include it in the extensions<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(), m_type(type), m_status(status)
{

}

QXmppPresence::~QXmppPresence()
{

}

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    m_vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0153: vCard-Based Avatars
        if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                m_photoHash = photoElement.text().toUtf8();
                if(m_photoHash.isEmpty())
                    m_vCardUpdateType = PhotoNotAdvertized;
                else
                    m_vCardUpdateType = PhotoAdvertised;
            }
            else
            {
                m_photoHash = "";
                m_vCardUpdateType = PhotoNotReady;
            }
        }
        else if (xElement.tagName() != "error")
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);

    // XEP-0153: vCard-Based Avatars
    if(m_vCardUpdateType != VCardUpdateNone)
    {
        xmlWriter->writeStartElement("x");
        helperToXmlAddAttribute(xmlWriter, "xmlns", ns_vcard_update);
        switch(m_vCardUpdateType)
        {
        case PhotoNotAdvertized:
            helperToXmlAddTextElement(xmlWriter, "photo", "");
            break;
        case PhotoAdvertised:
            helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash);
            break;
        case PhotoNotReady:
            break;
        default:
            break;
        }
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Error:
        text = "error";
        break;
    case QXmppPresence::Available:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Unavailable:
        text = "unavailable";
        break;
    case QXmppPresence::Subscribe:
        text = "subscribe";
        break;
    case QXmppPresence::Subscribed:
        text = "subscribed";
        break;
    case QXmppPresence::Unsubscribe:
        text = "unsubscribe";
        break;
    case QXmppPresence::Unsubscribed:
        text = "unsubscribed";
        break;
    case QXmppPresence::Probe:
        text = "probe";
        break;
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        break;
    }
    return text;
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    QXmppPresence::Type type;
    if(str == "error")
    {
        type = QXmppPresence::Error;
        setType(type);
        return;
    }
    else if(str == "unavailable")
    {
        type = QXmppPresence::Unavailable;
        setType(type);
        return;
    }
    else if(str == "subscribe")
    {
        type = QXmppPresence::Subscribe;
        setType(type);
        return;
    }
    else if(str == "subscribed")
    {
        type = QXmppPresence::Subscribed;
        setType(type);
        return;
    }
    else if(str == "unsubscribe")
    {
        type = QXmppPresence::Unsubscribe;
        setType(type);
        return;
    }
    else if(str == "unsubscribed")
    {
        type = QXmppPresence::Unsubscribed;
        setType(type);
        return;
    }
    else if(str == "probe")
    {
        type = QXmppPresence::Probe;
        setType(type);
        return;
    }
    else if(str == "")
    {
        type = QXmppPresence::Available;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Type>(-1);
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        setType(type);
        return;
    }
}

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // there is no keyword for Offline

    QXmppPresence::Status::Type type;
    if(str == "")   // not type-attribute means online
    {
        type = QXmppPresence::Status::Online;
        setType(type);
        return;
    }
    else if(str == "away")
    {
        type = QXmppPresence::Status::Away;
        setType(type);
        return;
    }
    else if(str == "xa")
    {
        type = QXmppPresence::Status::XA;
        setType(type);
        return;
    }
    else if(str == "dnd")
    {
        type = QXmppPresence::Status::DND;
        setType(type);
        return;
    }
    else if(str == "chat")
    {
        type = QXmppPresence::Status::Chat;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Status::Type>(-1);
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        setType(type);
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Status::Online:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Status::Offline:
        text = "";
        break;
    case QXmppPresence::Status::Away:
        text = "away";
        break;
    case QXmppPresence::Status::XA:
        text = "xa";
        break;
    case QXmppPresence::Status::DND:
        text = "dnd";
        break;
    case QXmppPresence::Status::Chat:
        text = "chat";
        break;
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        break;
    }
    return text;
}

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    const QString show = getTypeStr();
    if (!show.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    if (!m_statusText.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}

QByteArray QXmppPresence::photoHash() const
{
    return m_photoHash;
}

void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
    m_photoHash = photoHash;
}

QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()
{
    return m_vCardUpdateType;
}

void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
    m_vCardUpdateType = type;
}

/// \cond

QXmppPresence::Type QXmppPresence::getType() const
{
    return m_type;
}

const QXmppPresence::Status& QXmppPresence::getStatus() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::getStatus()
{
    return m_status;
}

QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
    return m_type;
}

QString QXmppPresence::Status::getStatusText() const
{
    return m_statusText;
}

int QXmppPresence::Status::getPriority() const
{
    return m_priority;
}

/// \endcond
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef __rtkBinningImageFilter_cxx
#define __rtkBinningImageFilter_cxx

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkVariableLengthVector.h>
#include <itkImageConstIteratorWithIndex.h>

namespace rtk
{

BinningImageFilter::BinningImageFilter()
{
  m_BinningFactors[0]=2;
  m_BinningFactors[1]=2;
}

void BinningImageFilter::GenerateInputRequestedRegion()
{
  ImageType::Pointer inputPtr = const_cast<ImageType *>(this->GetInput());
  const ImageType::Pointer outputPtr = const_cast<ImageType *>(this->GetOutput());

  ImageType::RegionType inputReqRegion = inputPtr->GetLargestPossibleRegion();
  const ImageType::RegionType outputReqRegion = outputPtr->GetRequestedRegion();
  const ImageType::RegionType outputLPRegion = outputPtr->GetLargestPossibleRegion();
  for (unsigned int i = 0; i < ImageType::ImageDimension; i++)
    {
    inputReqRegion.SetSize(i, outputReqRegion.GetSize(i) * m_BinningFactors[i]);
    inputReqRegion.SetIndex(i, inputReqRegion.GetIndex(i) +
                               m_BinningFactors[i] * ( outputReqRegion.GetIndex(i) -
                                                       outputLPRegion.GetIndex(i) ) );
    }
  inputPtr->SetRequestedRegion( inputReqRegion );
}

void BinningImageFilter::GenerateOutputInformation()
{
  const ImageType::SpacingType& inputSpacing    = this->GetInput()->GetSpacing();
  const ImageType::SizeType&    inputSize       = this->GetInput()->GetLargestPossibleRegion().GetSize();
  const ImageType::IndexType&   inputStartIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();
  const ImageType::PointType&   inputOrigin     = this->GetInput()->GetOrigin();

  ImageType::SpacingType  outputSpacing;
  ImageType::SizeType     outputSize;
  ImageType::IndexType    outputStartIndex;
  ImageType::PointType    outputOrigin;

  for (unsigned int i = 0; i < ImageType::ImageDimension; i++)
    {
    outputSpacing[i] = inputSpacing[i] * m_BinningFactors[i];
    outputOrigin[i]  = inputOrigin[i] - 0.5*inputSpacing[i] + 0.5*outputSpacing[i];
    if(inputSize[i]%m_BinningFactors[i] != 0)
      {
      itkExceptionMacro(<< "Binning currently works only for integer divisions")
      }
    else
      outputSize[i] = inputSize[i] / m_BinningFactors[i];

    outputStartIndex[i] = 0;
  }

  this->GetOutput()->SetSpacing( outputSpacing );
  this->GetOutput()->SetOrigin( outputOrigin );

  // Set region
  ImageType::RegionType outputLargestPossibleRegion;
  outputLargestPossibleRegion.SetSize( outputSize );
  outputLargestPossibleRegion.SetIndex( outputStartIndex );
  this->GetOutput()->SetLargestPossibleRegion( outputLargestPossibleRegion );
}

void BinningImageFilter
::ThreadedGenerateData(const OutputImageRegionType& itkNotUsed(outputRegionForThread), ThreadIdType threadId )
{

  int inputSize[2], binSize[2];
  inputSize[0] = this->GetInput()->GetLargestPossibleRegion().GetSize()[0];
  inputSize[1] = this->GetInput()->GetLargestPossibleRegion().GetSize()[1];
  binSize[0] = (inputSize[0]>>1);
  binSize[1] = (inputSize[1]>>1);

  typedef   ImageType::PixelType inputPixel;
  typedef   ImageType::PixelType outputPixel;

  //this->GenerateOutputInformation();
  const inputPixel  *bufferIn  = this->GetInput()->GetBufferPointer();
  outputPixel *bufferOut = this->GetOutput()->GetBufferPointer();

  int initX = threadId*inputSize[0]*inputSize[1]/(this->GetNumberOfThreads()*m_BinningFactors[0]);
  int endX = initX + binSize[0]*inputSize[1]/this->GetNumberOfThreads();
  int initY = threadId*binSize[1]/this->GetNumberOfThreads();
  int endY = initY + binSize[1]/this->GetNumberOfThreads();

  // Binning 2x2
  if(m_BinningFactors[0]==2 && m_BinningFactors[1]==2)
  {
    const int Vlength = endX-initX;
    std::vector<int> V(Vlength,0);

    int i, j, idx, pos, vj;
    for (i=0, idx=initX*m_BinningFactors[0]; i < Vlength; i++, idx+=2) // Only works if number of pixels per line multiple of 2
    {
        V[i] = ( (bufferIn[idx])+(bufferIn[idx+1]) );
    }
    for (j=initY, vj=0; j<endY; j++, vj++)
    {
      pos = j*binSize[0];
      for (i=0; i < binSize[0]; i++, pos++)
        {
            bufferOut[pos] = ( (V[2*vj*binSize[0]+i])+(V[(2*vj+1)*binSize[0]+i]) )>>2;
        }
    }
  }

  // Binning 2x1
  else if(m_BinningFactors[0]==2 && m_BinningFactors[1]==1)
  {
    int i, idx;
    for (i=initX, idx=initX*m_BinningFactors[0]; i < endX; i++, idx+=2) // Only works if number of pixels per line multiple of 2
        bufferOut[i] = ( (bufferIn[idx])+(bufferIn[idx+1]) )>>1;
  }

  // Binning 1x2
  else if(m_BinningFactors[0]==1 && m_BinningFactors[1]==2)
  {
    int i, j, pos;
    for (j=initY; j<endY;j++)
    {
      pos = j*inputSize[0];
      for (i=0; i<inputSize[0];i++, pos++)
        bufferOut[pos] = ( (bufferIn[2*j*inputSize[0]+i])+(bufferIn[(2*j+1)*inputSize[0]+i]) )>>1;
    }
  }
  else
  {
    itkExceptionMacro(<< "Binning factors mismatch! Current factors: "
                      << m_BinningFactors[0] << "x"
                      << m_BinningFactors[1] << " "
                      << "accepted modes [2x2] [2x1] and [1x2]")
  }
}

} // end namespace rtk

#endif // __rtkBinningImageFilter_cxx
<commit_msg>Use itk regions in binning<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef __rtkBinningImageFilter_cxx
#define __rtkBinningImageFilter_cxx

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkVariableLengthVector.h>
#include <itkImageConstIteratorWithIndex.h>

namespace rtk
{

BinningImageFilter::BinningImageFilter()
{
  m_BinningFactors[0]=2;
  m_BinningFactors[1]=2;
}

void BinningImageFilter::GenerateInputRequestedRegion()
{
  ImageType::Pointer inputPtr = const_cast<ImageType *>(this->GetInput());
  const ImageType::Pointer outputPtr = const_cast<ImageType *>(this->GetOutput());

  ImageType::RegionType inputReqRegion = inputPtr->GetLargestPossibleRegion();
  const ImageType::RegionType outputReqRegion = outputPtr->GetRequestedRegion();
  const ImageType::RegionType outputLPRegion = outputPtr->GetLargestPossibleRegion();
  for (unsigned int i = 0; i < ImageType::ImageDimension; i++)
    {
    inputReqRegion.SetSize(i, outputReqRegion.GetSize(i) * m_BinningFactors[i]);
    inputReqRegion.SetIndex(i, inputReqRegion.GetIndex(i) +
                               m_BinningFactors[i] * ( outputReqRegion.GetIndex(i) -
                                                       outputLPRegion.GetIndex(i) ) );
    }
  inputPtr->SetRequestedRegion( inputReqRegion );
}

void BinningImageFilter::GenerateOutputInformation()
{
  const ImageType::SpacingType& inputSpacing    = this->GetInput()->GetSpacing();
  const ImageType::SizeType&    inputSize       = this->GetInput()->GetLargestPossibleRegion().GetSize();
  const ImageType::IndexType&   inputStartIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();
  const ImageType::PointType&   inputOrigin     = this->GetInput()->GetOrigin();

  ImageType::SpacingType  outputSpacing;
  ImageType::SizeType     outputSize;
  ImageType::IndexType    outputStartIndex;
  ImageType::PointType    outputOrigin;

  for (unsigned int i = 0; i < ImageType::ImageDimension; i++)
    {
    outputSpacing[i] = inputSpacing[i] * m_BinningFactors[i];
    outputOrigin[i]  = inputOrigin[i] - 0.5*inputSpacing[i] + 0.5*outputSpacing[i];
    if(inputSize[i]%m_BinningFactors[i] != 0)
      {
      itkExceptionMacro(<< "Binning currently works only for integer divisions")
      }
    else
      outputSize[i] = inputSize[i] / m_BinningFactors[i];

    outputStartIndex[i] = 0;
  }

  this->GetOutput()->SetSpacing( outputSpacing );
  this->GetOutput()->SetOrigin( outputOrigin );

  // Set region
  ImageType::RegionType outputLargestPossibleRegion;
  outputLargestPossibleRegion.SetSize( outputSize );
  outputLargestPossibleRegion.SetIndex( outputStartIndex );
  this->GetOutput()->SetLargestPossibleRegion( outputLargestPossibleRegion );
}

void BinningImageFilter
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType itkNotUsed(threadId) )
{
  const ImageType::PixelType *pIn  = this->GetInput()->GetBufferPointer();
  ImageType::PixelType *pOut = this->GetOutput()->GetBufferPointer();

  // Move pointers to beginning of region
  ImageType::RegionType inputRegion;
  for(unsigned int i=0; i<ImageType::ImageDimension; i++)
    {
    pOut += outputRegionForThread.GetIndex(i) * this->GetOutput()->GetOffsetTable()[i];
    pIn  += outputRegionForThread.GetIndex(i) * this->GetInput() ->GetOffsetTable()[i] * m_BinningFactors[i];

    // Account for difference between buffered and largest possible regions
    pOut -= this->GetOutput()->GetOffsetTable()[i] *
            (this->GetOutput()->GetBufferedRegion().GetIndex()[i] -
             this->GetOutput()->GetLargestPossibleRegion().GetIndex()[i]);
    pIn  -= this->GetInput()->GetOffsetTable()[i] *
            (this->GetInput()->GetBufferedRegion().GetIndex()[i] -
             this->GetInput()->GetLargestPossibleRegion().GetIndex()[i]);
    }

  // Binning 2x2
  if(m_BinningFactors[0]==2 && m_BinningFactors[1]==2)
    {
    const size_t buffSize = outputRegionForThread.GetNumberOfPixels()*2;
    int *buffer = new int[buffSize];
    for(unsigned int j=0; j<outputRegionForThread.GetSize(1)*2; j++,
                                                                pIn+=this->GetInput()->GetOffsetTable()[1])
      for(unsigned int i=0; i<outputRegionForThread.GetSize(0)*2; i+=2, buffer++)
        *buffer = pIn[i] + pIn[i+1];

    buffer -= buffSize; // Back to original position
    for(unsigned int j=0; j<outputRegionForThread.GetSize(1); j++,
                                                              pOut+=this->GetOutput()->GetOffsetTable()[1],
                                                              buffer += 2*outputRegionForThread.GetSize(0))
      for(unsigned int i=0; i<outputRegionForThread.GetSize(0); i++)
        pOut[i] = (buffer[i] + buffer[i+outputRegionForThread.GetSize(0)] ) >> 2;

    buffer -= buffSize; // Back to original position
    delete buffer;
    }

  // Binning 2x1
  else if(m_BinningFactors[0]==2 && m_BinningFactors[1]==1)
    {
    for(unsigned int j=0; j<outputRegionForThread.GetSize(1); j++,
                                                              pIn+=this->GetInput()->GetOffsetTable()[1])
      for(unsigned int i=0; i<outputRegionForThread.GetSize(0)*2; i+=2, pOut++)
        *pOut = (pIn[i] + pIn[i+1])>>1;
    }

  // Binning 1x2
  else if(m_BinningFactors[0]==1 && m_BinningFactors[1]==2)
    {
    for(unsigned int j=0; j<outputRegionForThread.GetSize(1); j++,
                                                              pOut += this->GetOutput()->GetOffsetTable()[1],
                                                              pIn  += 2*this->GetInput()->GetOffsetTable()[1])
      for(unsigned int i=0; i<outputRegionForThread.GetSize(0); i++)
        pOut[i] = (pIn[i] + pIn[i+this->GetInput()->GetOffsetTable()[1]]) >> 1;
    }
  else
    {
    itkExceptionMacro(<< "Binning factors mismatch! Current factors: "
                      << m_BinningFactors[0] << "x"
                      << m_BinningFactors[1] << " "
                      << "accepted modes [2x2] [2x1] and [1x2]")
    }
}

} // end namespace rtk

#endif // __rtkBinningImageFilter_cxx
<|endoftext|>


<commit_before>#include <memory>
#include <mutex>
#include <sstream>
#include <fstream>

#include <utils.h>
#include <teapot.h>
#include <chaiscript/chaiscript.hpp>

namespace fpgui {
namespace chai {

class Chai_Impl
{
    public:

        Chai_Impl(const char* chai_script):
        chai_script_(chai_script)
        {
            init();
        }

        ~Chai_Impl()
        {
            deinit();
        }

        int compare(const std::string& msg1, const std::string& msg2)
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);
            compare_result_ = -3;

            std::string log_msg1_escaped(msg1);
            std::string log_msg2_escaped(msg2);

            fpgui::generic_util::escape_quotes(log_msg1_escaped);
            fpgui::generic_util::escape_quotes(log_msg2_escaped);

            std::string std_format("log_msg1=\"%s\";\nfplog_message1 = from_json(log_msg1);\nlog_msg2=\"%s\";\nfplog_message2 = from_json(log_msg2);\n");

        retry_parsing:

            int chai_len = static_cast<int>(log_msg1_escaped.length() + log_msg2_escaped.length() + 256);

            char* chai_script = new char[chai_len];
            memset(chai_script, 0, chai_len);
            std::auto_ptr<char> chai_script_ptr(chai_script);
#ifndef _LINUX
            _snprintf(chai_script, chai_len - 1, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());
#else
            sprintf(chai_script, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());
#endif
            std::string full_script(chai_script + chai_script_);

            try
            {
                chai_->eval(full_script);
            }
            catch (chaiscript::exception::eval_error&)
            {
                std_format = "var log_msg1=\"%s\";\nvar fplog_message1 = from_json(log_msg1);\nvar log_msg2=\"%s\";\nvar fplog_message2 = from_json(log_msg2);\n";
                goto retry_parsing;
            }
            catch (std::exception& e)
            {
                std::cout << e.what() << std::endl;
                std::cout << full_script << std::endl;
            }

            return compare_result_;
        }

    private:

        int compare_result_;
        std::recursive_mutex mutex_;
        chaiscript::ChaiScript* chai_;

        void init()
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);

            chai_ = new chaiscript::ChaiScript(chaiscript::Std_Lib::library());
            chai_->add(chaiscript::var(std::ref(compare_result_)), "compare_result");
            chai_->add(chaiscript::fun(&generic_utils::date_time::iso_timestamp_to_ms), "iso_timestamp_to_ms");
        }

        void deinit()
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);

            delete chai_;
        }

        std::string chai_script_;
};

static std::recursive_mutex g_chai_mutex;
static std::auto_ptr<Chai_Impl> g_chai;

void load_from_file(const std::string& filename)
{
    std::lock_guard<std::recursive_mutex> lock(g_chai_mutex);

    std::ifstream infile(filename);
    std::string line, script;

    while (std::getline(infile, line))
        script += (line + "\n");

    g_chai.reset(new Chai_Impl(script.c_str()));
}

int compare_json_strings(const std::string& json_str1, const std::string& json_str2)
{
    if (!g_chai.get())
        return 0;

    return g_chai->compare(json_str1, json_str2);
}

}
}
<commit_msg>Missed include.<commit_after>#include <memory>
#include <mutex>
#include <sstream>
#include <fstream>

#include <utils.h>
#include <teapot.h>
#include <chaiscript/chaiscript.hpp>
#include <chaiscript/chaiscript_stdlib.hpp>

namespace fpgui {
namespace chai {

class Chai_Impl
{
    public:

        Chai_Impl(const char* chai_script):
        chai_script_(chai_script)
        {
            init();
        }

        ~Chai_Impl()
        {
            deinit();
        }

        int compare(const std::string& msg1, const std::string& msg2)
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);
            compare_result_ = -3;

            std::string log_msg1_escaped(msg1);
            std::string log_msg2_escaped(msg2);

            fpgui::generic_util::escape_quotes(log_msg1_escaped);
            fpgui::generic_util::escape_quotes(log_msg2_escaped);

            std::string std_format("log_msg1=\"%s\";\nfplog_message1 = from_json(log_msg1);\nlog_msg2=\"%s\";\nfplog_message2 = from_json(log_msg2);\n");

        retry_parsing:

            int chai_len = static_cast<int>(log_msg1_escaped.length() + log_msg2_escaped.length() + 256);

            char* chai_script = new char[chai_len];
            memset(chai_script, 0, chai_len);
            std::auto_ptr<char> chai_script_ptr(chai_script);
#ifndef _LINUX
            _snprintf(chai_script, chai_len - 1, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());
#else
            sprintf(chai_script, std_format.c_str(), log_msg1_escaped.c_str(), log_msg2_escaped.c_str());
#endif
            std::string full_script(chai_script + chai_script_);

            try
            {
                chai_->eval(full_script);
            }
            catch (chaiscript::exception::eval_error&)
            {
                std_format = "var log_msg1=\"%s\";\nvar fplog_message1 = from_json(log_msg1);\nvar log_msg2=\"%s\";\nvar fplog_message2 = from_json(log_msg2);\n";
                goto retry_parsing;
            }
            catch (std::exception& e)
            {
                std::cout << e.what() << std::endl;
                std::cout << full_script << std::endl;
            }

            return compare_result_;
        }

    private:

        int compare_result_;
        std::recursive_mutex mutex_;
        chaiscript::ChaiScript* chai_;

        void init()
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);

            chai_ = new chaiscript::ChaiScript(chaiscript::Std_Lib::library());
            chai_->add(chaiscript::var(std::ref(compare_result_)), "compare_result");
            chai_->add(chaiscript::fun(&generic_utils::date_time::iso_timestamp_to_ms), "iso_timestamp_to_ms");
        }

        void deinit()
        {
            std::lock_guard<std::recursive_mutex> lock(mutex_);

            delete chai_;
        }

        std::string chai_script_;
};

static std::recursive_mutex g_chai_mutex;
static std::auto_ptr<Chai_Impl> g_chai;

void load_from_file(const std::string& filename)
{
    std::lock_guard<std::recursive_mutex> lock(g_chai_mutex);

    std::ifstream infile(filename);
    std::string line, script;

    while (std::getline(infile, line))
        script += (line + "\n");

    g_chai.reset(new Chai_Impl(script.c_str()));
}

int compare_json_strings(const std::string& json_str1, const std::string& json_str2)
{
    if (!g_chai.get())
        return 0;

    return g_chai->compare(json_str1, json_str2);
}

}
}
<|endoftext|>


<commit_before><commit_msg>swpagerelsize: fix RelativeHeightRelation UNO API<commit_after><|endoftext|>


<commit_before><commit_msg>sal_uInt16 to more proper types, constify, avoid unneeded casts<commit_after><|endoftext|>


<commit_before>/*BEGIN_LEGAL
Intel Open Source License

Copyright (c) 2002-2013 Intel Corporation. All rights reserved.

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
the Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
#include <iostream>
#include <fstream>
#include "pin.H"

ofstream OutFile;

// The running count of instructions is kept here
// make it static to help the compiler optimize docount
static UINT64 ccount = 0;

static bool isMain = false;

static VOID ImageLoad(IMG img, VOID * v)
{
	cout << "Loading " << IMG_Name(img) << ", Image id = " << IMG_Id(img) << endl;
	for(SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec)){
		//cout << "SEC: " << SEC_Name(sec) << ", SEC size = " << SEC_Size(sec) << endl;
		for(RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn)){
			cout << "\tRTN: " << RTN_Name(rtn) << endl;
		}
	}

	RTN mainRtn = RTN_FindByName(img, "_init");
    if (RTN_Valid(mainRtn)){
    	isMain = true;
		cout << "main is valid" << endl;
	}else{
		cout << "main is invalid" << endl;
	}
}

// This function is called before every instruction is executed
VOID docount()
{
	ccount++;
}

// This function is called before every call instruction is executed
VOID print_RETURN_IP(ADDRINT ret_ip)
{
	OutFile << "Return: 0x" << hex << ret_ip << endl;
	/*
	REGVAL regval;
	REG reg = (REG)REG_EIP;
        PIN_GetContextRegval(ctxt, reg, &regval);
        UINT64 val;
        PIN_ReadRegvalQWord(&regval, &val, 0);
        OutFile << REG_StringShort(reg) << ": 0x" << hex << val << endl;
	*/
}

// This function is called before every return instruction is executed
VOID printRet(const CONTEXT * ctxt)
{
	REGVAL regval;
	REG reg = (REG)REG_EIP;
        PIN_GetContextRegval(ctxt, reg, &regval);
        UINT64 val;
        PIN_ReadRegvalQWord(&regval, &val, 0);
        OutFile << REG_StringShort(reg) << ": 0x" << hex << val << endl;
}

// Pin calls this function every time a call instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
	if(!isMain) return;
    // Insert a call to docount before every call instruction, no arguments are passed
	if(INS_IsCall(ins)){
    		INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END);
		INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)print_RETURN_IP, IARG_RETURN_IP, IARG_END);
	}
	else if(INS_IsRet(ins)){
		INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printRet, IARG_CONST_CONTEXT, IARG_END);
	}
}

KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
    "o", "maincallcount.out", "specify output file name");

// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
    // Write to a file since cout and cerr maybe closed by the application
    OutFile.setf(ios::showbase);
    OutFile << "Count " << dec << ccount << endl;
    OutFile.close();
}

/* ===================================================================== */
/* Print Help Message                                                    */
/* ===================================================================== */

INT32 Usage()
{
    cerr << "This tool counts the number of dynamic instructions executed" << endl;
    cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
    return -1;
}

/* ===================================================================== */
/* Main                                                                  */
/* ===================================================================== */
/*   argc, argv are the entire command line: pin -t <toolname> -- ...    */
/* ===================================================================== */

int main(int argc, char * argv[])
{
    // Initialize pin
    if (PIN_Init(argc, argv)) return Usage();

    OutFile.open(KnobOutputFile.Value().c_str());

	// Instruction to start only at main
	IMG_AddInstrumentFunction(ImageLoad, 0);

    // Register Instruction to be called to instrument instructions
    INS_AddInstrumentFunction(Instruction, 0);

    // Register Fini to be called when the application exits
    PIN_AddFiniFunction(Fini, 0);

    // Start the program, never returns
    PIN_StartProgram();

    return 0;
}
<commit_msg>correctly saves/checks return address before call/ret instructions<commit_after>/*BEGIN_LEGAL
Intel Open Source License

Copyright (c) 2002-2013 Intel Corporation. All rights reserved.

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
the Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
#include <iostream>
#include <fstream>
#include "pin.H"

ofstream OutFile;

// The running count of instructions is kept here
// make it static to help the compiler optimize docount
static UINT64 ccount = 0;

// This function is called before every instruction is executed
VOID docount()
{
	ccount++;
}

VOID saveCall(ADDRINT nextip)
{
	OutFile << "Return set: 0x" << hex << nextip << endl;
}

VOID checkRet(ADDRINT *rsp, UINT32 framesize)
{
	ADDRINT retval;

	ADDRINT rspval = *rsp;
	ADDRINT *psp = (ADDRINT *)rspval;
	retval = *psp;
	OutFile << "Return to: 0x" << hex << retval << endl;
}

// Pin calls this function every time a call instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
	// Insert a call to docount before every call instruction, no arguments are passed
	if (INS_IsCall(ins))
	{
		INS_InsertCall(ins, IPOINT_BEFORE,
			(AFUNPTR)docount,
			IARG_END);
		INS_InsertCall(ins, IPOINT_BEFORE,
			AFUNPTR(saveCall),
			IARG_ADDRINT, INS_NextAddress(ins),
			IARG_END);
	}
	else if (INS_IsRet(ins))
	{
		UINT64 imm = 0;
		if (INS_OperandCount(ins) > 0 && INS_OperandIsImmediate(ins, 0))
			imm = INS_OperandImmediate(ins, 0);

		INS_InsertCall(ins, IPOINT_BEFORE,
			AFUNPTR(checkRet),
			IARG_CALL_ORDER, CALL_ORDER_FIRST,
			IARG_REG_REFERENCE, REG_STACK_PTR,
			IARG_ADDRINT, (ADDRINT)imm,
			IARG_END);
	}
}

KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
    "o", "callcount.out", "specify output file name");

// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
    // Write to a file since cout and cerr maybe closed by the application
    OutFile.setf(ios::showbase);
    OutFile << "Count " << dec << ccount << endl;
    OutFile.close();
}

/* ===================================================================== */
/* Print Help Message                                                    */
/* ===================================================================== */

INT32 Usage()
{
    cerr << "This tool counts the number of dynamic instructions executed" << endl;
    cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
    return -1;
}

/* ===================================================================== */
/* Main                                                                  */
/* ===================================================================== */
/*   argc, argv are the entire command line: pin -t <toolname> -- ...    */
/* ===================================================================== */

int main(int argc, char * argv[])
{
    // Initialize pin
    if (PIN_Init(argc, argv)) return Usage();

    OutFile.open(KnobOutputFile.Value().c_str());

    // Register Instruction to be called to instrument instructions
    INS_AddInstrumentFunction(Instruction, 0);

    // Register Fini to be called when the application exits
    PIN_AddFiniFunction(Fini, 0);

    // Start the program, never returns
    PIN_StartProgram();

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#define DLL_EXPORT extern "C"

struct S {
	int n;
	uint8_t b;
};
class C {
public:
	int n;
	uint8_t b;
};

DLL_EXPORT void Func0()
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
}

DLL_EXPORT void Func1(int n)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  n = " << n << std::endl;
	n = 456;
	std::cout << "    => " << n << std::endl;
}

DLL_EXPORT void Func2(int *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func3(int *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func4(int n)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  n = " << n << std::endl;
	n = 456;
	std::cout << "    => " << n << std::endl;
}

DLL_EXPORT void Func5(int *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func6(S s)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  s.n = " << s.n << std::endl;
	s.n = 456;
	std::cout << "    => " << s.n << std::endl;
}

DLL_EXPORT void Func7(S *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 456;
		std::cout << "    => " << p->n << std::endl;
	}
}

DLL_EXPORT void Func8(S *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 456;
		std::cout << "    => " << p->n << std::endl;
	}
}

DLL_EXPORT void Func9(S s)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  s.n = " << s.n << std::endl;
	s.n = 456;
	std::cout << "    => " << s.n << std::endl;
}

DLL_EXPORT void Func10(S *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 678;
		std::cout << "    => " << p->n << std::endl;
		std::cout << "  p->b = " << (int)p->b << std::endl;
		p->b = 90;
		std::cout << "    => " << (int)p->b << std::endl;
	}
}

DLL_EXPORT void Func11(C *p)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 678;
		std::cout << "    => " << p->n << std::endl;
		std::cout << "  p->b = " << (int)p->b << std::endl;
		p->b = 90;
		std::cout << "    => " << (int)p->b << std::endl;
	}
}

DLL_EXPORT void Func12(C **pp)
{
	std::cout << "Native: " << __PRETTY_FUNCTION__ << std::endl;
	std::cout << "  pp = " << pp << std::endl;
	if (pp != nullptr) {
		C *p = *pp;
		std::cout << "  p = " << p << std::endl;
		if (p != nullptr) {
			std::cout << "  p->n = " << p->n << std::endl;
			p->n = 678;
			std::cout << "    => " << p->n << std::endl;
			std::cout << "  p->b = " << (int)p->b << std::endl;
			p->b = 90;
			std::cout << "    => " << (int)p->b << std::endl;
		}
	}
}

// Local variables:
// mode: c++
// coding: utf-8-with-signature
// c-file-style: "bsd"
// c-basic-offset: 4
// c-file-offsets: ((inextern-lang . 0)(innamespace . 0))
// indent-tabs-mode: t
// tab-width: 4
// End:
<commit_msg>Visual Studio 2012でビルドできるように変更しました。<commit_after>#include <cstdint>
#include <iostream>

#if defined(_MSC_VER)
#define DLL_EXPORT extern "C" _declspec(dllexport)
#else
#define DLL_EXPORT extern "C"
#endif

struct S {
	int n;
	uint8_t b;
};
class C {
public:
	int n;
	uint8_t b;
};

DLL_EXPORT void Func0()
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
}

DLL_EXPORT void Func1(int n)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  n = " << n << std::endl;
	n = 456;
	std::cout << "    => " << n << std::endl;
}

DLL_EXPORT void Func2(int *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func3(int *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func4(int n)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  n = " << n << std::endl;
	n = 456;
	std::cout << "    => " << n << std::endl;
}

DLL_EXPORT void Func5(int *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	std::cout << "  *p = " << *p << std::endl;
	if (p != nullptr) {
		*p = 456;
		std::cout << "    => " << *p << std::endl;
	}
}

DLL_EXPORT void Func6(S s)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  s.n = " << s.n << std::endl;
	s.n = 456;
	std::cout << "    => " << s.n << std::endl;
}

DLL_EXPORT void Func7(S *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 456;
		std::cout << "    => " << p->n << std::endl;
	}
}

DLL_EXPORT void Func8(S *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 456;
		std::cout << "    => " << p->n << std::endl;
	}
}

DLL_EXPORT void Func9(S s)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  s.n = " << s.n << std::endl;
	s.n = 456;
	std::cout << "    => " << s.n << std::endl;
}

DLL_EXPORT void Func10(S *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 678;
		std::cout << "    => " << p->n << std::endl;
		std::cout << "  p->b = " << (int)p->b << std::endl;
		p->b = 90;
		std::cout << "    => " << (int)p->b << std::endl;
	}
}

DLL_EXPORT void Func11(C *p)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  p = " << p << std::endl;
	if (p != nullptr) {
		std::cout << "  p->n = " << p->n << std::endl;
		p->n = 678;
		std::cout << "    => " << p->n << std::endl;
		std::cout << "  p->b = " << (int)p->b << std::endl;
		p->b = 90;
		std::cout << "    => " << (int)p->b << std::endl;
	}
}

DLL_EXPORT void Func12(C **pp)
{
	std::cout << "Native: " << __FUNCTION__ << std::endl;
	std::cout << "  pp = " << pp << std::endl;
	if (pp != nullptr) {
		C *p = *pp;
		std::cout << "  p = " << p << std::endl;
		if (p != nullptr) {
			std::cout << "  p->n = " << p->n << std::endl;
			p->n = 678;
			std::cout << "    => " << p->n << std::endl;
			std::cout << "  p->b = " << (int)p->b << std::endl;
			p->b = 90;
			std::cout << "    => " << (int)p->b << std::endl;
		}
	}
}

// Local variables:
// mode: c++
// coding: utf-8-with-signature
// c-file-style: "bsd"
// c-basic-offset: 4
// c-file-offsets: ((inextern-lang . 0)(innamespace . 0))
// indent-tabs-mode: t
// tab-width: 4
// End:
<|endoftext|>