<commit_before>#pragma once

#include <tudocomp/util.hpp>
#include <tudocomp/io.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/Algorithm.hpp>

#include <vector>
#include <tuple>

namespace tdc {
namespace lfs {

template<typename text_t = TextDS<> , uint min_lrf = 2>
class ESAStrategy : public Algorithm {
private:

    //(position in text, non_terminal_symbol_number, length_of_symbol);
    typedef std::tuple<uint,uint,uint> non_term;
    typedef std::vector<non_term> non_terminal_symbols;
    typedef std::vector<std::pair<uint,uint>> rules;

    BitVector dead_positions;

    inline virtual std::vector<uint> select_starting_positions(std::vector<uint> starting_positions, uint length){
        std::vector<uint> selected_starting_positions;
        std::sort(starting_positions.begin(), starting_positions.end());
        //select occurences greedily non-overlapping:
        selected_starting_positions.reserve(starting_positions.size());

        int last =  0-length;
        uint current;
        for (std::vector<uint>::iterator it=starting_positions.begin(); it!=starting_positions.end(); ++it){

            current = *it;
            //DLOG(INFO) << "checking starting position: " << current << " length: " << top.first << "last " << last;
            if(last+length <= current){
                selected_starting_positions.push_back(current);
                last = current;

            }

        }
        return selected_starting_positions;
    }

    //could be node_type
    std::vector<std::vector<uint> > lcp_bins;
public:

    using Algorithm::Algorithm; //import constructor

    inline static Meta meta() {
        Meta m("lfs_comp", "esa");

        m.option("textds").templated<text_t, TextDS<>>("textds");
        return m;
    }

    inline void compute_rules(io::InputView & input, rules & dictionary, non_terminal_symbols & nts_symbols){

//env().env_for_option("textds"),
        //const auto input = in.as_view();

        text_t t(env().env_for_option("textds"), input);
       // text_t t(env, in);
        DLOG(INFO) << "building sa and lcp";
        StatPhase::wrap("computing sa and lcp", [&]{

            t.require(text_t::SA | text_t::ISA | text_t::LCP);
        });
        auto& sa_t = t.require_sa();
        auto& lcp_t = t.require_lcp();

        //min_lrf=2;
        StatPhase::wrap("computing lrf occurences", [&]{

        // iterate over lcp array, add indexes with non overlapping prefix length greater than min_lrf_length to vector
        //std::vector<std::pair<uint,uint>> lrf_occurences;

        StatPhase::wrap("computing lrf occs", [&]{

        DLOG(INFO) << "iterate over lcp";
        uint dif ;
        uint factor_length;

        uint max = 0;

        for(uint i = 1; i<lcp_t.size(); i++){

            if(lcp_t[i] >= min_lrf){
                if(max < lcp_t[i]){
                    max = lcp_t[i];
                    lcp_bins.resize(max+1);
                }
                //compute length of non-overlapping factor:

                dif = abs(sa_t[i-1] - sa_t[i]);
                factor_length = lcp_t[i];
                factor_length = std::min(factor_length, dif);

                //maybe greater non-overlapping factor possible with smaller suffix?
                int j =i-1;
                uint alt_dif;
                while(j>0 && lcp_t[j]>factor_length ){
                    alt_dif = abs(sa_t[j] - sa_t[i]);
                    if(alt_dif>dif){
                        dif = alt_dif;
                    }
                    j--;

                }
                factor_length = lcp_t[i];
                factor_length = std::min(factor_length, dif);
                //second is position in suffix array
                //first is length of common prefix
               // std::pair<uint,uint> pair (factor_length, i);
              //  if(factor_length>=min_lrf){
               //     lrf_occurences.push_back(pair);
               // }

                lcp_bins[factor_length].push_back(i);
            }
        }

        DLOG(INFO)<<"max lcp: "<<max;

        });

        //Pq for the non-terminal symbols
        //the first in pair is position, the seconds the number of the non terminal symbol

        DLOG(INFO) << "computing lrfs";

        //vector of text position, length
        //std::vector<std::pair<uint,uint>> dictionary;
      //  StatPhase::wrap("sorting lrf occs", [&]{

      //  std::sort(lrf_occurences.begin(),lrf_occurences.end());
     //   });

        StatPhase::wrap("selecting occs", [&]{

            // Pop PQ, Select occurences of suffix, check if contains replaced symbols
        dead_positions = BitVector(t.size(), 0);

        //std::vector<std::tuple<uint,uint,uint>> nts_symbols;
        nts_symbols.reserve(lcp_bins.size());
        uint non_terminal_symbol_number = 0;

        for(uint lcp_len = lcp_bins.size()-1; lcp_len>= min_lrf; lcp_len--){
            DLOG(INFO)<<"size of lrf: "  << lcp_len <<" occs: "<< lcp_bins[lcp_len].size();
            for(auto bin_it = lcp_bins[lcp_len].begin(); bin_it!=lcp_bins[lcp_len].end(); bin_it++){

               // if(dead_positions[sa_t[*bin_it]] || dead_positions[sa_t[*bin_it-1]] || dead_positions[sa_t[*bin_it]+lcp_len-1] || dead_positions[sa_t[*bin_it-1]+lcp_len-1]){
               //     continue;
               // }

                //detect all starting positions of this string using the sa and lcp:
                std::vector<uint> starting_positions;
                starting_positions.reserve(20);

                //starting_positions.push_back(sa_t[*bin_it]);

                // and ceck in bitvector viable starting positions
                // there is no 1 bit on the corresponding positions
                // it suffices to check start and end position, because lrf can only be same length and shorter
                uint i = *bin_it;

                while(i>=0 && ( lcp_t[i])>=lcp_len){
                    if(!dead_positions[sa_t[i-1]]  && !dead_positions[sa_t[i-1]+lcp_len-1]){
                        starting_positions.push_back(sa_t[i-1]);
                    }
                    i--;
                }
                i = *bin_it;
                while(i< lcp_t.size() &&  lcp_t[i]>=lcp_len){
                    if(!dead_positions[sa_t[i]]  && !dead_positions[sa_t[i]+lcp_len-1]){
                        starting_positions.push_back(sa_t[i]);
                    }
                    i++;
                }
                //if the factor is still repeating, make the corresponding positions unviable

                if(starting_positions.size()>=2){
                    std::vector<uint> selected_starting_positions = select_starting_positions(starting_positions, lcp_len);
                    //computing substring to be replaced
                    if(selected_starting_positions.size()>=2){

                        uint offset = sa_t[*bin_it];
                        std::pair<uint,uint> longest_repeating_factor(offset, lcp_len);
                        for (std::vector<uint>::iterator it=selected_starting_positions.begin(); it!=selected_starting_positions.end(); ++it){
                            for(uint k = 0; k<lcp_len; k++){
                                dead_positions[*it+k]=1;
                            }

                            uint length_of_symbol = lcp_len;
                            std::tuple<uint,uint,uint> symbol(*it, non_terminal_symbol_number, length_of_symbol);
                            nts_symbols.push_back(symbol);
                        }
                        dictionary.push_back(longest_repeating_factor);
                        non_terminal_symbol_number++;
                    }
                }

            }
        }
        });
        });

        StatPhase::wrap("sorting symbols", [&]{
        DLOG(INFO) << "sorting symbols";
        //, std::greater<std::tuple<uint,uint,uint>>()
        std::sort(nts_symbols.begin(), nts_symbols.end());

        });

    }
};
}
}
<commit_msg>exact matching, ultra slow<commit_after>#pragma once

#include <tudocomp/util.hpp>
#include <tudocomp/io.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/Algorithm.hpp>

#include <vector>
#include <tuple>

