<commit_before>// Simple binary search tree class for integers

#include "bst.h"

Bst::Bst() {
    root_ = nullptr;
}

Bst::~Bst() {
    // Recursively delete starting at root
    DeleteRecursive(root_);
}

void Bst::Insert(int val) {
    // Check if empty
    if (root_ == nullptr) {
        // Empty tree; insert at root
        root_ = new BstNode {val, nullptr, nullptr};
        return;
    }

    // Not empty; traverse to find insertion point
    BstNode* node = root_;
    while (true) {
        if (val <= node->data) {
            // Check if we can insert on left child
            if (node->left == nullptr) {
                // Insert and return
                node->left = new BstNode {val, nullptr, nullptr};
                return;
            } else {
                // Traverse down left child
                node = node->left;
            }
        } else {
            // Check if we can insert on right child
            if (node->right == nullptr) {
                // Insert and return
                node->right = new BstNode {val, nullptr, nullptr};
                return;
            } else {
                // Traverse down right child
                node = node->right;
            }
        }
    }
}

BstNode* Bst::Find(int val) {
    BstNode* node = root_;

    // Traverse down tree
    while (node != nullptr) {
        if (node->data == val) {
            // Found the value; return the node
            return node;
        } else if (val <= node->data) {
            // Traverse down left child
            node = node->left;
        } else {
            // Traverse down right child
            node = node->right;
        }
    }
    return nullptr;
}

void Bst::Remove(int val) {
    // TODO
}

BstNode* Bst::GetRoot() {
    return root_;
}

void Bst::DeleteRecursive(BstNode* node) {
    if (node == nullptr) {
        // Base case; return
        return;
    } else {
        // Recursively delete left and right children
        DeleteRecursive(node->left);
        DeleteRecursive(node->right);

        // Delete this node
        delete node;
    }
}
<commit_msg>Implement BST remove method<commit_after>// Simple binary search tree class for integers

#include "bst.h"

Bst::Bst() {
    root_ = nullptr;
}

Bst::~Bst() {
    // Recursively delete starting at root
    DeleteRecursive(root_);
}

void Bst::Insert(int val) {
    // Check if empty
    if (root_ == nullptr) {
        // Empty tree; insert at root
        root_ = new BstNode {val, nullptr, nullptr};
        return;
    }

    // Not empty; traverse to find insertion point
    BstNode* node = root_;
    while (true) {
        if (val <= node->data) {
            // Check if we can insert on left child
            if (node->left == nullptr) {
                // Insert and return
                node->left = new BstNode {val, nullptr, nullptr};
                return;
            } else {
                // Traverse down left child
                node = node->left;
            }
        } else {
            // Check if we can insert on right child
            if (node->right == nullptr) {
                // Insert and return
                node->right = new BstNode {val, nullptr, nullptr};
                return;
            } else {
                // Traverse down right child
                node = node->right;
            }
        }
    }
}

BstNode* Bst::Find(int val) {
    BstNode* node = root_;

    // Traverse down tree
    while (node != nullptr) {
        if (node->data == val) {
            // Found the value; return the node
            return node;
        } else if (val <= node->data) {
            // Traverse down left child
            node = node->left;
        } else {
            // Traverse down right child
            node = node->right;
        }
    }
    return nullptr;
}

void Bst::Remove(int val) {
    BstNode* node;
    BstNode* parent = nullptr;

    // Find node
    while (node != nullptr) {
        if (node->data == val) {
            // Found the node
            return node;
        } else if (val <= node->data) {
            // Traverse down left child
            parent = node;
            node = node->left;
        } else {
            // Traverse down right child
            parent = node;
            node = node->right;
        }
    }

    // Check if node has children
    if (!node->left && !node->right) {
        // No children; trivial delete
        if (!parent) {
            // Node was root; set root to nullptr
            root_ = nullptr;
        } else if (node == parent->left) {
            // Node was left child; update parent->left
            parent->left = nullptr;
        } else {
            // Node was right child; update parent->right
            parent->right = nullptr;
        }
        delete node;
    } else if (!node->left) {
        // Only has left children
        if (!parent) {
            // Node was root; set root to left children
            root_ = node->left;
        } else if (node == parent->left) {
            // Node was left child; update parent->left
            parent->left = node->left;
        } else {
            // Node was right child; update parent->right
            parent->right = node->left;
        }
        delete node;
    } else if (!node->right) {
        // Only has right children
        if (!parent) {
            // Node was root; set root to right children
            root_ = node->right;
        } else if (node == parent->left) {
            // Node was left child; update parent->left
            parent->left = node->right;
        } else {
            // Node was right child; update parent->right
            parent->right = node->right;
        }
        delete node;
    } else {
        // Has left and right children; complex delete

        // Find inorder successor to node being deleted (smallest value in right subtree)
        BstNode* successor = node->right;
        BstNode* parent_successor = node;
        while (successor->left) {
            parent_successor = successor;
            successor = successor->left;
        }

        // Handle successor's right subtree if it exists
        if (successor->right) {
            parent_successor->left = successor->right;
        }

        // Replace node we're deleting with the successor
        successor->right = node->right;
        successor->left = node->left;
        delete node;
    }
}

BstNode* Bst::GetRoot() {
    return root_;
}