namespace tdc {
namespace lfs {

template<typename text_t = TextDS<> , uint min_lrf = 2>
class ESAStrategy : public Algorithm {
private:

    //(position in text, non_terminal_symbol_number, length_of_symbol);
    typedef std::tuple<uint,uint,uint> non_term;
    typedef std::vector<non_term> non_terminal_symbols;
    typedef std::vector<std::pair<uint,uint>> rules;

    BitVector dead_positions;

    inline virtual std::vector<uint> select_starting_positions(std::vector<uint> starting_positions, uint length){
        std::vector<uint> selected_starting_positions;
        std::sort(starting_positions.begin(), starting_positions.end());
        //select occurences greedily non-overlapping:
        selected_starting_positions.reserve(starting_positions.size());

        int last =  0-length;
        uint current;
        for (std::vector<uint>::iterator it=starting_positions.begin(); it!=starting_positions.end(); ++it){

            current = *it;
            //DLOG(INFO) << "checking starting position: " << current << " length: " << top.first << "last " << last;
            if(last+length <= current){
                selected_starting_positions.push_back(current);
                last = current;

            }

        }
        return selected_starting_positions;
    }

    //could be node_type
    std::vector<std::vector<uint> > lcp_bins;
public:

    using Algorithm::Algorithm; //import constructor

    inline static Meta meta() {
        Meta m("lfs_comp", "esa");

        m.option("textds").templated<text_t, TextDS<>>("textds");
        return m;
    }

    inline void compute_rules(io::InputView & input, rules & dictionary, non_terminal_symbols & nts_symbols){

//env().env_for_option("textds"),
        //const auto input = in.as_view();

        text_t t(env().env_for_option("textds"), input);
       // text_t t(env, in);
        DLOG(INFO) << "building sa and lcp";
        StatPhase::wrap("computing sa and lcp", [&]{

            t.require(text_t::SA | text_t::ISA | text_t::LCP);
        });
        auto& sa_t = t.require_sa();
        auto& lcp_t = t.require_lcp();

        //min_lrf=2;
        StatPhase::wrap("computing lrf occurences", [&]{

        // iterate over lcp array, add indexes with non overlapping prefix length greater than min_lrf_length to vector
        //std::vector<std::pair<uint,uint>> lrf_occurences;

        StatPhase::wrap("computing lrf occs", [&]{

        DLOG(INFO) << "iterate over lcp";
        uint dif ;
        uint factor_length;

        uint max = 0;

        for(uint i = 1; i<lcp_t.size(); i++){

            if(lcp_t[i] >= min_lrf){
                if(max < lcp_t[i]){
                    max = lcp_t[i];
                    lcp_bins.resize(max+1);
                }
                //compute length of non-overlapping factor:

                dif = abs(sa_t[i-1] - sa_t[i]);
                factor_length = lcp_t[i];
                factor_length = std::min(factor_length, dif);

                //maybe greater non-overlapping factor possible with smaller suffix?
                int j =i-1;
                uint alt_dif;
                while(j>0 && lcp_t[j]>factor_length ){
                    alt_dif = abs(sa_t[j] - sa_t[i]);
                    if(alt_dif>dif){
                        dif = alt_dif;
                    }
                    j--;

                }
                factor_length = lcp_t[i];
                factor_length = std::min(factor_length, dif);
                //second is position in suffix array
                //first is length of common prefix
               // std::pair<uint,uint> pair (factor_length, i);
              //  if(factor_length>=min_lrf){
               //     lrf_occurences.push_back(pair);
               // }

                lcp_bins[factor_length].push_back(i);
            }
        }

        DLOG(INFO)<<"max lcp: "<<max;

        });

        //Pq for the non-terminal symbols
        //the first in pair is position, the seconds the number of the non terminal symbol

        DLOG(INFO) << "computing lrfs";

        //vector of text position, length
        //std::vector<std::pair<uint,uint>> dictionary;
      //  StatPhase::wrap("sorting lrf occs", [&]{

      //  std::sort(lrf_occurences.begin(),lrf_occurences.end());
     //   });

        StatPhase::wrap("selecting occs", [&]{

            // Pop PQ, Select occurences of suffix, check if contains replaced symbols
        dead_positions = BitVector(t.size(), 0);

        //std::vector<std::tuple<uint,uint,uint>> nts_symbols;
        nts_symbols.reserve(lcp_bins.size());
        uint non_terminal_symbol_number = 0;

        for(uint lcp_len = lcp_bins.size()-1; lcp_len>= min_lrf; lcp_len--){
            //DLOG(INFO)<<"size of lrf: "  << lcp_len <<" occs: "<< lcp_bins[lcp_len].size();
            for(auto bin_it = lcp_bins[lcp_len].begin(); bin_it!=lcp_bins[lcp_len].end(); bin_it++){

               // if(dead_positions[sa_t[*bin_it]] || dead_positions[sa_t[*bin_it-1]] || dead_positions[sa_t[*bin_it]+lcp_len-1] || dead_positions[sa_t[*bin_it-1]+lcp_len-1]){
               //     continue;
               // }

                //detect all starting positions of this string using the sa and lcp:
                std::vector<uint> starting_positions;
                starting_positions.reserve(20);

                //starting_positions.push_back(sa_t[*bin_it]);

                // and ceck in bitvector viable starting positions
                // there is no 1 bit on the corresponding positions
                // it suffices to check start and end position, because lrf can only be same length and shorter
                uint i = *bin_it;

                uint shorter_dif = lcp_len;

                while(i>=0 && ( lcp_t[i])>=lcp_len){
                    if(!dead_positions[sa_t[i-1]]  && !dead_positions[sa_t[i-1]+lcp_len-1]){
                        starting_positions.push_back(sa_t[i-1]);
                    }

                    if(!dead_positions[sa_t[i-1]] && dead_positions[sa_t[i-1]+lcp_len-1] ){
                        //DLOG(INFO)<<"shorter lrf poss";
                        while(!dead_positions[sa_t[i-1]+lcp_len-shorter_dif]){
                            shorter_dif--;
                        }
                    }
                    i--;

                }
                i = *bin_it;
                while(i< lcp_t.size() &&  lcp_t[i]>=lcp_len){

                    if(!dead_positions[sa_t[i]]  && !dead_positions[sa_t[i]+lcp_len-1]){
                        starting_positions.push_back(sa_t[i]);
                    }
                    if(!dead_positions[sa_t[i]]   && dead_positions[sa_t[i]+lcp_len-1] ){
                        //DLOG(INFO)<<"shorter lrf poss";
                        while(!dead_positions[sa_t[i]+lcp_len-shorter_dif]){
                            shorter_dif--;
                        }
                    }
                    i++;
                }
               // DLOG(INFO)<<"lrf_len: "<<lcp_len<< " shorter dif: "<< shorter_dif;
                //if the factor is still repeating, make the corresponding positions unviable
                if(lcp_len-shorter_dif>=min_lrf){
                    lcp_bins[lcp_len-shorter_dif].push_back(*bin_it);
                }

                if(starting_positions.size()>=2){
                    std::vector<uint> selected_starting_positions = select_starting_positions(starting_positions, lcp_len);
                    //computing substring to be replaced

                    if(selected_starting_positions.size()>=2){

                        uint offset = sa_t[*bin_it];
                        std::pair<uint,uint> longest_repeating_factor(offset, lcp_len);
                        for (std::vector<uint>::iterator it=selected_starting_positions.begin(); it!=selected_starting_positions.end(); ++it){
                            for(uint k = 0; k<lcp_len; k++){
                                dead_positions[*it+k]=1;
                            }

                            uint length_of_symbol = lcp_len;
                            std::tuple<uint,uint,uint> symbol(*it, non_terminal_symbol_number, length_of_symbol);
                            nts_symbols.push_back(symbol);
                        }

                        dictionary.push_back(longest_repeating_factor);
                        non_terminal_symbol_number++;
                    }
                }

            }
        }
        });
        });

        StatPhase::wrap("sorting symbols", [&]{
        DLOG(INFO) << "sorting symbols";
        //, std::greater<std::tuple<uint,uint,uint>>()
        std::sort(nts_symbols.begin(), nts_symbols.end());

        });

    }
};
}
}
<|endoftext|>