void Bst::DeleteRecursive(BstNode* node) {
    if (node == nullptr) {
        // Base case; return
        return;
    } else {
        // Recursively delete left and right children
        DeleteRecursive(node->left);
        DeleteRecursive(node->right);

        // Delete this node
        delete node;
    }
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QDateTime>

#include <buildtime.h>

#include "data/models.h"
#include "data/loader.h"
#include "data/vptr.h"
#include "gui/mainwindow.h"

QTextStream *out = 0;
bool logToFile = false;
bool verbose = false;
bool makeScreenshot = false;

void logOutput( QtMsgType type, const char *msg )
{
    QString filedate = QDateTime::currentDateTime().toString( "yyyy.MM.dd hh:mm:ss:zzz" );
    QString debugdate = QDateTime::currentDateTime().toString( "hh:mm:ss:zzz" );

    switch (type)
    {
    case QtDebugMsg:
        debugdate += " [D]";
        break;
    case QtWarningMsg:
        debugdate += " [W]";
        break;
    case QtCriticalMsg:
        debugdate += " [C]";
        break;
    case QtFatalMsg:
        debugdate += " [F]";
        break;
    }
    if ( verbose )
    {
        (*out) << debugdate << " " << msg << endl;
    }
    if ( logToFile )
    {
        QFile outFile("log.txt");
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream ts(&outFile);
        ts << filedate << " " << msg << endl;
    }

    if (QtFatalMsg == type)
    {
        abort();
    }
}

void noOutput(QtMsgType type, const char *msg) {}

int main( int argc, char *argv[] )
{
    QString hg = HGTIP;
    hg.remove( ";" );
    hg.remove( "changeset:" );
    hg.replace( " ","" );

    qDebug() << "brainGL development version" << hg << BUILDDATE << BUILDTIME;
    qDebug() << "(c) 2012, 2013 Ralph Schurade, Joachim Boettger";
    qDebug() << "Submit suggestions, feature requests, bug reports to https://code.google.com/p/braingl/";

    QApplication app( argc, argv );

    QCoreApplication::setOrganizationDomain( "braingl.de" );
	QCoreApplication::setOrganizationName( "MPI_CBS" );
	QCoreApplication::setApplicationName( "braingl" );
	QCoreApplication::setApplicationVersion( "0.8.1" );

    Q_INIT_RESOURCE( resources );

    QStringList args = app.arguments();

    bool debug = false;
    bool resetSettings = false;
    bool runScript = false;

    for ( int i = 1; i < args.size(); ++i )
    {
        if ( args.at( i ) == "-v" )
        {
            verbose = true;
        }
        if ( args.at( i ) == "-d" )
        {
            debug = true;
        }
        if ( args.at( i ) == "-l" )
        {
            logToFile = true;
        }
        if ( args.at( i ) == "-r" )
        {
            // reset saved settings
            resetSettings = true;
        }
        if ( args.at( i ) == "-s" )
        {
            makeScreenshot = true;
        }
        if ( args.at( i ) == "-rs" )
        {
            runScript = true;
        }

        if ( args.at( i ) == "-h" || args.at( i ) == "?" )
        {
            qDebug() << "Command line options:";
            qDebug() << "-h : displays this message";
            qDebug() << "-v : toggles verbose mode, warning: this will spam your console with messages";
            qDebug() << "-l : logs debug messages to text file";
            qDebug() << "-r : resets saved settings";
            qDebug() << "-s : makes a screenshot and quits";
            qDebug() << "-rs : runs the loaded script";
            qDebug() << "---";

        }
    }
    qInstallMsgHandler( noOutput );
    out = new QTextStream( stdout );
    qInstallMsgHandler( logOutput );

#ifdef __DEBUG__
    debug = true;
#endif

    Models::init();

    MainWindow mainWin( debug, resetSettings );
    mainWin.show();

    for ( int i = 1; i < args.size(); ++i )
    {
        mainWin.load( args.at( i ) );
    }

    if ( runScript )
    {
        mainWin.runScript();
    }

    if ( makeScreenshot )
    {
        mainWin.screenshot();
        exit( 0 );
    }

    return app.exec();
}
<commit_msg>command line parameters fpor initial slice positions<commit_after>#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QDateTime>

#include <buildtime.h>

#include "data/models.h"
#include "data/loader.h"
#include "data/vptr.h"
#include "gui/mainwindow.h"

QTextStream *out = 0;
bool logToFile = false;
bool verbose = false;
bool makeScreenshot = false;

void logOutput( QtMsgType type, const char *msg )
{
    QString filedate = QDateTime::currentDateTime().toString( "yyyy.MM.dd hh:mm:ss:zzz" );
    QString debugdate = QDateTime::currentDateTime().toString( "hh:mm:ss:zzz" );

    switch (type)
    {
    case QtDebugMsg:
        debugdate += " [D]";
        break;
    case QtWarningMsg:
        debugdate += " [W]";
        break;
    case QtCriticalMsg:
        debugdate += " [C]";
        break;
    case QtFatalMsg:
        debugdate += " [F]";
        break;
    }
    if ( verbose )
    {
        (*out) << debugdate << " " << msg << endl;
    }
    if ( logToFile )
    {
        QFile outFile("log.txt");
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream ts(&outFile);
        ts << filedate << " " << msg << endl;
    }

    if (QtFatalMsg == type)
    {
        abort();
    }
}

void noOutput(QtMsgType type, const char *msg) {}

int main( int argc, char *argv[] )
{
    QString hg = HGTIP;
    hg.remove( ";" );
    hg.remove( "changeset:" );
    hg.replace( " ","" );

    qDebug() << "brainGL development version" << hg << BUILDDATE << BUILDTIME;
    qDebug() << "(c) 2012, 2013 Ralph Schurade, Joachim Boettger";
    qDebug() << "Submit suggestions, feature requests, bug reports to https://code.google.com/p/braingl/";

    QApplication app( argc, argv );

    QCoreApplication::setOrganizationDomain( "braingl.de" );
	QCoreApplication::setOrganizationName( "MPI_CBS" );
	QCoreApplication::setApplicationName( "braingl" );
	QCoreApplication::setApplicationVersion( "0.8.1" );

    Q_INIT_RESOURCE( resources );

    QStringList args = app.arguments();

    bool debug = false;
    bool resetSettings = false;
    bool runScript = false;

    int x = -1;
    int y = -1;
    int z = -1;

    for ( int i = 1; i < args.size(); ++i )
    {
        if ( args.at( i ) == "-v" )
        {
            verbose = true;
        }
        if ( args.at( i ) == "-d" )
        {
            debug = true;
        }
        if ( args.at( i ) == "-l" )
        {
            logToFile = true;
        }
        if ( args.at( i ) == "-r" )
        {
            // reset saved settings
            resetSettings = true;
        }
        if ( args.at( i ) == "-s" )
        {
            makeScreenshot = true;
        }
        if ( args.at( i ) == "-rs" )
        {
            runScript = true;
        }

        if ( args.at( i ) == "-x" )
        {
            bool ok = false;
            if ( args.size() > i + 1 )
            {
                int tmp = args.at( i + 1 ).toInt( &ok );
                if ( ok )
                {
                    x = tmp;
                }
            }
        }

        if ( args.at( i ) == "-y" )
        {
            bool ok = false;
            if ( args.size() > i + 1 )
            {
                int tmp = args.at( i + 1 ).toInt( &ok );
                if ( ok )
                {
                    y = tmp;
                }
            }
        }

        if ( args.at( i ) == "-z" )
        {
            bool ok = false;
            if ( args.size() > i + 1 )
            {
                int tmp = args.at( i + 1 ).toInt( &ok );
                if ( ok )
                {
                    z = tmp;
                }
            }
        }

        if ( args.at( i ) == "-h" || args.at( i ) == "?" )
        {
            qDebug() << "Command line options:";
            qDebug() << "-h : displays this message";
            qDebug() << "-v : toggles verbose mode, warning: this will spam your console with messages";
            qDebug() << "-l : logs debug messages to text file";
            qDebug() << "-r : resets saved settings";
            qDebug() << "-s : makes a screenshot and quits";
            qDebug() << "-rs : runs the loaded script";
            qDebug() << "---";

        }
    }
    qInstallMsgHandler( noOutput );
    out = new QTextStream( stdout );
    qInstallMsgHandler( logOutput );

#ifdef __DEBUG__
    debug = true;
#endif

    Models::init();

    MainWindow mainWin( debug, resetSettings );
    mainWin.show();

    for ( int i = 1; i < args.size(); ++i )
    {
        mainWin.load( args.at( i ) );
    }

    if ( x != - 1 )
    {
        Models::setGlobal( Fn::Property::G_SAGITTAL, x );
    }

    if ( y != - 1 )
    {
        Models::setGlobal( Fn::Property::G_CORONAL, y );
    }

    if ( z != - 1 )
    {
        Models::setGlobal( Fn::Property::G_AXIAL, z );
    }

    if ( runScript )
    {
        mainWin.runScript();
    }

    if ( makeScreenshot )
    {
        mainWin.screenshot();
        exit( 0 );
    }

    return app.exec();
}
<|endoftext|>


<commit_before>/*************************************************
* Utility Functions Source File                  *
* (C) 1999-2007 Jack Lloyd                       *
*************************************************/

#include <botan/util.h>
#include <botan/bit_ops.h>
#include <algorithm>
#include <cmath>

namespace Botan {

/*************************************************
* Round up n to multiple of align_to             *
*************************************************/
u32bit round_up(u32bit n, u32bit align_to)
   {
   if(n % align_to || n == 0)
      n += align_to - (n % align_to);
   return n;
   }

/*************************************************
* Round down n to multiple of align_to           *
*************************************************/
u32bit round_down(u32bit n, u32bit align_to)
   {
   return (n - (n % align_to));
   }

/*************************************************
* Return the work required for solving DL        *
*************************************************/
u32bit dl_work_factor(u32bit n_bits)
   {
   const u32bit MIN_ESTIMATE = 64;

   if(n_bits < 32)
      return 0;

   const double log_x = n_bits / 1.44;

   const double strength =
      2.76 * std::pow(log_x, 1.0/3.0) * std::pow(std::log(log_x), 2.0/3.0);

   if(strength > MIN_ESTIMATE)
      return static_cast<u32bit>(strength);
   return MIN_ESTIMATE;
   }

/*************************************************
* Estimate the entropy of the buffer             *
*************************************************/
u32bit entropy_estimate(const byte buffer[], u32bit length)
   {
   if(length <= 4)
      return 0;

   u32bit estimate = 0;
   byte last = 0, last_delta = 0, last_delta2 = 0;

   for(u32bit j = 0; j != length; ++j)
      {
      byte delta = last ^ buffer[j];
      last = buffer[j];

      byte delta2 = delta ^ last_delta;
      last_delta = delta;

      byte delta3 = delta2 ^ last_delta2;
      last_delta2 = delta2;

      byte min_delta = delta;
      if(min_delta > delta2) min_delta = delta2;
      if(min_delta > delta3) min_delta = delta3;

      estimate += hamming_weight(min_delta);
      }

   return (estimate / 2);
   }

}
<commit_msg>Rewrite dl_work_factor using a lookup table with data from RFC 3526, "More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)", which removes Botan's dependency on standard math library (which can be a big deal on embedded systems, and it seemed silly to have just a single function cause us to pull in potentially all of libm)<commit_after>/*************************************************
* Utility Functions Source File                  *
* (C) 1999-2007 Jack Lloyd                       *
*************************************************/

#include <botan/util.h>
#include <botan/bit_ops.h>
#include <algorithm>

namespace Botan {

/*************************************************
* Round up n to multiple of align_to             *
*************************************************/
u32bit round_up(u32bit n, u32bit align_to)
   {
   if(n % align_to || n == 0)
      n += align_to - (n % align_to);
   return n;
   }

/*************************************************
* Round down n to multiple of align_to           *
*************************************************/
u32bit round_down(u32bit n, u32bit align_to)
   {
   return (n - (n % align_to));
   }

/*************************************************
* Choose the exponent size for a DL group
*************************************************/
u32bit dl_work_factor(u32bit bits)
   {
   /*
   These values were taken from RFC 3526
   */
   if(bits <= 1536)
      return 90;
   else if(bits <= 2048)
      return 110;
   else if(bits <= 3072)
      return 130;
   else if(bits <= 4096)
      return 150;
   else if(bits <= 6144)
      return 170;
   else if(bits <= 8192)
      return 190;
   return 256;
   }

/*************************************************
* Estimate the entropy of the buffer             *
*************************************************/
u32bit entropy_estimate(const byte buffer[], u32bit length)
   {
   if(length <= 4)
      return 0;

   u32bit estimate = 0;
   byte last = 0, last_delta = 0, last_delta2 = 0;

   for(u32bit j = 0; j != length; ++j)
      {
      byte delta = last ^ buffer[j];
      last = buffer[j];

      byte delta2 = delta ^ last_delta;
      last_delta = delta;

      byte delta3 = delta2 ^ last_delta2;
      last_delta2 = delta2;

      byte min_delta = delta;
      if(min_delta > delta2) min_delta = delta2;
      if(min_delta > delta3) min_delta = delta3;

      estimate += hamming_weight(min_delta);
      }

   return (estimate / 2);
   }

}
<|endoftext|>


<commit_before>#include <string>

/*
public class TennisGame4 implements TennisGame {

    int serverScore;
    int receiverScore;
    String server;
    String receiver;

    public TennisGame4(String player1, String player2) {
        this.server = player1;
        this.receiver = player2;
    }

    @java.lang.Override
    public void wonPoint(String playerName) {
        if (server.equals(playerName))
            this.serverScore += 1;
        else
            this.receiverScore += 1;
    }

    @java.lang.Override
    public String getScore() {
        TennisResult result = new Deuce(
                this, new GameServer(
                        this, new GameReceiver(
                                this, new AdvantageServer(
                                        this, new AdvantageReceiver(
                                                this, new DefaultResult(this)))))).getResult();
        return result.format();
    }

    boolean receiverHasAdvantage() {
        return receiverScore >= 4 && (receiverScore - serverScore) == 1;
    }

    boolean serverHasAdvantage() {
        return serverScore >= 4 && (serverScore - receiverScore) == 1;
    }

    boolean receiverHasWon() {
        return receiverScore >= 4 && (receiverScore - serverScore) >= 2;
    }

    boolean serverHasWon() {
        return serverScore >= 4 && (serverScore - receiverScore) >= 2;
    }

    boolean isDeuce() {
        return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore);
    }
}

class TennisResult {
    String serverScore;
    String receiverScore;

    TennisResult(String serverScore, String receiverScore) {
        this.serverScore = serverScore;
        this.receiverScore = receiverScore;
    }

    String format() {
        if ("".equals(this.receiverScore))
            return this.serverScore;
        if (serverScore.equals(receiverScore))
            return serverScore + "-All";
        return this.serverScore + "-" + this.receiverScore;
    }
}

interface ResultProvider {
    TennisResult getResult();
}

class Deuce implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public Deuce(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.isDeuce())
            return new TennisResult("Deuce", "");
        return this.nextResult.getResult();
    }
}

class GameServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasWon())
            return new TennisResult("Win for " + game.server, "");
        return this.nextResult.getResult();
    }
}

class GameReceiver implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasWon())
            return new TennisResult("Win for " + game.receiver, "");
        return this.nextResult.getResult();
    }t
}

class AdvantageServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasAdvantage())
            return new TennisResult("Advantage " + game.server, "");
        return this.nextResult.getResult();
    }
}

class AdvantageReceiver implements ResultProvider {

    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasAdvantage())
            return new TennisResult("Advantage " + game.receiver, "");
        return this.nextResult.getResult();
    }
}

class DefaultResult implements ResultProvider {

    private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"};

    private final TennisGame4 game;

    public DefaultResult(TennisGame4 game) {
        this.game = game;
    }

    @Override
    public TennisResult getResult() {
        return new TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }
}
 */

class TennisGame4 {
public:
    int serverScore, receiverScore;
};

class TennisResult {
public:
    TennisResult(std::string serverScore, std::string receiverScore) {
        this->serverScore = serverScore;
        this->receiverScore = receiverScore;
    }

    std::string format() {
        if ("" == this->receiverScore)
            return this->serverScore;
        if (serverScore == this->receiverScore)
            return serverScore + "-All";
        return this->serverScore + "-" + this->receiverScore;
    }

private:
    std::string serverScore;
    std::string receiverScore;
};

class ResultProvider {
public:
    virtual TennisResult getResult() = 0;
    virtual ~ResultProvider() {}
};

//class Deuce implements ResultProvider {
//class GameServer implements ResultProvider {
//class GameReceiver implements ResultProvider {
//class AdvantageServer implements ResultProvider {
//class AdvantageReceiver implements ResultProvider {

class DefaultResult : ResultProvider {
public:
    DefaultResult(TennisGame4& game) : game(game) { }

    TennisResult getResult() override {
        return TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }

private:
    static const std::string scores[];
    const TennisGame4& game;
};

const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"};

// tennis3 function below (TODO: re-implement using class mess above!)
/* relevant inspiration from Java Unit Test
    public void checkAllScores(TennisGame game) {
        int highestScore = Math.max(this.player1Score, this.player2Score);
        for (int i = 0; i < highestScore; i++) {
            if (i < this.player1Score)
                game.wonPoint("player1");
            if (i < this.player2Score)
                game.wonPoint("player2");
        }
        assertEquals(this.expectedScore, game.getScore());
    }
*/
const std::string tennis_score(int p1, int p2) {
    std::string s;
    std::string p1N = "player1";
    std::string p2N = "player2";
    if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) {
        std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"};
        s = p[p1];
        return (p1 == p2) ? s + "-All" : s + "-" + p[p2];
    } else {
        if (p1 == p2)
            return "Deuce";
        s = p1 > p2 ? p1N : p2N;
        return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s;
    }
}<commit_msg>Apply some clang suggestions<commit_after>#include <string>

/*
public class TennisGame4 implements TennisGame {

    int serverScore;
    int receiverScore;
    String server;
    String receiver;

    public TennisGame4(String player1, String player2) {
        this.server = player1;
        this.receiver = player2;
    }

    @java.lang.Override
    public void wonPoint(String playerName) {
        if (server.equals(playerName))
            this.serverScore += 1;
        else
            this.receiverScore += 1;
    }

    @java.lang.Override
    public String getScore() {
        TennisResult result = new Deuce(
                this, new GameServer(
                        this, new GameReceiver(
                                this, new AdvantageServer(
                                        this, new AdvantageReceiver(
                                                this, new DefaultResult(this)))))).getResult();
        return result.format();
    }

    boolean receiverHasAdvantage() {
        return receiverScore >= 4 && (receiverScore - serverScore) == 1;
    }

    boolean serverHasAdvantage() {
        return serverScore >= 4 && (serverScore - receiverScore) == 1;
    }

    boolean receiverHasWon() {
        return receiverScore >= 4 && (receiverScore - serverScore) >= 2;
    }

    boolean serverHasWon() {
        return serverScore >= 4 && (serverScore - receiverScore) >= 2;
    }

    boolean isDeuce() {
        return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore);
    }
}

class TennisResult {
    String serverScore;
    String receiverScore;

    TennisResult(String serverScore, String receiverScore) {
        this.serverScore = serverScore;
        this.receiverScore = receiverScore;
    }

    String format() {
        if ("".equals(this.receiverScore))
            return this.serverScore;
        if (serverScore.equals(receiverScore))
            return serverScore + "-All";
        return this.serverScore + "-" + this.receiverScore;
    }
}

interface ResultProvider {
    TennisResult getResult();
}

class Deuce implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public Deuce(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.isDeuce())
            return new TennisResult("Deuce", "");
        return this.nextResult.getResult();
    }
}

class GameServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasWon())
            return new TennisResult("Win for " + game.server, "");
        return this.nextResult.getResult();
    }
}

class GameReceiver implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public GameReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasWon())
            return new TennisResult("Win for " + game.receiver, "");
        return this.nextResult.getResult();
    }t
}

class AdvantageServer implements ResultProvider {
    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageServer(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.serverHasAdvantage())
            return new TennisResult("Advantage " + game.server, "");
        return this.nextResult.getResult();
    }
}

class AdvantageReceiver implements ResultProvider {

    private final TennisGame4 game;
    private final ResultProvider nextResult;

    public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) {
        this.game = game;
        this.nextResult = nextResult;
    }

    @Override
    public TennisResult getResult() {
        if (game.receiverHasAdvantage())
            return new TennisResult("Advantage " + game.receiver, "");
        return this.nextResult.getResult();
    }
}

class DefaultResult implements ResultProvider {

    private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"};

    private final TennisGame4 game;

    public DefaultResult(TennisGame4 game) {
        this.game = game;
    }

    @Override
    public TennisResult getResult() {
        return new TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }
}
 */

class TennisGame4 {
public:
    int serverScore, receiverScore;
};

class TennisResult {
public:
    TennisResult(std::string serverScore, std::string receiverScore) {
        this->serverScore = serverScore;
        this->receiverScore = receiverScore;
    }

    std::string format() {
        if ("" == this->receiverScore)
            return this->serverScore;
        if (serverScore == this->receiverScore)
            return serverScore + "-All";
        return this->serverScore + "-" + this->receiverScore;
    }

private:
    std::string serverScore;
    std::string receiverScore;
};

class ResultProvider {
public:
    virtual TennisResult getResult() = 0;
    virtual ~ResultProvider() = default;
};

//class Deuce implements ResultProvider {
//class GameServer implements ResultProvider {
//class GameReceiver implements ResultProvider {
//class AdvantageServer implements ResultProvider {
//class AdvantageReceiver implements ResultProvider {

class DefaultResult : ResultProvider {
public:
    explicit DefaultResult(TennisGame4& game) : game(game) { }

    TennisResult getResult() override {
        return TennisResult(scores[game.serverScore], scores[game.receiverScore]);
    }

private:
    static const std::string scores[];
    const TennisGame4& game;
};

const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"};

// tennis3 function below (TODO: re-implement using class mess above!)
/* relevant inspiration from Java Unit Test
    public void checkAllScores(TennisGame game) {
        int highestScore = Math.max(this.player1Score, this.player2Score);
        for (int i = 0; i < highestScore; i++) {
            if (i < this.player1Score)
                game.wonPoint("player1");
            if (i < this.player2Score)
                game.wonPoint("player2");
        }
        assertEquals(this.expectedScore, game.getScore());
    }
*/
const std::string tennis_score(int p1, int p2) {
    std::string s;
    std::string p1N = "player1";
    std::string p2N = "player2";
    if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) {
        std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"};
        s = p[p1];
        return (p1 == p2) ? s + "-All" : s + "-" + p[p2];
    } else {
        if (p1 == p2)
            return "Deuce";
        s = p1 > p2 ? p1N : p2N;
        return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s;
    }
}<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file TimeCalibLoader.cpp
 */

#include "TimeCalibLoader.h"
#include "TimeCalibTools.h"
#include "JPetGeomMapping/JPetGeomMapping.h"
#include <JPetParamManager/JPetParamManager.h>

TimeCalibLoader::TimeCalibLoader(const char* name):
  JPetUserTask(name) {}

TimeCalibLoader::~TimeCalibLoader() {}

bool TimeCalibLoader::init()
{
  fOutputEvents = new JPetTimeWindow("JPetSigCh");

  auto calibFile =  std::string("timeCalib.txt");
  if (fParams.getOptions().count(fConfigFileParamKey)) {
    calibFile = boost::any_cast<std::string>(fParams.getOptions().at(fConfigFileParamKey));
  }
  assert(fParamManager);
  JPetGeomMapping mapper(fParamManager->getParamBank());
  auto tombMap = mapper.getTOMBMapping();
  fTimeCalibration = TimeCalibTools::loadTimeCalibration(calibFile, tombMap);
  if (fTimeCalibration.empty()) {
    ERROR("Time calibration seems to be empty");
  }

  return true;
}