<commit_before>// Copyright 2014 BVLC and contributors.
#include <gflags/gflags.h>
#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::string;
using caffe::vector;

// Used in device query
DEFINE_int32(device_id, 0,
             "[devicequery,speedtest] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
              "[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
              "[speedtest] The net proto file to use.");
DEFINE_string(resume_point_file, "",
              "[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
              "[train] (optional) A pretrained network to run finetune from. "
              "Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
             "[speedtest] The number of iterations to run.");
DEFINE_bool(speedtest_with_gpu, false,
            "[speedtest] Test the model with GPU.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe actions that could be called in the form
//     caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);

int devicequery() {
  LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
  caffe::Caffe::SetDevice(FLAGS_device_id);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(devicequery);

int train() {
  CHECK_GT(FLAGS_solver_proto_file.size(), 0);

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);

  LOG(INFO) << "Starting Optimization";
  caffe::SGDSolver<float> solver(solver_param);
  if (FLAGS_resume_point_file.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
    solver.Solve(FLAGS_resume_point_file);
  } else if (FLAGS_pretrained_net_file.size()) {
    LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
    solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
    solver.Solve();
  } else {
    solver.Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

int speedtest() {
  // Set device id and mode
  if (FLAGS_speedtest_with_gpu) {
    LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
    Caffe::SetDevice(FLAGS_device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Caffe::set_phase(Caffe::TRAIN);
  Net<float> caffe_net(FLAGS_net_proto_file);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  forward_timer.Start();
  Timer timer;
  for (int i = 0; i < layers.size(); ++i) {
    const string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
    }
    LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
        " milli seconds.";
  }
  LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
      " milli seconds.";
  Timer backward_timer;
  backward_timer.Start();
  for (int i = layers.size() - 1; i >= 0; --i) {
    const string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          &bottom_vecs[i]);
    }
    LOG(INFO) << layername << "\tbackward: "
        << timer.MilliSeconds() << " milli seconds.";
  }
  LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(speedtest);

int main(int argc, char** argv) {
  caffe::GlobalInit(&argc, &argv);
  CHECK_EQ(argc, 2);
  return GetBrewFunction(string(argv[1]))();
}
<commit_msg>using caffe::string to be consistent with other string definition.<commit_after>// Copyright 2014 BVLC and contributors.
#include <gflags/gflags.h>
#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;

// Used in device query
DEFINE_int32(device_id, 0,
             "[devicequery,speedtest] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
              "[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
              "[speedtest] The net proto file to use.");
DEFINE_string(resume_point_file, "",
              "[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
              "[train] (optional) A pretrained network to run finetune from. "
              "Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
             "[speedtest] The number of iterations to run.");
DEFINE_bool(speedtest_with_gpu, false,
            "[speedtest] Test the model with GPU.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const caffe::string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe actions that could be called in the form
//     caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);

int devicequery() {
  LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
  caffe::Caffe::SetDevice(FLAGS_device_id);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(devicequery);

int train() {
  CHECK_GT(FLAGS_solver_proto_file.size(), 0);

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);

  LOG(INFO) << "Starting Optimization";
  caffe::SGDSolver<float> solver(solver_param);
  if (FLAGS_resume_point_file.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
    solver.Solve(FLAGS_resume_point_file);
  } else if (FLAGS_pretrained_net_file.size()) {
    LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
    solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
    solver.Solve();
  } else {
    solver.Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

int speedtest() {
  // Set device id and mode
  if (FLAGS_speedtest_with_gpu) {
    LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
    Caffe::SetDevice(FLAGS_device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Caffe::set_phase(Caffe::TRAIN);
  Net<float> caffe_net(FLAGS_net_proto_file);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  forward_timer.Start();
  Timer timer;
  for (int i = 0; i < layers.size(); ++i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
    }
    LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
        " milli seconds.";
  }
  LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
      " milli seconds.";
  Timer backward_timer;
  backward_timer.Start();
  for (int i = layers.size() - 1; i >= 0; --i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          &bottom_vecs[i]);
    }
    LOG(INFO) << layername << "\tbackward: "
        << timer.MilliSeconds() << " milli seconds.";
  }
  LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(speedtest);

int main(int argc, char** argv) {
  caffe::GlobalInit(&argc, &argv);
  CHECK_EQ(argc, 2);
  return GetBrewFunction(caffe::string(argv[1]))();
}
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XTENSOR_PYTHON_CONFIG_HPP
#define XTENSOR_PYTHON_CONFIG_HPP

#define XTENSOR_PYTHON_VERSION_MAJOR 0
#define XTENSOR_PYTHON_VERSION_MINOR 9
#define XTENSOR_PYTHON_VERSION_PATCH 1

#endif
<commit_msg>Release 0.9.2<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XTENSOR_PYTHON_CONFIG_HPP
#define XTENSOR_PYTHON_CONFIG_HPP

#define XTENSOR_PYTHON_VERSION_MAJOR 0
#define XTENSOR_PYTHON_VERSION_MINOR 9
#define XTENSOR_PYTHON_VERSION_PATCH 2

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlFixedContent.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-20 19:01:24 $
 *
 *  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 "precompiled_reportdesign.hxx"

#ifndef RPT_XMLFIXEDCONTENT_HXX
#include "xmlFixedContent.hxx"
#endif
#ifndef RPT_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef RPT_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef RPT_XMLREPORTELEMENT_HXX
#include "xmlReportElement.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_REPORT_XSHAPE_HPP_
#include <com/sun/star/report/XShape.hpp>
#endif
#ifndef RPT_XMLFIXEDTEXT_HXX
#include "xmlFixedText.hxx"
#endif
#ifndef RPT_XMLCELL_HXX
#include "xmlCell.hxx"
#endif
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_REPORT_XSHAPE_HPP_
#include <com/sun/star/report/XShape.hpp>
#endif
#include <com/sun/star/text/ControlCharacter.hpp>
#ifndef RPT_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#include <xmloff/XMLCharContext.hxx>

namespace rptxml
{
    using namespace ::com::sun::star;

class OXMLCharContent : public XMLCharContext
{
    OXMLFixedContent* m_pFixedContent;
    OXMLCharContent(const OXMLCharContent&);
    void operator =(const OXMLCharContent&);
public:
    OXMLCharContent(
            SvXMLImport& rImport,
            OXMLFixedContent* _pFixedContent,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const uno::Reference< xml::sax::XAttributeList > & xAttrList,
            sal_Unicode c,
            sal_Bool bCount );
    OXMLCharContent(
            SvXMLImport& rImport,
            OXMLFixedContent* _pFixedContent,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const uno::Reference< xml::sax::XAttributeList > & xAttrList,
            sal_Int16 nControl );

    virtual void InsertControlCharacter(sal_Int16   _nControl);
    virtual void InsertString(const ::rtl::OUString& _sString);
};
OXMLCharContent::OXMLCharContent(
        SvXMLImport& rImport,
        OXMLFixedContent* _pFixedContent,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        sal_Unicode c,
        sal_Bool bCount )
    : XMLCharContext(rImport,nPrfx,rLName,xAttrList,c,bCount)
    ,m_pFixedContent(_pFixedContent)
{
}
// -----------------------------------------------------------------------------
OXMLCharContent::OXMLCharContent(
        SvXMLImport& rImport,
        OXMLFixedContent* _pFixedContent,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        sal_Int16 nControl )
    : XMLCharContext(rImport,nPrfx,rLName,xAttrList,nControl)
    ,m_pFixedContent(_pFixedContent)
{
}
// -----------------------------------------------------------------------------
void OXMLCharContent::InsertControlCharacter(sal_Int16   _nControl)
{
    switch( _nControl )
    {
        case ControlCharacter::LINE_BREAK:
            m_pFixedContent->Characters(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\n")));
            break;
        default:
            OSL_ENSURE(0,"Not supported control character");
            break;
    }
}
// -----------------------------------------------------------------------------
void OXMLCharContent::InsertString(const ::rtl::OUString& _sString)
{
    m_pFixedContent->Characters(_sString);
}
// -----------------------------------------------------------------------------

DBG_NAME( rpt_OXMLFixedContent )

OXMLFixedContent::OXMLFixedContent( ORptFilter& rImport,
                sal_uInt16 nPrfx, const ::rtl::OUString& rLName
                ,OXMLCell& _rCell
                ,OXMLTable* _pContainer
                ,bool _bInP) :
    OXMLReportElementBase( rImport, nPrfx, rLName,NULL,_pContainer)
,m_rCell(_rCell)
,m_bInP(_bInP)
{
    DBG_CTOR( rpt_OXMLFixedContent,NULL);
}
// -----------------------------------------------------------------------------

OXMLFixedContent::~OXMLFixedContent()
{

    DBG_DTOR( rpt_OXMLFixedContent,NULL);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLFixedContent::_CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = OXMLReportElementBase::_CreateChildContext(nPrefix,rLocalName,xAttrList);
    if ( pContext )
        return pContext;
    const SvXMLTokenMap&    rTokenMap   = m_rImport.GetCellElemTokenMap();
    Reference<XMultiServiceFactory> xFactor = m_rImport.getServiceFactory();

    m_rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
    const sal_uInt16 nToken = rTokenMap.Get( nPrefix, rLocalName );
    switch( nToken )
    {
        case XML_TOK_P:
            pContext = new OXMLFixedContent(m_rImport,nPrefix, rLocalName,m_rCell,m_pContainer,true);
            break;
        case XML_TOK_TEXT_TAB_STOP:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                0x0009, sal_False );
            break;

        case XML_TOK_TEXT_LINE_BREAK:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                ControlCharacter::LINE_BREAK );
            break;

        case XML_TOK_TEXT_S:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                0x0020, sal_True );
            break;
    }
    return pContext;
}
// -----------------------------------------------------------------------------
void OXMLFixedContent::EndElement()
{
    if ( m_bInP )
    {
        const Reference<XMultiServiceFactory> xFactor(m_rImport.GetModel(),uno::UNO_QUERY);
        Reference< XFixedText > xControl(xFactor->createInstance(SERVICE_FIXEDTEXT),uno::UNO_QUERY);
        OSL_ENSURE(xControl.is(),"Could not create FixedContent!");
        m_xComponent = xControl.get();
        m_pContainer->addCell(m_xComponent);
        m_rCell.setComponent(m_xComponent);
        xControl->setLabel(m_sLabel);
        OXMLReportElementBase::EndElement();
    }
}
// -----------------------------------------------------------------------------
void OXMLFixedContent::Characters( const ::rtl::OUString& rChars )
{
    m_sLabel += rChars;
}

//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS reportdesign02 (1.4.16); FILE MERGED 2007/12/20 08:42:12 oj 1.4.16.1: #i83193# merge from reportdesign03<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlFixedContent.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2008-01-29 13:45:26 $
 *
 *  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 "precompiled_reportdesign.hxx"

#ifndef RPT_XMLFIXEDCONTENT_HXX
#include "xmlFixedContent.hxx"
#endif
#ifndef RPT_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef RPT_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef RPT_XMLREPORTELEMENT_HXX
#include "xmlReportElement.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_REPORT_XSHAPE_HPP_
#include <com/sun/star/report/XShape.hpp>
#endif
#ifndef RPT_XMLFIXEDTEXT_HXX
#include "xmlFixedText.hxx"
#endif
#ifndef RPT_XMLCELL_HXX
#include "xmlCell.hxx"
#endif
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_REPORT_XSHAPE_HPP_
#include <com/sun/star/report/XShape.hpp>
#endif
#include <com/sun/star/report/XFormattedField.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
#ifndef RPT_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#include <xmloff/XMLCharContext.hxx>

namespace rptxml
{
    using namespace ::com::sun::star;

class OXMLCharContent : public XMLCharContext
{
    OXMLFixedContent* m_pFixedContent;
    OXMLCharContent(const OXMLCharContent&);
    void operator =(const OXMLCharContent&);
public:
    OXMLCharContent(
            SvXMLImport& rImport,
            OXMLFixedContent* _pFixedContent,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const uno::Reference< xml::sax::XAttributeList > & xAttrList,
            sal_Unicode c,
            sal_Bool bCount );
    OXMLCharContent(
            SvXMLImport& rImport,
            OXMLFixedContent* _pFixedContent,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const uno::Reference< xml::sax::XAttributeList > & xAttrList,
            sal_Int16 nControl );

    virtual void InsertControlCharacter(sal_Int16   _nControl);
    virtual void InsertString(const ::rtl::OUString& _sString);
};
OXMLCharContent::OXMLCharContent(
        SvXMLImport& rImport,
        OXMLFixedContent* _pFixedContent,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        sal_Unicode c,
        sal_Bool bCount )
    : XMLCharContext(rImport,nPrfx,rLName,xAttrList,c,bCount)
    ,m_pFixedContent(_pFixedContent)
{
}
// -----------------------------------------------------------------------------
OXMLCharContent::OXMLCharContent(
        SvXMLImport& rImport,
        OXMLFixedContent* _pFixedContent,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const uno::Reference< xml::sax::XAttributeList > & xAttrList,
        sal_Int16 nControl )
    : XMLCharContext(rImport,nPrfx,rLName,xAttrList,nControl)
    ,m_pFixedContent(_pFixedContent)
{
}
// -----------------------------------------------------------------------------
void OXMLCharContent::InsertControlCharacter(sal_Int16   _nControl)
{
    switch( _nControl )
    {
        case ControlCharacter::LINE_BREAK:
            m_pFixedContent->Characters(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\n")));
            break;
        default:
            OSL_ENSURE(0,"Not supported control character");
            break;
    }
}
// -----------------------------------------------------------------------------
void OXMLCharContent::InsertString(const ::rtl::OUString& _sString)
{
    m_pFixedContent->Characters(_sString);
}
// -----------------------------------------------------------------------------

DBG_NAME( rpt_OXMLFixedContent )

OXMLFixedContent::OXMLFixedContent( ORptFilter& rImport,
                sal_uInt16 nPrfx, const ::rtl::OUString& rLName
                ,OXMLCell& _rCell
                ,OXMLTable* _pContainer
                ,OXMLFixedContent* _pInP) :
    OXMLReportElementBase( rImport, nPrfx, rLName,NULL,_pContainer)
,m_rCell(_rCell)
,m_pInP(_pInP)
,m_bFormattedField(false)
{
    DBG_CTOR( rpt_OXMLFixedContent,NULL);
}
// -----------------------------------------------------------------------------

OXMLFixedContent::~OXMLFixedContent()
{

    DBG_DTOR( rpt_OXMLFixedContent,NULL);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLFixedContent::_CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = OXMLReportElementBase::_CreateChildContext(nPrefix,rLocalName,xAttrList);
    if ( pContext )
        return pContext;

    static const ::rtl::OUString s_sStringConcat(RTL_CONSTASCII_USTRINGPARAM(" & "));
    const SvXMLTokenMap&    rTokenMap   = m_rImport.GetCellElemTokenMap();
    Reference<XMultiServiceFactory> xFactor = m_rImport.getServiceFactory();

    m_rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
    const sal_uInt16 nToken = rTokenMap.Get( nPrefix, rLocalName );
    switch( nToken )
    {
        case XML_TOK_P:
            pContext = new OXMLFixedContent(m_rImport,nPrefix, rLocalName,m_rCell,m_pContainer,this);
            break;
        case XML_TOK_TEXT_TAB_STOP:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                0x0009, sal_False );
            break;

        case XML_TOK_TEXT_LINE_BREAK:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                ControlCharacter::LINE_BREAK );
            break;

        case XML_TOK_TEXT_S:
            pContext = new OXMLCharContent( m_rImport, this,nPrefix,
                                                rLocalName, xAttrList,
                                                0x0020, sal_True );
            break;
        case XML_TOK_PAGE_NUMBER:
            m_sPageText += s_sStringConcat + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" PageNumber()"));
            m_bFormattedField = true;
            break;
        case XML_TOK_PAGE_COUNT:
            m_sPageText += s_sStringConcat + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" PageCount()"));
            m_bFormattedField = true;
            break;
        default:
            ;
    }
    return pContext;
}
// -----------------------------------------------------------------------------
void OXMLFixedContent::EndElement()
{
    if ( m_pInP )
    {
        const Reference<XMultiServiceFactory> xFactor(m_rImport.GetModel(),uno::UNO_QUERY);
        if ( m_bFormattedField )
        {
            uno::Reference< uno::XInterface> xInt = xFactor->createInstance(SERVICE_FORMATTEDFIELD);
            Reference< report::XFormattedField > xControl(xInt,uno::UNO_QUERY);
            xControl->setDataField(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("rpt:")) + m_sPageText);
             OSL_ENSURE(xControl.is(),"Could not create FormattedField!");
            m_pInP->m_xComponent = xControl.get();
            m_xComponent = xControl.get();
        }
        else
        {
            Reference< XFixedText > xControl(xFactor->createInstance(SERVICE_FIXEDTEXT),uno::UNO_QUERY);
             OSL_ENSURE(xControl.is(),"Could not create FixedContent!");
            m_pInP->m_xComponent = xControl.get();
            m_xComponent = xControl.get();
            xControl->setLabel(m_sLabel);
        }

        m_pContainer->addCell(m_xComponent);
        m_rCell.setComponent(m_xComponent);

        OXMLReportElementBase::EndElement();
    }
}
// -----------------------------------------------------------------------------
void OXMLFixedContent::Characters( const ::rtl::OUString& rChars )
{
    m_sLabel += rChars;
    if ( rChars.getLength() )
    {
        static const ::rtl::OUString s_Quote(RTL_CONSTASCII_USTRINGPARAM("\""));
        if ( m_sPageText.getLength() )
        {
            static const ::rtl::OUString s_sStringConcat(RTL_CONSTASCII_USTRINGPARAM(" & "));
            m_sPageText += s_sStringConcat;
        }

        m_sPageText += s_Quote + rChars + s_Quote;
    }
}