bool TimeCalibLoader::exec()
{
  if (auto oldTimeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {

    auto n = oldTimeWindow->getNumberOfEvents();
    for(uint i=0;i<n;++i){

      JPetSigCh sigCh = dynamic_cast<const JPetSigCh&>(oldTimeWindow->operator[](i));
    /// Calibration time is ns so we should change it to ps, cause all the time is in ps.
      sigCh.setValue(sigCh.getValue() + 1000. * TimeCalibTools::getTimeCalibCorrection(fTimeCalibration, sigCh.getTOMBChannel().getChannel()));
      fOutputEvents->add<JPetSigCh>(sigCh);
    }
  }else{
    return false;
  }
  return true;
}

bool TimeCalibLoader::terminate()
{
  return true;
}

<commit_msg>Remove use of obsolete variables<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file TimeCalibLoader.cpp
 */

#include "TimeCalibLoader.h"
#include "TimeCalibTools.h"
#include "JPetGeomMapping/JPetGeomMapping.h"
#include <JPetParamManager/JPetParamManager.h>

TimeCalibLoader::TimeCalibLoader(const char* name):
  JPetUserTask(name) {}

TimeCalibLoader::~TimeCalibLoader() {}

bool TimeCalibLoader::init()
{
  fOutputEvents = new JPetTimeWindow("JPetSigCh");

  auto calibFile =  std::string("timeCalib.txt");
  if (fParams.getOptions().count(fConfigFileParamKey)) {
    calibFile = boost::any_cast<std::string>(fParams.getOptions().at(fConfigFileParamKey));
  }

  JPetGeomMapping mapper(getParamBank());
  auto tombMap = mapper.getTOMBMapping();
  fTimeCalibration = TimeCalibTools::loadTimeCalibration(calibFile, tombMap);
  if (fTimeCalibration.empty()) {
    ERROR("Time calibration seems to be empty");
  }

  return true;
}

bool TimeCalibLoader::exec()
{
  if (auto oldTimeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {

    auto n = oldTimeWindow->getNumberOfEvents();
    for(uint i=0;i<n;++i){

      JPetSigCh sigCh = dynamic_cast<const JPetSigCh&>(oldTimeWindow->operator[](i));
    /// Calibration time is ns so we should change it to ps, cause all the time is in ps.
      sigCh.setValue(sigCh.getValue() + 1000. * TimeCalibTools::getTimeCalibCorrection(fTimeCalibration, sigCh.getTOMBChannel().getChannel()));
      fOutputEvents->add<JPetSigCh>(sigCh);
    }
  }else{
    return false;
  }
  return true;
}

bool TimeCalibLoader::terminate()
{
  return true;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gsub.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:24:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library 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 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.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "sft.h"
#undef true
#undef false

#include "gsub.h"

#include <vector>
#include <map>
#include <algorithm>

typedef sal_uInt32 ULONG;
typedef sal_uInt16 USHORT;
typedef sal_uInt8 FT_Byte;

typedef std::map<USHORT,USHORT> GlyphSubstitution;

inline long NEXT_Long( const unsigned char* &p )
{
    long nVal = (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3];
    p += 4;
    return nVal;
}

inline USHORT NEXT_UShort( const unsigned char* &p )
{
    USHORT nVal = (p[0]<<8) + p[1];
    p += 2;
    return nVal;
}

#define MKTAG(s) ((((((s[0]<<8)+s[1])<<8)+s[2])<<8)+s[3])

int ReadGSUB( struct _TrueTypeFont* pTTFile,
    int nRequestedScript, int nRequestedLangsys )
{
    const FT_Byte* pGsubBase = (FT_Byte*)pTTFile->tables[ O_gsub ];
    if( !pGsubBase )
        return -1;

    // #129682# check offsets inside GSUB table
    const FT_Byte* pGsubLimit = pGsubBase + pTTFile->tlens[ O_gsub ];

    // parse GSUB header
    const FT_Byte* pGsubHeader = pGsubBase;
    const ULONG nVersion            = NEXT_Long( pGsubHeader );
    const USHORT nOfsScriptList     = NEXT_UShort( pGsubHeader );
    const USHORT nOfsFeatureTable   = NEXT_UShort( pGsubHeader );
    const USHORT nOfsLookupList     = NEXT_UShort( pGsubHeader );

    // sanity check the GSUB header
    if( nVersion != 0x00010000 )
        if( nVersion != 0x00001000 )    // workaround for SunBatang etc.
            return -1;                  // unknown format or broken

    typedef std::vector<ULONG> ReqFeatureTagList;
    ReqFeatureTagList aReqFeatureTagList;

    aReqFeatureTagList.push_back( MKTAG("vert") );

    typedef std::vector<USHORT> UshortList;
    UshortList aFeatureIndexList;
    UshortList aFeatureOffsetList;

    // parse Script Table
    const FT_Byte* pScriptHeader = pGsubBase + nOfsScriptList;
    const USHORT nCntScript = NEXT_UShort( pScriptHeader );
    if( pGsubLimit < pScriptHeader + 6 * nCntScript )
        return false;
    for( USHORT nScriptIndex = 0; nScriptIndex < nCntScript; ++nScriptIndex )
    {
        const ULONG nTag            = NEXT_Long( pScriptHeader ); // e.g. hani/arab/kana/hang
        const USHORT nOfsScriptTable= NEXT_UShort( pScriptHeader );
        if( (nTag != (USHORT)nRequestedScript) && (nRequestedScript != 0) )
            continue;

        const FT_Byte* pScriptTable     = pGsubBase + nOfsScriptList + nOfsScriptTable;
        if( pGsubLimit < pScriptTable + 4 )
            return false;
        const USHORT nDefaultLangsysOfs = NEXT_UShort( pScriptTable );
        const USHORT nCntLangSystem     = NEXT_UShort( pScriptTable );
        USHORT nLangsysOffset = 0;
        if( pGsubLimit < pScriptTable + 6 * nCntLangSystem )
            return false;
        for( USHORT nLangsysIndex = 0; nLangsysIndex < nCntLangSystem; ++nLangsysIndex )
        {
            const ULONG nInnerTag = NEXT_Long( pScriptTable );    // e.g. KOR/ZHS/ZHT/JAN
            const USHORT nOffset= NEXT_UShort( pScriptTable );
            if( (nInnerTag != (USHORT)nRequestedLangsys) && (nRequestedLangsys != 0) )
                continue;
            nLangsysOffset = nOffset;
            break;
        }

        if( (nDefaultLangsysOfs != 0) && (nDefaultLangsysOfs != nLangsysOffset) )
        {
            const FT_Byte* pLangSys = pGsubBase + nOfsScriptList + nOfsScriptTable + nDefaultLangsysOfs;
            if( pGsubLimit < pLangSys + 6 )
                return false;
            /*const USHORT nLookupOrder   =*/ NEXT_UShort( pLangSys );
            const USHORT nReqFeatureIdx = NEXT_UShort( pLangSys );
            const USHORT nCntFeature    = NEXT_UShort( pLangSys );
            if( pGsubLimit < pLangSys + 2 * nCntFeature )
                return false;
            aFeatureIndexList.push_back( nReqFeatureIdx );
            for( USHORT i = 0; i < nCntFeature; ++i )
            {
                const USHORT nFeatureIndex = NEXT_UShort( pLangSys );
                aFeatureIndexList.push_back( nFeatureIndex );
            }
        }

        if( nLangsysOffset != 0 )
        {
            const FT_Byte* pLangSys = pGsubBase + nOfsScriptList + nOfsScriptTable + nLangsysOffset;
            if( pGsubLimit < pLangSys + 6 )
                return false;
            /*const USHORT nLookupOrder   =*/ NEXT_UShort( pLangSys );
            const USHORT nReqFeatureIdx = NEXT_UShort( pLangSys );
            const USHORT nCntFeature    = NEXT_UShort( pLangSys );
            if( pGsubLimit < pLangSys + 2 * nCntFeature )
                return false;
            aFeatureIndexList.push_back( nReqFeatureIdx );
            for( USHORT i = 0; i < nCntFeature; ++i )
            {
                const USHORT nFeatureIndex = NEXT_UShort( pLangSys );
                aFeatureIndexList.push_back( nFeatureIndex );
            }
        }
    }

    if( !aFeatureIndexList.size() )
        return true;

    UshortList aLookupIndexList;
    UshortList aLookupOffsetList;

    // parse Feature Table
    const FT_Byte* pFeatureHeader = pGsubBase + nOfsFeatureTable;
    if( pGsubLimit < pFeatureHeader + 2 )
          return false;
    const USHORT nCntFeature = NEXT_UShort( pFeatureHeader );
    if( pGsubLimit < pFeatureHeader + 6 * nCntFeature )
          return false;
    for( USHORT nFeatureIndex = 0; nFeatureIndex < nCntFeature; ++nFeatureIndex )
    {
        const ULONG nTag    = NEXT_Long( pFeatureHeader ); // e.g. locl/vert/trad/smpl/liga/fina/...
        const USHORT nOffset= NEXT_UShort( pFeatureHeader );

        // feature (required && (requested || available))?
        if( (aFeatureIndexList[0] != nFeatureIndex)
            &&  (!std::count( aReqFeatureTagList.begin(), aReqFeatureTagList.end(), nTag))
            ||  (!std::count( aFeatureIndexList.begin(), aFeatureIndexList.end(), nFeatureIndex) ) )
            continue;

        const FT_Byte* pFeatureTable = pGsubBase + nOfsFeatureTable + nOffset;
        if( pGsubLimit < pFeatureTable + 2 )
            return false;
        const USHORT nCntLookups = NEXT_UShort( pFeatureTable );
        if( pGsubLimit < pFeatureTable + 2 * nCntLookups )
            return false;
        for( USHORT i = 0; i < nCntLookups; ++i )
        {
            const USHORT nLookupIndex = NEXT_UShort( pFeatureTable );
            aLookupIndexList.push_back( nLookupIndex );
        }
        if( nCntLookups == 0 ) //### hack needed by Mincho/Gothic/Mingliu/Simsun/...
            aLookupIndexList.push_back( 0 );
    }

    // parse Lookup List
    const FT_Byte* pLookupHeader = pGsubBase + nOfsLookupList;
    if( pGsubLimit < pLookupHeader + 2 )
        return false;
    const USHORT nCntLookupTable = NEXT_UShort( pLookupHeader );
    if( pGsubLimit < pLookupHeader + 2 * nCntLookupTable )
        return false;
    for( USHORT nLookupIdx = 0; nLookupIdx < nCntLookupTable; ++nLookupIdx )
    {
        const USHORT nOffset = NEXT_UShort( pLookupHeader );
        if( std::count( aLookupIndexList.begin(), aLookupIndexList.end(), nLookupIdx ) )
            aLookupOffsetList.push_back( nOffset );
    }

    UshortList::const_iterator it = aLookupOffsetList.begin();
    for(; it != aLookupOffsetList.end(); ++it )
    {
        const USHORT nOfsLookupTable = *it;
        const FT_Byte* pLookupTable = pGsubBase + nOfsLookupList + nOfsLookupTable;
        if( pGsubLimit < pLookupTable + 6 )
            return false;
        const USHORT eLookupType        = NEXT_UShort( pLookupTable );
        /*const USHORT eLookupFlag        =*/ NEXT_UShort( pLookupTable );
        const USHORT nCntLookupSubtable = NEXT_UShort( pLookupTable );

        // TODO: switch( eLookupType )
        if( eLookupType != 1 )  // TODO: once we go beyond SingleSubst
            continue;

        if( pGsubLimit < pLookupTable + 2 * nCntLookupSubtable )
            return false;
        for( USHORT nSubTableIdx = 0; nSubTableIdx < nCntLookupSubtable; ++nSubTableIdx )
        {
            const USHORT nOfsSubLookupTable = NEXT_UShort( pLookupTable );
            const FT_Byte* pSubLookup = pGsubBase + nOfsLookupList + nOfsLookupTable + nOfsSubLookupTable;
            if( pGsubLimit < pSubLookup + 6 )
                return false;
            const USHORT nFmtSubstitution   = NEXT_UShort( pSubLookup );
            const USHORT nOfsCoverage       = NEXT_UShort( pSubLookup );

            typedef std::pair<USHORT,USHORT> GlyphSubst;
            typedef std::vector<GlyphSubst> SubstVector;
            SubstVector aSubstVector;

            const FT_Byte* pCoverage    = pGsubBase
                + nOfsLookupList + nOfsLookupTable + nOfsSubLookupTable + nOfsCoverage;
            if( pGsubLimit < pCoverage + 4 )
                return false;
            const USHORT nFmtCoverage   = NEXT_UShort( pCoverage );
            switch( nFmtCoverage )
            {
                case 1:         // Coverage Format 1
                {
                    const USHORT nCntGlyph = NEXT_UShort( pCoverage );
                    if( pGsubLimit < pCoverage + 2 * nCntGlyph )
                        // TODO? nCntGlyph = (pGsubLimit - pCoverage) / 2;
                        return false;
                    aSubstVector.reserve( nCntGlyph );
                    for( USHORT i = 0; i < nCntGlyph; ++i )
                    {
                        const USHORT nGlyphId = NEXT_UShort( pCoverage );
                        aSubstVector.push_back( GlyphSubst( nGlyphId, 0 ) );
                    }
                }
                break;

                case 2:         // Coverage Format 2
                {
                    const USHORT nCntRange = NEXT_UShort( pCoverage );
                    if( pGsubLimit < pCoverage + 6 * nCntRange )
                        // TODO? nCntGlyph = (pGsubLimit - pCoverage) / 6;
                        return false;
                    for( int i = nCntRange; --i >= 0; )
                    {
                        const USHORT nGlyph0 = NEXT_UShort( pCoverage );
                        const USHORT nGlyph1 = NEXT_UShort( pCoverage );
                        const USHORT nCovIdx = NEXT_UShort( pCoverage );
                        for( USHORT j = nGlyph0; j <= nGlyph1; ++j )
                            aSubstVector.push_back( GlyphSubst( j + nCovIdx, 0 ) );
                    }
                }
                break;
            }

            SubstVector::iterator subst_it( aSubstVector.begin() );

            switch( nFmtSubstitution )
            {
                case 1:     // Single Substitution Format 1
                {
                    const USHORT nDeltaGlyphId = NEXT_UShort( pSubLookup );

                    for(; subst_it != aSubstVector.end(); ++subst_it )
                        (*subst_it).second = (*subst_it).first + nDeltaGlyphId;
                }
                break;

                case 2:     // Single Substitution Format 2
                {
                    const USHORT nCntGlyph = NEXT_UShort( pSubLookup );
                    for( int i = nCntGlyph; (subst_it != aSubstVector.end()) && (--i>=0); ++subst_it )
                    {
                        if( pGsubLimit < pSubLookup + 2 )
                            return false;
                        const USHORT nGlyphId = NEXT_UShort( pSubLookup );
                        (*subst_it).second = nGlyphId;
                    }
                }
                break;
            }

            // now apply the glyph substitutions that have been collected in this subtable
            if( aSubstVector.size() > 0 )
            {
                GlyphSubstitution* pGSubstitution = new GlyphSubstitution;
                pTTFile->pGSubstitution = (void*)pGSubstitution;
                for( subst_it = aSubstVector.begin(); subst_it != aSubstVector.end(); ++subst_it )
                    (*pGSubstitution)[ (*subst_it).first ] =  (*subst_it).second;
            }
        }
    }

    return true;
}

int UseGSUB( struct _TrueTypeFont* pTTFile, int nGlyph, int /*wmode*/ )
{
    GlyphSubstitution* pGlyphSubstitution = (GlyphSubstitution*)pTTFile->pGSubstitution;
    if( pGlyphSubstitution != 0 )
    {
        GlyphSubstitution::const_iterator it( pGlyphSubstitution->find( sal::static_int_cast<USHORT>(nGlyph) ) );
        if( it != pGlyphSubstitution->end() )
            nGlyph = (*it).second;
    }

    return nGlyph;
}

int HasVerticalGSUB( struct _TrueTypeFont* pTTFile )
{
    GlyphSubstitution* pGlyphSubstitution = (GlyphSubstitution*)pTTFile->pGSubstitution;
    return pGlyphSubstitution ? +1 : 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.10.20); FILE MERGED 2006/09/01 17:32:54 kaib 1.10.20.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gsub.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 12:34:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library 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 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.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_psprint.hxx"

#include "sft.h"
#undef true
#undef false

#include "gsub.h"

#include <vector>
#include <map>
#include <algorithm>

typedef sal_uInt32 ULONG;
typedef sal_uInt16 USHORT;
typedef sal_uInt8 FT_Byte;

typedef std::map<USHORT,USHORT> GlyphSubstitution;

inline long NEXT_Long( const unsigned char* &p )
{
    long nVal = (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3];
    p += 4;
    return nVal;
}

inline USHORT NEXT_UShort( const unsigned char* &p )
{
    USHORT nVal = (p[0]<<8) + p[1];
    p += 2;
    return nVal;
}

#define MKTAG(s) ((((((s[0]<<8)+s[1])<<8)+s[2])<<8)+s[3])

int ReadGSUB( struct _TrueTypeFont* pTTFile,
    int nRequestedScript, int nRequestedLangsys )
{
    const FT_Byte* pGsubBase = (FT_Byte*)pTTFile->tables[ O_gsub ];
    if( !pGsubBase )
        return -1;

    // #129682# check offsets inside GSUB table
    const FT_Byte* pGsubLimit = pGsubBase + pTTFile->tlens[ O_gsub ];

    // parse GSUB header
    const FT_Byte* pGsubHeader = pGsubBase;
    const ULONG nVersion            = NEXT_Long( pGsubHeader );
    const USHORT nOfsScriptList     = NEXT_UShort( pGsubHeader );
    const USHORT nOfsFeatureTable   = NEXT_UShort( pGsubHeader );
    const USHORT nOfsLookupList     = NEXT_UShort( pGsubHeader );

    // sanity check the GSUB header
    if( nVersion != 0x00010000 )
        if( nVersion != 0x00001000 )    // workaround for SunBatang etc.
            return -1;                  // unknown format or broken

    typedef std::vector<ULONG> ReqFeatureTagList;
    ReqFeatureTagList aReqFeatureTagList;

    aReqFeatureTagList.push_back( MKTAG("vert") );

    typedef std::vector<USHORT> UshortList;
    UshortList aFeatureIndexList;
    UshortList aFeatureOffsetList;

    // parse Script Table
    const FT_Byte* pScriptHeader = pGsubBase + nOfsScriptList;
    const USHORT nCntScript = NEXT_UShort( pScriptHeader );
    if( pGsubLimit < pScriptHeader + 6 * nCntScript )
        return false;
    for( USHORT nScriptIndex = 0; nScriptIndex < nCntScript; ++nScriptIndex )
    {
        const ULONG nTag            = NEXT_Long( pScriptHeader ); // e.g. hani/arab/kana/hang
        const USHORT nOfsScriptTable= NEXT_UShort( pScriptHeader );
        if( (nTag != (USHORT)nRequestedScript) && (nRequestedScript != 0) )
            continue;

        const FT_Byte* pScriptTable     = pGsubBase + nOfsScriptList + nOfsScriptTable;
        if( pGsubLimit < pScriptTable + 4 )
            return false;
        const USHORT nDefaultLangsysOfs = NEXT_UShort( pScriptTable );
        const USHORT nCntLangSystem     = NEXT_UShort( pScriptTable );
        USHORT nLangsysOffset = 0;
        if( pGsubLimit < pScriptTable + 6 * nCntLangSystem )
            return false;
        for( USHORT nLangsysIndex = 0; nLangsysIndex < nCntLangSystem; ++nLangsysIndex )
        {
            const ULONG nInnerTag = NEXT_Long( pScriptTable );    // e.g. KOR/ZHS/ZHT/JAN
            const USHORT nOffset= NEXT_UShort( pScriptTable );
            if( (nInnerTag != (USHORT)nRequestedLangsys) && (nRequestedLangsys != 0) )
                continue;
            nLangsysOffset = nOffset;
            break;
        }

        if( (nDefaultLangsysOfs != 0) && (nDefaultLangsysOfs != nLangsysOffset) )
        {
            const FT_Byte* pLangSys = pGsubBase + nOfsScriptList + nOfsScriptTable + nDefaultLangsysOfs;
            if( pGsubLimit < pLangSys + 6 )
                return false;
            /*const USHORT nLookupOrder   =*/ NEXT_UShort( pLangSys );
            const USHORT nReqFeatureIdx = NEXT_UShort( pLangSys );
            const USHORT nCntFeature    = NEXT_UShort( pLangSys );
            if( pGsubLimit < pLangSys + 2 * nCntFeature )
                return false;
            aFeatureIndexList.push_back( nReqFeatureIdx );
            for( USHORT i = 0; i < nCntFeature; ++i )
            {
                const USHORT nFeatureIndex = NEXT_UShort( pLangSys );
                aFeatureIndexList.push_back( nFeatureIndex );
            }
        }

        if( nLangsysOffset != 0 )
        {
            const FT_Byte* pLangSys = pGsubBase + nOfsScriptList + nOfsScriptTable + nLangsysOffset;
            if( pGsubLimit < pLangSys + 6 )
                return false;
            /*const USHORT nLookupOrder   =*/ NEXT_UShort( pLangSys );
            const USHORT nReqFeatureIdx = NEXT_UShort( pLangSys );
            const USHORT nCntFeature    = NEXT_UShort( pLangSys );
            if( pGsubLimit < pLangSys + 2 * nCntFeature )
                return false;
            aFeatureIndexList.push_back( nReqFeatureIdx );
            for( USHORT i = 0; i < nCntFeature; ++i )
            {
                const USHORT nFeatureIndex = NEXT_UShort( pLangSys );
                aFeatureIndexList.push_back( nFeatureIndex );
            }
        }
    }

    if( !aFeatureIndexList.size() )
        return true;

    UshortList aLookupIndexList;
    UshortList aLookupOffsetList;

    // parse Feature Table
    const FT_Byte* pFeatureHeader = pGsubBase + nOfsFeatureTable;
    if( pGsubLimit < pFeatureHeader + 2 )
          return false;
    const USHORT nCntFeature = NEXT_UShort( pFeatureHeader );
    if( pGsubLimit < pFeatureHeader + 6 * nCntFeature )
          return false;
    for( USHORT nFeatureIndex = 0; nFeatureIndex < nCntFeature; ++nFeatureIndex )
    {
        const ULONG nTag    = NEXT_Long( pFeatureHeader ); // e.g. locl/vert/trad/smpl/liga/fina/...
        const USHORT nOffset= NEXT_UShort( pFeatureHeader );

        // feature (required && (requested || available))?
        if( (aFeatureIndexList[0] != nFeatureIndex)
            &&  (!std::count( aReqFeatureTagList.begin(), aReqFeatureTagList.end(), nTag))
            ||  (!std::count( aFeatureIndexList.begin(), aFeatureIndexList.end(), nFeatureIndex) ) )
            continue;

        const FT_Byte* pFeatureTable = pGsubBase + nOfsFeatureTable + nOffset;
        if( pGsubLimit < pFeatureTable + 2 )
            return false;
        const USHORT nCntLookups = NEXT_UShort( pFeatureTable );
        if( pGsubLimit < pFeatureTable + 2 * nCntLookups )
            return false;
        for( USHORT i = 0; i < nCntLookups; ++i )
        {
            const USHORT nLookupIndex = NEXT_UShort( pFeatureTable );
            aLookupIndexList.push_back( nLookupIndex );
        }
        if( nCntLookups == 0 ) //### hack needed by Mincho/Gothic/Mingliu/Simsun/...
            aLookupIndexList.push_back( 0 );
    }

    // parse Lookup List
    const FT_Byte* pLookupHeader = pGsubBase + nOfsLookupList;
    if( pGsubLimit < pLookupHeader + 2 )
        return false;
    const USHORT nCntLookupTable = NEXT_UShort( pLookupHeader );
    if( pGsubLimit < pLookupHeader + 2 * nCntLookupTable )
        return false;
    for( USHORT nLookupIdx = 0; nLookupIdx < nCntLookupTable; ++nLookupIdx )
    {
        const USHORT nOffset = NEXT_UShort( pLookupHeader );
        if( std::count( aLookupIndexList.begin(), aLookupIndexList.end(), nLookupIdx ) )
            aLookupOffsetList.push_back( nOffset );
    }

    UshortList::const_iterator it = aLookupOffsetList.begin();
    for(; it != aLookupOffsetList.end(); ++it )
    {
        const USHORT nOfsLookupTable = *it;
        const FT_Byte* pLookupTable = pGsubBase + nOfsLookupList + nOfsLookupTable;
        if( pGsubLimit < pLookupTable + 6 )
            return false;
        const USHORT eLookupType        = NEXT_UShort( pLookupTable );
        /*const USHORT eLookupFlag        =*/ NEXT_UShort( pLookupTable );
        const USHORT nCntLookupSubtable = NEXT_UShort( pLookupTable );

        // TODO: switch( eLookupType )
        if( eLookupType != 1 )  // TODO: once we go beyond SingleSubst
            continue;

        if( pGsubLimit < pLookupTable + 2 * nCntLookupSubtable )
            return false;
        for( USHORT nSubTableIdx = 0; nSubTableIdx < nCntLookupSubtable; ++nSubTableIdx )
        {
            const USHORT nOfsSubLookupTable = NEXT_UShort( pLookupTable );
            const FT_Byte* pSubLookup = pGsubBase + nOfsLookupList + nOfsLookupTable + nOfsSubLookupTable;
            if( pGsubLimit < pSubLookup + 6 )
                return false;
            const USHORT nFmtSubstitution   = NEXT_UShort( pSubLookup );
            const USHORT nOfsCoverage       = NEXT_UShort( pSubLookup );

            typedef std::pair<USHORT,USHORT> GlyphSubst;
            typedef std::vector<GlyphSubst> SubstVector;
            SubstVector aSubstVector;

            const FT_Byte* pCoverage    = pGsubBase
                + nOfsLookupList + nOfsLookupTable + nOfsSubLookupTable + nOfsCoverage;
            if( pGsubLimit < pCoverage + 4 )
                return false;
            const USHORT nFmtCoverage   = NEXT_UShort( pCoverage );
            switch( nFmtCoverage )
            {
                case 1:         // Coverage Format 1
                {
                    const USHORT nCntGlyph = NEXT_UShort( pCoverage );
                    if( pGsubLimit < pCoverage + 2 * nCntGlyph )
                        // TODO? nCntGlyph = (pGsubLimit - pCoverage) / 2;
                        return false;
                    aSubstVector.reserve( nCntGlyph );
                    for( USHORT i = 0; i < nCntGlyph; ++i )
                    {
                        const USHORT nGlyphId = NEXT_UShort( pCoverage );
                        aSubstVector.push_back( GlyphSubst( nGlyphId, 0 ) );
                    }
                }
                break;

                case 2:         // Coverage Format 2
                {
                    const USHORT nCntRange = NEXT_UShort( pCoverage );
                    if( pGsubLimit < pCoverage + 6 * nCntRange )
                        // TODO? nCntGlyph = (pGsubLimit - pCoverage) / 6;
                        return false;
                    for( int i = nCntRange; --i >= 0; )
                    {
                        const USHORT nGlyph0 = NEXT_UShort( pCoverage );
                        const USHORT nGlyph1 = NEXT_UShort( pCoverage );
                        const USHORT nCovIdx = NEXT_UShort( pCoverage );
                        for( USHORT j = nGlyph0; j <= nGlyph1; ++j )
                            aSubstVector.push_back( GlyphSubst( j + nCovIdx, 0 ) );
                    }
                }
                break;
            }

            SubstVector::iterator subst_it( aSubstVector.begin() );

            switch( nFmtSubstitution )
            {
                case 1:     // Single Substitution Format 1
                {
                    const USHORT nDeltaGlyphId = NEXT_UShort( pSubLookup );

                    for(; subst_it != aSubstVector.end(); ++subst_it )
                        (*subst_it).second = (*subst_it).first + nDeltaGlyphId;
                }
                break;

                case 2:     // Single Substitution Format 2
                {
                    const USHORT nCntGlyph = NEXT_UShort( pSubLookup );
                    for( int i = nCntGlyph; (subst_it != aSubstVector.end()) && (--i>=0); ++subst_it )
                    {
                        if( pGsubLimit < pSubLookup + 2 )
                            return false;
                        const USHORT nGlyphId = NEXT_UShort( pSubLookup );
                        (*subst_it).second = nGlyphId;
                    }
                }
                break;
            }

            // now apply the glyph substitutions that have been collected in this subtable
            if( aSubstVector.size() > 0 )
            {
                GlyphSubstitution* pGSubstitution = new GlyphSubstitution;
                pTTFile->pGSubstitution = (void*)pGSubstitution;
                for( subst_it = aSubstVector.begin(); subst_it != aSubstVector.end(); ++subst_it )
                    (*pGSubstitution)[ (*subst_it).first ] =  (*subst_it).second;
            }
        }
    }

    return true;
}

int UseGSUB( struct _TrueTypeFont* pTTFile, int nGlyph, int /*wmode*/ )
{
    GlyphSubstitution* pGlyphSubstitution = (GlyphSubstitution*)pTTFile->pGSubstitution;
    if( pGlyphSubstitution != 0 )
    {
        GlyphSubstitution::const_iterator it( pGlyphSubstitution->find( sal::static_int_cast<USHORT>(nGlyph) ) );
        if( it != pGlyphSubstitution->end() )
            nGlyph = (*it).second;
    }

    return nGlyph;
}

int HasVerticalGSUB( struct _TrueTypeFont* pTTFile )
{
    GlyphSubstitution* pGlyphSubstitution = (GlyphSubstitution*)pTTFile->pGSubstitution;
    return pGlyphSubstitution ? +1 : 0;
}
<|endoftext|>


<commit_before>
#include "CatGameLib.h"
#include "ExternalLib.h"

#include "LibSound.h"

using namespace std;
using namespace CatGameLib;

int LibSound::loadCount = 0;
unsigned int LibSound::sourceIDs[LoadSoundMax] = { 0 };
unsigned int LibSound::bufferIDs[LoadSoundMax] = { 0 };

LibSound* LibSound::create( const char* fileName)
{
	LibSound* sound = new (nothrow)LibSound();

	if( sound == nullptr)
	{
		return nullptr;
	}

	sound -> loadFile( fileName);
	return sound;
}

void LibSound::allRelease( void)
{
	alSourceStopv( loadCount, sourceIDs);
	alDeleteSources( loadCount, sourceIDs);
	alDeleteBuffers( loadCount, bufferIDs);
	loadCount = 0;
}

LibSound::LibSound() : sourceID( 0),
					   bufferID( 0)
{
}

LibSound::~LibSound()
{
	stop();
	alDeleteSources( 1, &sourceIDs[sourceID]);
	alDeleteBuffers( 1, &bufferIDs[bufferID]);
}

void LibSound::setLoop( bool isLoop)
{
	alSourcei( sourceIDs[sourceID], AL_LOOPING, isLoop);
}

void LibSound::setVolume( float vol)
{
	alSourcef( sourceIDs[sourceID], AL_GAIN, LibBasicFunc::clamp( vol, 0.0f, 1.0f));
}

void LibSound::play( void)
{
	alSourcePlay( sourceIDs[sourceID]);
}

void LibSound::pause( void)
{
	alSourcePause( sourceIDs[sourceID]);
}

void LibSound::stop( void)
{
	alSourceStop( sourceIDs[sourceID]);
}

void LibSound::restart( void)
{
	stop();
	play();
}

void LibSound::loadFile( const char* fileName)
{
	string filePass = "ResourceFile/Sound/";
	filePass += fileName;

	// \[X쐬
	alGenSources( 1, &sourceIDs[loadCount]);

	// obt@쐬
	bufferIDs[loadCount] = alureCreateBufferFromFile( filePass.c_str());
	if( bufferIDs[loadCount] == AL_NONE)
	{
		std::cout << "Failed to load from file!" << std::endl;
	}

	// w肵ԍۑ
	sourceID = loadCount;
	bufferID = loadCount;

	// JEgXV
	loadCount++;

	// obt@ɐݒ
	alSourcei( sourceIDs[sourceID], AL_BUFFER, bufferIDs[bufferID]);

	// ʂ𔼕
	alSourcef( sourceIDs[sourceID], AL_GAIN, 0.5f);
}
	<commit_msg>サウンドクラスのエラー処置の不備を修正<commit_after>
#include "CatGameLib.h"
#include "ExternalLib.h"

#include "LibSound.h"

using namespace std;
using namespace CatGameLib;

int LibSound::loadCount = 0;
unsigned int LibSound::sourceIDs[LoadSoundMax] = { 0 };
unsigned int LibSound::bufferIDs[LoadSoundMax] = { 0 };

LibSound* LibSound::create( const char* fileName)
{
	LibSound* sound = new (nothrow)LibSound();

	if( sound == nullptr)
	{
		return nullptr;
	}

	sound -> loadFile( fileName);
	return sound;
}

void LibSound::allRelease( void)
{
	alSourceStopv( loadCount, sourceIDs);
	alDeleteSources( loadCount, sourceIDs);
	alDeleteBuffers( loadCount, bufferIDs);
	loadCount = 0;
}

LibSound::LibSound() : sourceID( 0),
					   bufferID( 0)
{
}

LibSound::~LibSound()
{
	stop();
	alDeleteSources( 1, &sourceIDs[sourceID]);
	alDeleteBuffers( 1, &bufferIDs[bufferID]);
}

void LibSound::setLoop( bool isLoop)
{
	alSourcei( sourceIDs[sourceID], AL_LOOPING, isLoop);
}

void LibSound::setVolume( float vol)
{
	alSourcef( sourceIDs[sourceID], AL_GAIN, LibBasicFunc::clamp( vol, 0.0f, 1.0f));
}

void LibSound::play( void)
{
	alSourcePlay( sourceIDs[sourceID]);
}

void LibSound::pause( void)
{
	alSourcePause( sourceIDs[sourceID]);
}

void LibSound::stop( void)
{
	alSourceStop( sourceIDs[sourceID]);
}

void LibSound::restart( void)
{
	stop();
	play();
}

void LibSound::loadFile( const char* fileName)
{
	string filePass = "ResourceFile/Sound/";
	filePass += fileName;

	// \[X쐬
	alGenSources( 1, &sourceIDs[loadCount]);

	// obt@쐬
	bufferIDs[loadCount] = alureCreateBufferFromFile( filePass.c_str());
	if( bufferIDs[loadCount] == AL_NONE)
	{
		string message = "can't load from ";
		message += fileName;
		LibDebug::errorMessageBox( message.c_str());
	}

	// w肵ԍۑ
	sourceID = loadCount;
	bufferID = loadCount;

	// JEgXV
	loadCount++;

	// obt@ɐݒ
	alSourcei( sourceIDs[sourceID], AL_BUFFER, bufferIDs[bufferID]);

	// ʂ𔼕
	alSourcef( sourceIDs[sourceID], AL_GAIN, 0.5f);
}
	<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH

#include <vector>

#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/common/matrix.hh>
#include <dune/stuff/la/container/interface.hh>

#include <dune/detailed/discretizations/localoperator/codim0.hh>
#include <dune/detailed/discretizations/space/interface.hh>

namespace Dune {
namespace Detailed {
namespace Discretizations {

// forward, to be used in the traits
template <class LocalOperatorImp>
class LocalAssemblerCodim0Matrix;

template <class LocalOperatorImp>
class LocalAssemblerCodim0MatrixTraits
{
public:
  typedef LocalAssemblerCodim0Matrix<LocalOperatorImp> derived_type;
  typedef LocalOperatorCodim0Interface<typename LocalOperatorImp::Traits> LocalOperatorType;
}; // class LocalAssemblerCodim0MatrixTraits

template <class LocalOperatorImp>
class LocalAssemblerCodim0Matrix
{
public:
  typedef LocalAssemblerCodim0MatrixTraits<LocalOperatorImp> Traits;
  typedef typename Traits::LocalOperatorType LocalOperatorType;

  LocalAssemblerCodim0Matrix(const LocalOperatorType& op)
    : localOperator_(op)
  {
  }

  const LocalOperatorType& localOperator() const
  {
    return localOperator_;
  }

private:
  static const size_t numTmpObjectsRequired_ = 1;

public:
  std::vector<size_t> numTmpObjectsRequired() const
  {
    return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
  }

  /**
   *  \tparam T           Traits of the SpaceInterface implementation, representing the type of testSpace
   *  \tparam A
   *  \tparam EntityType
   *  \tparam M
   *  \tparam L
   */
  template <class T, class A, class EntityType, class M, class R>
  void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,
                     Dune::Stuff::LA::Container::MatrixInterface<M>& systemMatrix,
                     std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
                     std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
  {
    // check
    assert(tmpLocalMatricesContainer.size() >= 1);
    assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
    assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
    assert(tmpIndicesContainer.size() >= 2);
    // get and clear matrix
    auto& localMatrix = tmpLocalMatricesContainer[0][0];
    Dune::Stuff::Common::clear(localMatrix);
    auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
    // apply local operator (result is in localMatrix)
    localOperator_.apply(
        testSpace.baseFunctionSet(entity), ansatzSpace.baseFunctionSet(entity), localMatrix, tmpOperatorMatrices);
    // write local matrix to global
    auto& globalRows  = tmpIndicesContainer[0];
    auto& globalCols  = tmpIndicesContainer[1];
    const size_t rows = testSpace.mapper().numDofs(entity);
    const size_t cols = ansatzSpace.mapper().numDofs(entity);
    assert(globalRows.size() >= rows);
    assert(globalCols.size() >= cols);
    testSpace.mapper().globalIndices(entity, globalRows);
    ansatzSpace.mapper().globalIndices(entity, globalCols);
    for (size_t ii = 0; ii < rows; ++ii) {
      const auto& localRow = localMatrix[ii];
      for (size_t jj = 0; jj < cols; ++jj)
        systemMatrix.set(globalRows[ii], globalCols[jj], localRow[jj]);
    } // write local matrix to global
  } // ... assembleLocal(...)

private:
  const LocalOperatorType& localOperator_;
}; // class LocalAssemblerCodim0Matrix

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH
<commit_msg>[assembler.local.codim0] fixed wrong matrix filling (add instead of set)<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH

#include <vector>

#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/common/matrix.hh>
#include <dune/stuff/la/container/interface.hh>

#include <dune/detailed/discretizations/localoperator/codim0.hh>
#include <dune/detailed/discretizations/space/interface.hh>

namespace Dune {
namespace Detailed {
namespace Discretizations {

// forward, to be used in the traits
template <class LocalOperatorImp>
class LocalAssemblerCodim0Matrix;

template <class LocalOperatorImp>
class LocalAssemblerCodim0MatrixTraits
{
public:
  typedef LocalAssemblerCodim0Matrix<LocalOperatorImp> derived_type;
  typedef LocalOperatorCodim0Interface<typename LocalOperatorImp::Traits> LocalOperatorType;
}; // class LocalAssemblerCodim0MatrixTraits

template <class LocalOperatorImp>
class LocalAssemblerCodim0Matrix
{
public:
  typedef LocalAssemblerCodim0MatrixTraits<LocalOperatorImp> Traits;
  typedef typename Traits::LocalOperatorType LocalOperatorType;

  LocalAssemblerCodim0Matrix(const LocalOperatorType& op)
    : localOperator_(op)
  {
  }

  const LocalOperatorType& localOperator() const
  {
    return localOperator_;
  }

private:
  static const size_t numTmpObjectsRequired_ = 1;

public:
  std::vector<size_t> numTmpObjectsRequired() const
  {
    return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};
  }

  /**
   *  \tparam T           Traits of the SpaceInterface implementation, representing the type of testSpace
   *  \tparam A           Traits of the SpaceInterface implementation, representing the type of ansatzSpace
   *  \tparam EntityType  A model of Dune::Entity< 0 >
   *  \tparam M           Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the
   * type of systemMatrix
   *  \tparam R           RangeFieldType, i.e. double
   */
  template <class T, class A, class EntityType, class M, class R>
  void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,
                     Dune::Stuff::LA::Container::MatrixInterface<M>& systemMatrix,
                     std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,
                     std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const
  {
    // check
    assert(tmpLocalMatricesContainer.size() >= 1);
    assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);
    assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());
    assert(tmpIndicesContainer.size() >= 2);
    // get and clear matrix
    auto& localMatrix = tmpLocalMatricesContainer[0][0];
    Dune::Stuff::Common::clear(localMatrix);
    auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];
    // apply local operator (result is in localMatrix)
    localOperator_.apply(
        testSpace.baseFunctionSet(entity), ansatzSpace.baseFunctionSet(entity), localMatrix, tmpOperatorMatrices);
    // write local matrix to global
    auto& globalRows  = tmpIndicesContainer[0];
    auto& globalCols  = tmpIndicesContainer[1];
    const size_t rows = testSpace.mapper().numDofs(entity);
    const size_t cols = ansatzSpace.mapper().numDofs(entity);
    assert(globalRows.size() >= rows);
    assert(globalCols.size() >= cols);
    testSpace.mapper().globalIndices(entity, globalRows);
    ansatzSpace.mapper().globalIndices(entity, globalCols);
    for (size_t ii = 0; ii < rows; ++ii) {
      const auto& localRow = localMatrix[ii];
      for (size_t jj = 0; jj < cols; ++jj)
        systemMatrix.add(globalRows[ii], globalCols[jj], localRow[jj]);
    } // write local matrix to global
  } // ... assembleLocal(...)

private:
  const LocalOperatorType& localOperator_;
}; // class LocalAssemblerCodim0Matrix

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM0_HH
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "update_engine/dbus_service.h"

#include <string>

#include <base/logging.h>

#include "update_engine/marshal.glibmarshal.h"
#include "update_engine/omaha_request_params.h"
#include "update_engine/utils.h"

using std::string;

G_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)

static void update_engine_service_finalize(GObject* object) {
  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);
}

static guint status_update_signal = 0;

static void update_engine_service_class_init(UpdateEngineServiceClass* klass) {
  GObjectClass *object_class;
  object_class = G_OBJECT_CLASS(klass);
  object_class->finalize = update_engine_service_finalize;

  status_update_signal = g_signal_new(
      "status_update",
      G_OBJECT_CLASS_TYPE(klass),
      G_SIGNAL_RUN_LAST,
      0,  // 0 == no class method associated
      NULL,  // Accumulator
      NULL,  // Accumulator data
      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,
      G_TYPE_NONE,  // Return type
      5,  // param count:
      G_TYPE_INT64,
      G_TYPE_DOUBLE,
      G_TYPE_STRING,
      G_TYPE_STRING,
      G_TYPE_INT64);
}

static void update_engine_service_init(UpdateEngineService* object) {
}

UpdateEngineService* update_engine_service_new(void) {
  return reinterpret_cast<UpdateEngineService*>(
      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));
}

gboolean update_engine_service_attempt_update(UpdateEngineService* self,
                                              gchar* app_version,
                                              gchar* omaha_url,
                                              GError **error) {
  string update_app_version;
  string update_omaha_url;
  // Only non-official (e.g., dev and test) builds can override the current
  // version and update server URL over D-Bus.
  if (!chromeos_update_engine::utils::IsOfficialBuild()) {
    if (app_version) {
      update_app_version = app_version;
    }
    if (omaha_url) {
      update_omaha_url = omaha_url;
    }
  }
  LOG(INFO) << "Attempt update: app_version=\"" << update_app_version << "\" "
            << "omaha_url=\"" << update_omaha_url << "\"";
  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);
  return TRUE;
}

gboolean update_engine_service_get_status(UpdateEngineService* self,
                                          int64_t* last_checked_time,
                                          double* progress,
                                          gchar** current_operation,
                                          gchar** new_version,
                                          int64_t* new_size,
                                          GError **error) {
  string current_op;
  string new_version_str;

  CHECK(self->update_attempter_->GetStatus(last_checked_time,
                                           progress,
                                           &current_op,
                                           &new_version_str,
                                           new_size));

  *current_operation = strdup(current_op.c_str());
  *new_version = strdup(new_version_str.c_str());
  if (!(*current_operation && *new_version)) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_get_track(UpdateEngineService* self,
                                         gchar** track,
                                         GError **error) {
  string track_str =
      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();
  *track = strdup(track_str.c_str());
  return TRUE;
}

gboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,
                                                GError **error) {
  if (!self->update_attempter_->RebootIfNeeded()) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_set_track(UpdateEngineService* self,
                                         gchar* track,
                                         GError **error) {
  if (track) {
    LOG(INFO) << "Setting track to: " << track;
    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(
            track)) {
      *error = NULL;
      return FALSE;
    }
  }
  return TRUE;
}

gboolean update_engine_service_emit_status_update(
    UpdateEngineService* self,
    gint64 last_checked_time,
    gdouble progress,
    const gchar* current_operation,
    const gchar* new_version,
    gint64 new_size) {
  g_signal_emit(self,
                status_update_signal,
                0,
                last_checked_time,
                progress,
                current_operation,
                new_version,
                new_size);
  return TRUE;
}
<commit_msg>Use g_strdup() instead of strdup().<commit_after>// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "update_engine/dbus_service.h"

#include <string>

#include <base/logging.h>

#include "update_engine/marshal.glibmarshal.h"
#include "update_engine/omaha_request_params.h"
#include "update_engine/utils.h"

using std::string;

G_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)