//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include "Engine.hpp"

class Server {
  public:
    Server();
    ~Server();
  protected:
    int mPort;
    int mControl;

    int maxedConnection;
  private:
    time_t mLastSelect;

    fd_set mRead;
    fd_set mWrite;
    fd_set mError;

    bool mServerOn;
  public:
    bool InitiatePort(int portNum);
    bool ResetPollDescriptors();
    bool ResetFDControllers();
    bool SelectAndPoll();

    void startNewSocket(int ctrl);
}

Server::Server() {

};

Server::~Server() {

}

bool Server::InitiatePort(int portNum) {

}

bool Server::ResetPollDescriptors() {
	FD_ZERO( &mRead  );
	FD_ZERO( &mWrite );
	FD_ZERO( &mError );
	FD_SET( mControl, &mRead );

	maxedConnection	= mControl;
	return true;
}

bool Server::ResetFDControllers() {
  std::list<Socket *>::iterator iter, itern;
  for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
    Socket *s = (*iter);
    itern = ++iter;

	   maxedConnection = Maximum<int>( maxedConnection, s->getFileDescriptor() );
	   FD_SET( s->getFileDescriptor(), &mRead  );
	   FD_SET( s->getFileDescriptor(), &mWrite );
	   FD_SET( s->getFileDescriptor(), &mError );
  }
  return;
}