static void update_engine_service_finalize(GObject* object) {
  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);
}

static guint status_update_signal = 0;

static void update_engine_service_class_init(UpdateEngineServiceClass* klass) {
  GObjectClass *object_class;
  object_class = G_OBJECT_CLASS(klass);
  object_class->finalize = update_engine_service_finalize;

  status_update_signal = g_signal_new(
      "status_update",
      G_OBJECT_CLASS_TYPE(klass),
      G_SIGNAL_RUN_LAST,
      0,  // 0 == no class method associated
      NULL,  // Accumulator
      NULL,  // Accumulator data
      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,
      G_TYPE_NONE,  // Return type
      5,  // param count:
      G_TYPE_INT64,
      G_TYPE_DOUBLE,
      G_TYPE_STRING,
      G_TYPE_STRING,
      G_TYPE_INT64);
}

static void update_engine_service_init(UpdateEngineService* object) {
}

UpdateEngineService* update_engine_service_new(void) {
  return reinterpret_cast<UpdateEngineService*>(
      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));
}

gboolean update_engine_service_attempt_update(UpdateEngineService* self,
                                              gchar* app_version,
                                              gchar* omaha_url,
                                              GError **error) {
  string update_app_version;
  string update_omaha_url;
  // Only non-official (e.g., dev and test) builds can override the current
  // version and update server URL over D-Bus.
  if (!chromeos_update_engine::utils::IsOfficialBuild()) {
    if (app_version) {
      update_app_version = app_version;
    }
    if (omaha_url) {
      update_omaha_url = omaha_url;
    }
  }
  LOG(INFO) << "Attempt update: app_version=\"" << update_app_version << "\" "
            << "omaha_url=\"" << update_omaha_url << "\"";
  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);
  return TRUE;
}

gboolean update_engine_service_get_status(UpdateEngineService* self,
                                          int64_t* last_checked_time,
                                          double* progress,
                                          gchar** current_operation,
                                          gchar** new_version,
                                          int64_t* new_size,
                                          GError **error) {
  string current_op;
  string new_version_str;

  CHECK(self->update_attempter_->GetStatus(last_checked_time,
                                           progress,
                                           &current_op,
                                           &new_version_str,
                                           new_size));

  *current_operation = g_strdup(current_op.c_str());
  *new_version = g_strdup(new_version_str.c_str());
  if (!(*current_operation && *new_version)) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_get_track(UpdateEngineService* self,
                                         gchar** track,
                                         GError **error) {
  string track_str =
      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();
  *track = g_strdup(track_str.c_str());
  return TRUE;
}

gboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,
                                                GError **error) {
  if (!self->update_attempter_->RebootIfNeeded()) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_set_track(UpdateEngineService* self,
                                         gchar* track,
                                         GError **error) {
  if (track) {
    LOG(INFO) << "Setting track to: " << track;
    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(
            track)) {
      *error = NULL;
      return FALSE;
    }
  }
  return TRUE;
}

gboolean update_engine_service_emit_status_update(
    UpdateEngineService* self,
    gint64 last_checked_time,
    gdouble progress,
    const gchar* current_operation,
    const gchar* new_version,
    gint64 new_size) {
  g_signal_emit(self,
                status_update_signal,
                0,
                last_checked_time,
                progress,
                current_operation,
                new_version,
                new_size);
  return TRUE;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cassert>

#include "logger.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "environment.hpp"
#include "direct_interpreter.hpp"

// convert double to percent string
std::string format_probability(double prob)
{
    if (prob < 0.0001 && prob != 0)
    {
        return "< 0.01 %";
    }
    return std::to_string(prob * 100) + " %";
}

// value formatting functions

class formatting_visitor : public dice::value_visitor
{
public:
    void visit(dice::type_int* value) override
    {
        std::cout << value->data() << std::endl;
    }

    void visit(dice::type_double* value) override
    {
        std::cout << value->data() << std::endl;
    }

    void visit(dice::type_rand_var* value) override
    {
        const int width_value = 10;
        const int width_prob = 15;
        const int width_cdf = 15;

        // print table header
        std::cout << std::endl
            << std::setw(width_value) << "Value"
            << std::setw(width_prob) << "PMF"
            << std::setw(width_cdf) << "CDF"
            << std::endl;

        // sort PMF by value
        auto probability = value->data().to_random_variable().probability();
        dice::random_variable<int, double>::probability_list values{
            probability.begin(),
            probability.end()
        };
        std::sort(values.begin(), values.end(), [](auto&& a, auto&& b)
        {
            return a.first < b.first;
        });

        // print the random variable
        if (values.empty())
            return;

        double sum = 0;
        for (auto it = values.begin(); it != values.end(); ++it)
        {
            sum += it->second;
            std::cout
                << std::setw(width_value) << it->first
                << std::setw(width_prob) << format_probability(it->second)
                << std::setw(width_cdf) << format_probability(sum)
                << std::endl;
        }
    }
};

struct options
{
    // Command line arguments
    std::vector<std::string> args;
    // Input stream
    std::istream* input;
    // Should we print the executed script?
    bool verbose;

    options(int argc, char** argv) :
        args(argv, argv + argc),
        input(nullptr),
        verbose(false)
    {
        parse();
    }
private:
    std::ifstream input_file_;
    std::stringstream input_mem_;

    void parse()
    {
        auto it = args.begin() + 1; // first arg is the file path

        bool load_from_file = false;
        for (; it != args.end(); ++it)
        {
            if (*it == "-f") // input file
            {
                assert(it + 1 != args.end());
                ++it;
                input_file_.open(*it);
                input = &input_file_;
                load_from_file = true;
            }
            else if (*it == "-v")
            {
                verbose = true;
            }
            else
            {
                break;
            }
        }

        // load from arguments - concatenate the rest of the args
        if (!load_from_file && it != args.end())
        {
            std::string expr = *it++;
            for (; it != args.end(); ++it)
                expr += " " + *it;
            input_mem_ = std::stringstream{ expr };
            input = &input_mem_;
        }
    }
};

int main(int argc, char** argv)
{
    options opt{ argc, argv };

    if (opt.input != nullptr)
    {
        // parse and interpret the expression
        dice::logger log;
        dice::lexer lexer{ opt.input, &log };
        dice::environment env;
        dice::direct_interpreter<dice::environment> interpret{ &env };
        auto parser = dice::make_parser(&lexer, &log, &interpret);
        auto result = parser.parse();

        formatting_visitor format;
        for (auto&& value : result)
        {
            if (value == nullptr)
                continue;
            value->accept(&format);
        }

        if (!log.empty())
            return 1;
    }
    else
    {
        std::cerr << "Dice expressions interpreter." << std::endl
            << std::endl
            << "Usage:" << std::endl
            << "   ./dice_cli [options] [expression]" << std::endl
            << std::endl
            << "   [options]:" << std::endl
            << "      -f <file> load expression from file" << std::endl
            << "      -v verbose output (show executed script)" << std::endl
            << std::endl
            << "   [expression]:" << std::endl
            << "      A dice expression. Can be in multiple arguments." << std::endl
            << "      The program will join them wih a space." << std::endl;
        return 1;
    }
    return 0;
}<commit_msg>Add execution time<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cassert>
#include <chrono>

#include "logger.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "environment.hpp"
#include "direct_interpreter.hpp"

// convert double to percent string
std::string format_probability(double prob)
{
    if (prob < 0.0001 && prob != 0)
    {
        return "< 0.01 %";
    }
    return std::to_string(prob * 100) + " %";
}

// value formatting functions

class formatting_visitor : public dice::value_visitor
{
public:
    void visit(dice::type_int* value) override
    {
        std::cout << value->data() << std::endl;
    }

    void visit(dice::type_double* value) override
    {
        std::cout << value->data() << std::endl;
    }

    void visit(dice::type_rand_var* value) override
    {
        const int width_value = 10;
        const int width_prob = 15;
        const int width_cdf = 15;

        // print table header
        std::cout << std::endl
            << std::setw(width_value) << "Value"
            << std::setw(width_prob) << "PMF"
            << std::setw(width_cdf) << "CDF"
            << std::endl;

        // sort PMF by value
        auto probability = value->data().to_random_variable().probability();
        dice::random_variable<int, double>::probability_list values{
            probability.begin(),
            probability.end()
        };
        std::sort(values.begin(), values.end(), [](auto&& a, auto&& b)
        {
            return a.first < b.first;
        });

        // print the random variable
        if (values.empty())
            return;

        double sum = 0;
        for (auto it = values.begin(); it != values.end(); ++it)
        {
            sum += it->second;
            std::cout
                << std::setw(width_value) << it->first
                << std::setw(width_prob) << format_probability(it->second)
                << std::setw(width_cdf) << format_probability(sum)
                << std::endl;
        }
    }
};

struct options
{
    // Command line arguments
    std::vector<std::string> args;
    // Input stream
    std::istream* input;
    // Should we print the executed script?
    bool verbose;

    options(int argc, char** argv) :
        args(argv, argv + argc),
        input(nullptr),
        verbose(false)
    {
        parse();
    }
private:
    std::ifstream input_file_;
    std::stringstream input_mem_;

    void parse()
    {
        auto it = args.begin() + 1; // first arg is the file path

        bool load_from_file = false;
        for (; it != args.end(); ++it)
        {
            if (*it == "-f") // input file
            {
                assert(it + 1 != args.end());
                ++it;
                input_file_.open(*it);
                input = &input_file_;
                load_from_file = true;
            }
            else if (*it == "-v")
            {
                verbose = true;
            }
            else
            {
                break;
            }
        }

        // load from arguments - concatenate the rest of the args
        if (!load_from_file && it != args.end())
        {
            std::string expr = *it++;
            for (; it != args.end(); ++it)
                expr += " " + *it;
            input_mem_ = std::stringstream{ expr };
            input = &input_mem_;
        }
    }
};

int main(int argc, char** argv)
{
    options opt{ argc, argv };

    if (opt.input != nullptr)
    {
        // parse and interpret the expression
        dice::logger log;
        dice::lexer lexer{ opt.input, &log };
        dice::environment env;
        dice::direct_interpreter<dice::environment> interpret{ &env };
        auto parser = dice::make_parser(&lexer, &log, &interpret);

        auto start = std::chrono::high_resolution_clock::now();
        auto result = parser.parse();
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

        formatting_visitor format;
        for (auto&& value : result)
        {
            if (value == nullptr)
                continue;
            value->accept(&format);
        }

        std::cout << "Evaluated in " << duration << " ms" << std::endl;
        if (!log.empty())
            return 1;
    }
    else
    {
        std::cerr << "Dice expressions interpreter." << std::endl
            << std::endl
            << "Usage:" << std::endl
            << "   ./dice_cli [options] [expression]" << std::endl
            << std::endl
            << "   [options]:" << std::endl
            << "      -f <file> load expression from file" << std::endl
            << "      -v verbose output (show executed script)" << std::endl
            << std::endl
            << "   [expression]:" << std::endl
            << "      A dice expression. Can be in multiple arguments." << std::endl
            << "      The program will join them wih a space." << std::endl;
        return 1;
    }
    return 0;
}<|endoftext|>