bool Server::SelectAndPoll() {
  static struct timeval base_time;
	if ( select( maxedConnection+1, &mRead, &mWrite, &mError, &base_time ) < 0 )
	{
	    return false;
	}

	if ( FD_ISSET( mControl, &mRead ) )
	  startNewSocket( mControl );
	return true;
}

void Server::startNewSocket(int ctrl) {

}

<commit_msg>Update Server.cpp<commit_after>#include "Engine.hpp"

class Server {
  public:
    Server();
    ~Server();
  protected:
    int mPort;
    int mControl;

    int maxedConnection;
  private:
    time_t mLastSelect;

    fd_set mRead;
    fd_set mWrite;
    fd_set mError;

    bool mServerOn;
  public:
    bool InitiatePort(int portNum);
    bool ResetPollDescriptors();
    bool ResetFDControllers();
    bool SelectAndPoll();

    void startNewSocket(int ctrl);
}

Server::Server() {

};

Server::~Server() {

}

bool Server::InitiatePort(int portNum) {
	static struct sockaddr_in sa_zero;
	struct sockaddr_in sa;
	int x = 1;
	int fd;

	if ( ( fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
	{
		// -- TODO: insert logging mechanism
		return false;
	}

	if ( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,    (char *) &x, sizeof(x) ) < 0 )
	{
		// -- TODO: insert logging mechanism
		close(fd);
		exit( 1 );
	}

	#if defined(SO_DONTLINGER) && !defined(SYSV)
	{
		struct	linger	ld;
		ld.l_onoff  = 1;
		ld.l_linger = 1000;

		if ( setsockopt( fd, SOL_SOCKET, SO_DONTLINGER,	(char *) &ld, sizeof(ld) ) < 0 ) {
			// -- TODO: insert logging mechanism
			close(fd);
			return false;
		}
	}
	#endif

	sa		    = sa_zero;
	sa.sin_family	    = AF_INET;
	sa.sin_port	    = htons( port );

	if ( bind( fd, (struct sockaddr *) &sa, sizeof(sa) ) < 0 )
	{
		// -- TODO: insert logging mechanism
		close(fd);
		return false;
	}
	if ( listen( fd, 3 ) < 0 )
	{
		// -- TODO: insert logging mechanism
		close(fd);
		exit(1);
	}
	mControl = fd;
	return true;
}

bool Server::ResetPollDescriptors() {
	FD_ZERO( &mRead  );
	FD_ZERO( &mWrite );
	FD_ZERO( &mError );
	FD_SET( mControl, &mRead );

	maxedConnection	= mControl;
	return true;
}

bool Server::ResetFDControllers() {
  std::list<Socket *>::iterator iter, itern;
  for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
    Socket *s = (*iter);
    itern = ++iter;

	   maxedConnection = Maximum<int>( maxedConnection, s->getFileDescriptor() );
	   FD_SET( s->getFileDescriptor(), &mRead  );
	   FD_SET( s->getFileDescriptor(), &mWrite );
	   FD_SET( s->getFileDescriptor(), &mError );
  }
  return;
}

bool Server::SelectAndPoll() {
  static struct timeval base_time;
	if ( select( maxedConnection+1, &mRead, &mWrite, &mError, &base_time ) < 0 )
	{
	    return false;
	}

	if ( FD_ISSET( mControl, &mRead ) )
	  startNewSocket( mControl );
	return true;
}

void Server::startNewSocket(int ctrl) {
    	Socket *s;
    	struct sockaddr_in sock;

    	int desc;

    	socklen_t size;
    	size = sizeof(sock);

    	getsockname( ctrl, (struct sockaddr *) &sock, &size );

    	if ( ( desc = accept( ctrl, (struct sockaddr *) &sock, &size) ) < 0 )
    	{
		// -- TODO: insert log mechanism here
    		return;
    	}

    	#if !defined(FNDELAY)
    		#define FNDELAY O_NDELAY
    	#endif

    	if ( fcntl( desc, F_SETFL, FNDELAY ) == -1 )
    	{
    		// -- TODO: insert log mechanism here
    		return;
    	}

    	s = new Socket();

	// -- attempt to glean the host address/ip
    	size = sizeof(sock);
    	if ( getpeername( desc, (struct sockaddr *) &sock, &size ) < 0 )
    	{
    		// -- TODO: insert logging mechanism
    		s->setHost("UNKNOWN");
    		s->setIpAddress("UNKNOWN");
    	} else {
    		struct hostent *from = gethostbyaddr( (char *) &sock.sin_addr, sizeof(sock.sin_addr), AF_INET );

    		s->setHost(from ? from->h_name : "UNKNOWN");
    		h->setIpAddress(inet_ntoa(sock.sin_addr));
    	}

    	System.mSocketList.push_back(s);
    	s->sendGreeting();
    	return;
}

<|endoftext|>


<commit_before>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Eigen>

#include <sstream>

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const matrix_type::Index& rows = obj->matrix_.rows();
      const matrix_type::Index& cols = obj->matrix_.cols();

      if (len != rows * cols) {
        NanThrowError("Too few coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / rows, i % rows) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      element_type value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
          ctr->NewInstance(
              sizeof(argv)/sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_MATRIX_HPP
<commit_msg>src: fixed 'Matrix.set()' when pass too many coefficients<commit_after>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Eigen>

#include <sstream>

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const matrix_type::Index& rows = obj->matrix_.rows();
      const matrix_type::Index& cols = obj->matrix_.cols();
      const matrix_type::Index& elems = rows * cols;

      if (len != elems) {
        len < rows * cols
          ? NanThrowError("Too few coefficients passed to Matrix")
          : NanThrowError("Too many coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / rows, i % rows) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      element_type value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
          ctr->NewInstance(
              sizeof(argv)/sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_MATRIX_HPP
<|endoftext|>


<commit_before>//
//  Module.cpp
//  Cinder-ControlRoom
//
//  Created by Jean-Pierre Mouilleseaux on 02 Jul 2014.
//  Copyright 2014 Chorded Constructions. All rights reserved.
//

#include "Module.h"

namespace Cinder { namespace ControlRoom {

using namespace ci;
using namespace ci::app;

ModuleRef Module::create(const Rectf& frame) {
    return ModuleRef(new Module(frame));
}

Module::Module(const Rectf& frame) : View(frame) {
    app::App* app = app::App::get();
    mConnectionMouseDown = app->getWindow()->getSignalMouseDown().connect([&](MouseEvent event) {
        mTrackingView = nullptr;

        Vec2i point = convertPointFromView(event.getPos(), nullptr);
        if (!getBounds().contains(point)) {
            return;
        }

        for (const ViewRef& view : mSubviews) {
            if (view->isHidden() || !view->getFrame().contains(point)) {
                continue;
            }

            mTrackingView = view;
            break;
        }

        if (mTrackingView) {
            mTrackingView->mouseDown(event);
        }
        event.setHandled();
    });
    mConnectionMouseDrag = app->getWindow()->getSignalMouseDrag().connect([&](MouseEvent event) {
        if (!mTrackingView) {
            return;
        }

        mTrackingView->mouseDrag(event);
        event.setHandled();
    });
    mConnectionMouseUp = app->getWindow()->getSignalMouseUp().connect([&](MouseEvent event) {
        if (!mTrackingView) {
            return;
        }

        mTrackingView->mouseUp(event);
        event.setHandled();

        mTrackingView = nullptr;
});
}

Module::~Module() {
    mConnectionMouseDown.disconnect();
    mConnectionMouseDrag.disconnect();
    mConnectionMouseUp.disconnect();
}

}}
<commit_msg>order hit check given hidden is rare<commit_after>//
//  Module.cpp
//  Cinder-ControlRoom
//
//  Created by Jean-Pierre Mouilleseaux on 02 Jul 2014.
//  Copyright 2014 Chorded Constructions. All rights reserved.
//

#include "Module.h"

namespace Cinder { namespace ControlRoom {

using namespace ci;
using namespace ci::app;

ModuleRef Module::create(const Rectf& frame) {
    return ModuleRef(new Module(frame));
}

Module::Module(const Rectf& frame) : View(frame) {
    app::App* app = app::App::get();
    mConnectionMouseDown = app->getWindow()->getSignalMouseDown().connect([&](MouseEvent event) {
        mTrackingView = nullptr;

        Vec2i point = convertPointFromView(event.getPos(), nullptr);
        if (!getBounds().contains(point)) {
            return;
        }

        for (const ViewRef& view : mSubviews) {
            if (!view->getFrame().contains(point) || view->isHidden()) {
                continue;
            }

            // TODO - reject on disabled controls

            mTrackingView = view;
            break;
        }

        if (mTrackingView) {
            mTrackingView->mouseDown(event);
        }
        event.setHandled();
    });
    mConnectionMouseDrag = app->getWindow()->getSignalMouseDrag().connect([&](MouseEvent event) {
        if (!mTrackingView) {
            return;
        }

        mTrackingView->mouseDrag(event);
        event.setHandled();
    });
    mConnectionMouseUp = app->getWindow()->getSignalMouseUp().connect([&](MouseEvent event) {
        if (!mTrackingView) {
            return;
        }

        mTrackingView->mouseUp(event);
        event.setHandled();

        mTrackingView = nullptr;
});
}

Module::~Module() {
    mConnectionMouseDown.disconnect();
    mConnectionMouseDrag.disconnect();
    mConnectionMouseUp.disconnect();
}

}}
<|endoftext|>


<commit_before>#include "Caesar.h"

Cryptor::Caesar::Caesar( const std::string& msg, int key, const std::string& symbols, Cryptor::Mode mode )
{
	Message()->SetMsg( msg );
	m_symbols = symbols;
	SetKey( key );
	SetMode( mode );
}

void Cryptor::Caesar::Encrypt()
{
	if( this->GetMode() == Cryptor::Mode::ENCRYPT )
	{
		std::string tmpMsg;
		char symbol;
		int index;

		for( int i = 0; i < Message()->GetMsgLength(); i++ )
		{
			symbol = Message()->GetMsg().at( i );
			if( m_symbols.find( symbol ) != std::string::npos )
			{
				index = m_symbols.find_first_of( symbol );
				index += GetKey();

				if( index >= m_symbols.size() )
					index -= m_symbols.size();

				tmpMsg.push_back( m_symbols.at( index ) );
			}
			else
			{
				tmpMsg.push_back( symbol );
			}
		}

		NewMessage()->SetMsg( tmpMsg );
	}
	else
	{
		Decrypt();
	}
}

void Cryptor::Caesar::Decrypt()
{
	if( this->GetMode() == Cryptor::Mode::DECRYPT )
	{
		std::string tmpMsg;
		char symbol;
		int index;

		for( int i = 0; i < Message()->GetMsgLength(); i++ )
		{
			symbol = Message()->GetMsg().at( i );
			if( m_symbols.find( symbol ) != std::string::npos )
			{
				index = m_symbols.find_first_of( symbol );
				index -= GetKey();

				if( index < 0 )
				{
					index += m_symbols.size();
				}

				tmpMsg.push_back( m_symbols.at( index ) );
			}
			else
			{
				tmpMsg.push_back( symbol );
			}
		}

		NewMessage()->SetMsg( tmpMsg );
	}
	else
	{
		Encrypt();
	}
}
<commit_msg>Create Caesar.cpp<commit_after>#include "Caesar.h"

Cryptor::Caesar::Caesar( const std::string& msg, int key, const std::string& symbols, Cryptor::Mode mode )
{
	Message()->SetMsg( msg );
	m_symbols = symbols;
	SetKey( key );
	SetMode( mode );
}

void Cryptor::Caesar::Encrypt()
{
	if( this->GetMode() == Cryptor::Mode::ENCRYPT )
	{
		std::string tmpMsg;
		char symbol;
		int index;

		for( int i = 0; i < Message()->GetMsgLength(); i++ )
		{
			symbol = Message()->GetMsg().at( i );
			if( m_symbols.find( symbol ) != std::string::npos )
			{
				index = m_symbols.find_first_of( symbol );
				index += GetKey();

				if( index >= m_symbols.size() )
					index -= m_symbols.size();

				tmpMsg.push_back( m_symbols.at( index ) );
			}
			else
			{
				tmpMsg.push_back( symbol );
			}
		}

		NewMessage()->SetMsg( Reverse( tmpMsg ) );
	}
	else
	{
		Decrypt();
	}
}

void Cryptor::Caesar::Decrypt()
{
	if( this->GetMode() == Cryptor::Mode::DECRYPT )
	{
		std::string tmpMsg;
		char symbol;
		int index;

		for( int i = 0; i < Message()->GetMsgLength(); i++ )
		{
			symbol = Message()->GetMsg().at( i );
			if( m_symbols.find( symbol ) != std::string::npos )
			{
				index = m_symbols.find_first_of( symbol );
				index -= GetKey();

				if( index < 0 )
				{
					index += m_symbols.size();
				}

				tmpMsg.push_back( m_symbols.at( index ) );
			}
			else
			{
				tmpMsg.push_back( symbol );
			}
		}

		NewMessage()->SetMsg( Reverse( tmpMsg ) );
	}
	else
	{
		Encrypt();
	}
}

std::string Cryptor::Caesar::Reverse( const std::string& other )
{
	std::string reverse;

	for( int i = other.length() - 1; i >= 0; i-- )
	{
		reverse.push_back( other.at( i ) );
	}

	return reverse;
}
<|endoftext|>


<commit_before>#include <Candle.h>
#include <FastLED.h>

Candle::Candle(uint8_t brightness_min, uint8_t brightness_max, uint8_t steps_min, uint8_t steps_max) :
    _brightness_min(brightness_min),
    _brightness_max(brightness_max),
    _steps_min(steps_min),
    _steps_max(steps_max),
    _step(0),
    _steps(0),
    _brightness(0) {};

uint8_t Candle::get_next_brightness() {
    uint8_t new_brightness;

    // Return next brightness value for candle

    if (_step > _steps) {
        // Update target brightness and delay

        // Get new brightness
        new_brightness = random8(_brightness_min, _brightness_max);

        // Update candle steps
        _steps = random8(
            _steps_min, max(new_brightness - _brightness, _steps_max)
        );

        // Amount of change for every step
        _brightness_delta = (new_brightness - _brightness) / _steps;
        if (_brightness_delta == 0) _brightness_delta = 1;

        // Serial.println(12345);
        // Serial.println(brightness);
        // Serial.println(new_brightness);
        // Serial.println(candle_steps);
        // Serial.println(_brightness_delta);
        // Serial.println(12345);

        // Reset step counter
        _step = 0;
    }

    // Set (and limit) brightness
    if (_brightness_delta > 0) {
        _brightness = qadd8(_brightness, _brightness_delta);
    } else {
        _brightness += _brightness_delta;
    }

    _step++;

    return ease8InOutCubic(_brightness);
}
<commit_msg>Includes more in line with examples.<commit_after>#include "Candle.h"
#include "Arduino.h"
#include <FastLED.h>

Candle::Candle(uint8_t brightness_min, uint8_t brightness_max, uint8_t steps_min, uint8_t steps_max) :
    _brightness_min(brightness_min),
    _brightness_max(brightness_max),
    _steps_min(steps_min),
    _steps_max(steps_max),
    _step(0),
    _steps(0),
    _brightness(0) {};

uint8_t Candle::get_next_brightness() {
    uint8_t new_brightness;

    // Return next brightness value for candle

    if (_step > _steps) {
        // Update target brightness and delay

        // Get new brightness
        new_brightness = random8(_brightness_min, _brightness_max);

        // Update candle steps
        _steps = random8(
            _steps_min, max(new_brightness - _brightness, _steps_max)
        );

        // Amount of change for every step
        _brightness_delta = (new_brightness - _brightness) / _steps;
        if (_brightness_delta == 0) _brightness_delta = 1;

        // Serial.println(12345);
        // Serial.println(brightness);
        // Serial.println(new_brightness);
        // Serial.println(candle_steps);
        // Serial.println(_brightness_delta);
        // Serial.println(12345);

        // Reset step counter
        _step = 0;
    }

    // Set (and limit) brightness
    if (_brightness_delta > 0) {
        _brightness = qadd8(_brightness, _brightness_delta);
    } else {
        _brightness += _brightness_delta;
    }

    _step++;

    return ease8InOutCubic(_brightness);
}
<|endoftext|>


<commit_before>/***************************************************************************//**
 * \mainpage PetIBM
 *
 *                A PETSc-based Immersed Boundary Method code
 *
 * \author Anush Krishnan (anush@bu.edu)
 *         Olivier Mesnard (mesnardo@gwu.edu)
 */

/***************************************************************************//**
 * \file PetIBM.cpp
 * \author Anush Krishnan (anush@bu.edu)
 * \brief Main source-file of `PetIBM`.
 */

#include "createSolver.h"

#ifndef DIMENSIONS
#define DIMENSIONS 2
#endif

int main(int argc,char **argv)
{
  const PetscInt dim = DIMENSIONS;
  PetscErrorCode ierr;

  ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n======================\n*** PetIBM - Start ***\n======================\n"); CHKERRQ(ierr);

  // parse command-line to get simulation directory
  char dir[PETSC_MAX_PATH_LEN];
  PetscBool found;
  ierr = PetscOptionsGetString(NULL, NULL, "-directory", dir, sizeof(dir), &found); CHKERRQ(ierr);
  std::string directory(".");
  if (found)
    directory = dir;
  ierr = PetscPrintf(PETSC_COMM_WORLD, "directory: %s\n", directory.c_str()); CHKERRQ(ierr);

  // read different input files
  CartesianMesh mesh(directory);
  ierr = mesh.printInfo(); CHKERRQ(ierr);
  ierr = mesh.write(directory+"/grid.txt");
  FlowDescription<dim> flow(directory);
  ierr = flow.printInfo(); CHKERRQ(ierr);
  SimulationParameters parameters(directory);
  ierr = parameters.printInfo(); CHKERRQ(ierr);

  std::unique_ptr< NavierStokesSolver<dim> > solver = createSolver<dim>(&mesh,
                                                                        &flow,
                                                                        &parameters);

  ierr = solver->initialize(); CHKERRQ(ierr);

  while(!solver->finished())
  {
    ierr = solver->stepTime(); CHKERRQ(ierr);
    ierr = solver->writeData(); CHKERRQ(ierr);
  }

  ierr = solver->finalize(); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n=====================\n*** PetIBM - Done ***\n=====================\n"); CHKERRQ(ierr);

  ierr = PetscFinalize(); CHKERRQ(ierr);

  return 0;
} // main<commit_msg>Output initial solution into files<commit_after>/***************************************************************************//**
 * \mainpage PetIBM
 *
 *                A PETSc-based Immersed Boundary Method code
 *
 * \author Anush Krishnan (anush@bu.edu)
 *         Olivier Mesnard (mesnardo@gwu.edu)
 */

/***************************************************************************//**
 * \file PetIBM.cpp
 * \author Anush Krishnan (anush@bu.edu)
 * \brief Main source-file of `PetIBM`.
 */

#include "createSolver.h"

#ifndef DIMENSIONS
#define DIMENSIONS 2
#endif

int main(int argc,char **argv)
{
  const PetscInt dim = DIMENSIONS;
  PetscErrorCode ierr;

  ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n======================\n*** PetIBM - Start ***\n======================\n"); CHKERRQ(ierr);

  // parse command-line to get simulation directory
  char dir[PETSC_MAX_PATH_LEN];
  PetscBool found;
  ierr = PetscOptionsGetString(NULL, NULL, "-directory", dir, sizeof(dir), &found); CHKERRQ(ierr);
  std::string directory(".");
  if (found)
    directory = dir;
  ierr = PetscPrintf(PETSC_COMM_WORLD, "directory: %s\n", directory.c_str()); CHKERRQ(ierr);

  // read different input files
  CartesianMesh mesh(directory);
  ierr = mesh.printInfo(); CHKERRQ(ierr);
  ierr = mesh.write(directory+"/grid.txt");
  FlowDescription<dim> flow(directory);
  ierr = flow.printInfo(); CHKERRQ(ierr);
  SimulationParameters parameters(directory);
  ierr = parameters.printInfo(); CHKERRQ(ierr);

  std::unique_ptr< NavierStokesSolver<dim> > solver = createSolver<dim>(&mesh,
                                                                        &flow,
                                                                        &parameters);

  ierr = solver->initialize(); CHKERRQ(ierr);
  ierr = solver->writeData(); CHKERRQ(ierr);

  while(!solver->finished())
  {
    ierr = solver->stepTime(); CHKERRQ(ierr);
    ierr = solver->writeData(); CHKERRQ(ierr);
  }

  ierr = solver->finalize(); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n=====================\n*** PetIBM - Done ***\n=====================\n"); CHKERRQ(ierr);

  ierr = PetscFinalize(); CHKERRQ(ierr);

  return 0;
} // main<|endoftext|>


<commit_before>/***************************************************************************//**
 * \mainpage PetIBM
 *
 *                A PETSc-based Immersed Boundary Method code
 *
 * \author Anush Krishnan (anush@bu.edu)
 *         Olivier Mesnard (mesnardo@gwu.edu)
 */

/***************************************************************************//**
 * \file PetIBM.cpp
 * \author Anush Krishnan (anush@bu.edu)
 * \brief Main source-file of `PetIBM`.
 */

#include "createSolver.h"

#ifndef DIMENSIONS
#define DIMENSIONS 2
#endif

int main(int argc,char **argv)
{
  const PetscInt dim = DIMENSIONS;
  PetscErrorCode ierr;

  ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n======================\n*** PetIBM - Start ***\n======================\n"); CHKERRQ(ierr);

  // parse command-line to get simulation directory
  char dir[PETSC_MAX_PATH_LEN];
  PetscBool found;
  ierr = PetscOptionsGetString(NULL, NULL, "-directory", dir, sizeof(dir), &found); CHKERRQ(ierr);
  std::string directory(".");
  if (found)
    directory = dir;
  ierr = PetscPrintf(PETSC_COMM_WORLD, "directory: %s\n", directory.c_str()); CHKERRQ(ierr);

  // read different input files
  CartesianMesh mesh(directory);
  ierr = mesh.printInfo(); CHKERRQ(ierr);
  ierr = mesh.write(directory+"/grid.txt");
  FlowDescription<dim> flow(directory);
  ierr = flow.printInfo(); CHKERRQ(ierr);
  SimulationParameters parameters(directory);
  ierr = parameters.printInfo(); CHKERRQ(ierr);

  std::unique_ptr< NavierStokesSolver<dim> > solver = createSolver<dim>(&mesh,
                                                                        &flow,
                                                                        &parameters);

  ierr = solver->initialize(); CHKERRQ(ierr);

  while(!solver->finished())
  {
    ierr = solver->stepTime(); CHKERRQ(ierr);
    ierr = solver->writeData(); CHKERRQ(ierr);
  }

  ierr = solver->finalize(); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n=====================\n*** PetIBM - Done ***\n=====================\n"); CHKERRQ(ierr);

  ierr = PetscFinalize(); CHKERRQ(ierr);

  return 0;
} // main<commit_msg>Add message when initialization complete<commit_after>/***************************************************************************//**
 * \mainpage PetIBM
 *
 *                A PETSc-based Immersed Boundary Method code
 *
 * \author Anush Krishnan (anush@bu.edu)
 *         Olivier Mesnard (mesnardo@gwu.edu)
 */

/***************************************************************************//**
 * \file PetIBM.cpp
 * \author Anush Krishnan (anush@bu.edu)
 * \brief Main source-file of `PetIBM`.
 */

#include "createSolver.h"

#ifndef DIMENSIONS
#define DIMENSIONS 2
#endif

int main(int argc,char **argv)
{
  const PetscInt dim = DIMENSIONS;
  PetscErrorCode ierr;

  ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n======================\n*** PetIBM - Start ***\n======================\n"); CHKERRQ(ierr);

  // parse command-line to get simulation directory
  char dir[PETSC_MAX_PATH_LEN];
  PetscBool found;
  ierr = PetscOptionsGetString(NULL, NULL, "-directory", dir, sizeof(dir), &found); CHKERRQ(ierr);
  std::string directory(".");
  if (found)
    directory = dir;
  ierr = PetscPrintf(PETSC_COMM_WORLD, "directory: %s\n", directory.c_str()); CHKERRQ(ierr);

  // read different input files
  CartesianMesh mesh(directory);
  ierr = mesh.printInfo(); CHKERRQ(ierr);
  ierr = mesh.write(directory+"/grid.txt");
  FlowDescription<dim> flow(directory);
  ierr = flow.printInfo(); CHKERRQ(ierr);
  SimulationParameters parameters(directory);
  ierr = parameters.printInfo(); CHKERRQ(ierr);

  std::unique_ptr< NavierStokesSolver<dim> > solver = createSolver<dim>(&mesh,
                                                                        &flow,
                                                                        &parameters);

  ierr = solver->initialize(); CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "\nInitialization complete!\n"); CHKERRQ(ierr);

  while(!solver->finished())
  {
    ierr = solver->stepTime(); CHKERRQ(ierr);
    ierr = solver->writeData(); CHKERRQ(ierr);
  }

  ierr = solver->finalize(); CHKERRQ(ierr);

  ierr = PetscPrintf(PETSC_COMM_WORLD, "\n=====================\n*** PetIBM - Done ***\n=====================\n"); CHKERRQ(ierr);

  ierr = PetscFinalize(); CHKERRQ(ierr);

  return 0;
} // main<|endoftext|>