<commit_before>#include <cstdint>
#include <time.h>

#include "PosixTimespec.hpp"

//==============================================================================
//
//==============================================================================
PosixTimespec::PosixTimespec(const timespec& tp) :
    tp(tp)
{
}

//==============================================================================
//
//==============================================================================
PosixTimespec::~PosixTimespec()
{
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator=(const timespec& tp)
{
    this->tp.tv_sec  = tp.tv_sec;
    this->tp.tv_nsec = tp.tv_nsec;

    return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator+=(const timespec& tp)
{
    this->tp.tv_sec += tp.tv_sec;
    this->tp.tv_nsec += tp.tv_nsec;

    // Do we need to add one to tv_sec?
    if (std::uint64_t(this->tp.tv_nsec) + std::uint64_t(tp.tv_nsec) > 1e9)
    {
        this->tp.tv_sec += 1;
    }

    return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator+=(const PosixTimespec& tp)
{
    timespec tp_temp;
    tp.getTimespec(tp_temp);

    return operator+=(tp_temp);
}

//==============================================================================
//
//==============================================================================
/*PosixTimespec& PosixTimespec::operator-=(const timespec& tp)
{
    // Do the subtraction

    //return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator-=(const PosixTimespec& tp)
{
    timespec tp_temp;
    tp.getTimespec(tp_temp);

    return operator-=(tp_temp);
    }*/

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(PosixTimespec lhs, const PosixTimespec& rhs)
{
    lhs += rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(PosixTimespec lhs, const timespec& rhs)
{
    lhs += rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(timespec lhs, const PosixTimespec& rhs)
{
    // Addition is symmetric
    return operator+(rhs, lhs);
}

//==============================================================================
//
//==============================================================================
/*PosixTimespec operator-(PosixTimespec lhs, const PosixTimespec& rhs)
{
    lhs -= rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator-(PosixTimespec lhs, const timespec& rhs)
{
    lhs -= rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator-(timespec lhs, const PosixTimespec& rhs)
{
    // TODO
    }*/

//==============================================================================
//
//==============================================================================
bool operator==(const PosixTimespec& lhs, const PosixTimespec& rhs)
{
    timespec lhs_tp;
    timespec rhs_tp;

    lhs.getTimespec(lhs_tp);
    rhs.getTimespec(rhs_tp);

    return lhs_tp.tv_sec == rhs_tp.tv_sec && lhs_tp.tv_nsec == rhs_tp.tv_nsec;
}

//==============================================================================
//
//==============================================================================
bool operator==(const PosixTimespec& lhs, const timespec& rhs)
{
    return lhs == PosixTimespec(rhs);
}

//==============================================================================
//
//==============================================================================
bool operator==(const timespec& lhs, const PosixTimespec& rhs)
{
    return PosixTimespec(lhs) == rhs;
}

//==============================================================================
//
//==============================================================================
bool operator!=(const PosixTimespec& lhs, const PosixTimespec& rhs)
{
    return !(lhs == rhs);
}

//==============================================================================
//
//==============================================================================
bool operator!=(const PosixTimespec& lhs, const timespec& rhs)
{
    return !(lhs == rhs);
}

//==============================================================================
//
//==============================================================================
bool operator!=(const timespec& lhs, const PosixTimespec& rhs)
{
    return !(lhs == rhs);
}
<commit_msg>Different implementation that doesnt require C++11<commit_after>#include <climits>
#include <time.h>

#include "PosixTimespec.hpp"

//==============================================================================
//
//==============================================================================
PosixTimespec::PosixTimespec(const timespec& tp) :
    tp(tp)
{
}

//==============================================================================
//
//==============================================================================
PosixTimespec::~PosixTimespec()
{
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator=(const timespec& tp)
{
    this->tp.tv_sec  = tp.tv_sec;
    this->tp.tv_nsec = tp.tv_nsec;

    return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator+=(const timespec& tp)
{
    this->tp.tv_sec += tp.tv_sec;
    this->tp.tv_nsec += tp.tv_nsec;

    // Do we need to add one to tv_sec?
    if (this->tp.tv_nsec >= 1e9 - tp.tv_nsec)
    {
        this->tp.tv_sec += 1;
    }

    return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator+=(const PosixTimespec& tp)
{
    timespec tp_temp;
    tp.getTimespec(tp_temp);

    return operator+=(tp_temp);
}

//==============================================================================
//
//==============================================================================
/*PosixTimespec& PosixTimespec::operator-=(const timespec& tp)
{
    // Do the subtraction

    //return *this;
}

//==============================================================================
//
//==============================================================================
PosixTimespec& PosixTimespec::operator-=(const PosixTimespec& tp)
{
    timespec tp_temp;
    tp.getTimespec(tp_temp);

    return operator-=(tp_temp);
    }*/

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(PosixTimespec lhs, const PosixTimespec& rhs)
{
    lhs += rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(PosixTimespec lhs, const timespec& rhs)
{
    lhs += rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator+(timespec lhs, const PosixTimespec& rhs)
{
    // Addition is symmetric
    return operator+(rhs, lhs);
}

//==============================================================================
//
//==============================================================================
/*PosixTimespec operator-(PosixTimespec lhs, const PosixTimespec& rhs)
{
    lhs -= rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator-(PosixTimespec lhs, const timespec& rhs)
{
    lhs -= rhs;
    return lhs;
}

//==============================================================================
//
//==============================================================================
PosixTimespec operator-(timespec lhs, const PosixTimespec& rhs)
{
    // TODO
    }*/

//==============================================================================
//
//==============================================================================
bool operator==(const PosixTimespec& lhs, const PosixTimespec& rhs)
{
    timespec lhs_tp;
    timespec rhs_tp;

    lhs.getTimespec(lhs_tp);
    rhs.getTimespec(rhs_tp);

    return lhs_tp.tv_sec == rhs_tp.tv_sec && lhs_tp.tv_nsec == rhs_tp.tv_nsec;
}

//==============================================================================
//
//==============================================================================
bool operator==(const PosixTimespec& lhs, const timespec& rhs)
{
    return lhs == PosixTimespec(rhs);
}

//==============================================================================
//
//==============================================================================
bool operator==(const timespec& lhs, const PosixTimespec& rhs)
{
    return PosixTimespec(lhs) == rhs;
}

//==============================================================================
//
//==============================================================================
bool operator!=(const PosixTimespec& lhs, const PosixTimespec& rhs)
{
    return !(lhs == rhs);
}

//==============================================================================
//
//==============================================================================
bool operator!=(const PosixTimespec& lhs, const timespec& rhs)
{
    return !(lhs == rhs);
}

//==============================================================================
//
//==============================================================================
bool operator!=(const timespec& lhs, const PosixTimespec& rhs)
{
    return !(lhs == rhs);
}
<|endoftext|>


<commit_before>//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <cctype>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "google/protobuf/text_format.h"
#include "src/config.pb.h"
#include "src/linter.h"

ABSL_FLAG(std::string, config, "",
          "A prototxt file having configuration options.");

ABSL_FLAG(bool, quick, false,
          "Read from standart input. It will read one"
          "statement and continue until reading semicolon ';'");

ABSL_FLAG(bool, parsed_ast, false, "Print parsed AST for the input queries.");

namespace zetasql::linter {
namespace {

std::string ReadFile(std::string filename) {
  std::ifstream file(filename.c_str());
  std::string str = "";
  for (std::string line; std::getline(file, line);) {
    str += line + "\n";
  }
  return str;
}

Config ReadFromConfigFile(std::string filename) {
  Config config;
  std::string str = ReadFile(filename);
  if (!google::protobuf::TextFormat::ParseFromString(str, &config)) {
    std::cerr << "Configuration file couldn't be parsed." << std::endl;
    config = Config();
  }
  return config;
}

bool HasValidExtension(std::string filename) {
  std::vector<std::string> supported_extensions{".sql", ".sqlm", ".sqlp",
                                                ".sqlt", ".gsql"};

  std::string extension_str = absl::StrJoin(supported_extensions.begin(),
                                            supported_extensions.end(), ", ");

  bool ok = false;
  std::string extension = "";
  // Find until last '.';
  for (int i = filename.size() - 1; i >= 0; i--) {
    extension = filename[i] + extension;
    if (filename[i] == '.') break;
  }

  for (std::string supported_extension : supported_extensions)
    if (supported_extension == extension) ok = true;
  if (!ok) {
    std::cerr << "Ignoring " << filename << ";  not have a valid extension ("
              << extension_str << ")" << std::endl;
    return 0;
  }
  return 1;
}

void quick_run(Config config) {
  std::string str = "";
  for (std::string line; std::getline(std::cin, line);) {
    bool end = false;
    for (char c : line) {
      str += c;
      if (c == ';') {
        end = true;
        break;
      }
    }
    str += "\n";
    if (end) break;
  }
  zetasql::linter::LinterResult result =
      zetasql::linter::RunChecks(absl::string_view(str), config, "");

  result.PrintResult();
}

void run(std::vector<std::string> sql_files, Config config) {
  bool debug = absl::GetFlag(FLAGS_parsed_ast);
  bool runner = true;
  for (std::string filename : sql_files) {
    // The first argument is './runner'.
    if (runner || !HasValidExtension(filename)) {
      runner = false;
      continue;
    }
    std::string str = ReadFile(filename);
    if (debug) PrintASTTree(str);
    LinterResult result = RunChecks(absl::string_view(str), config, filename);

    result.PrintResult();
  }
}

}  // namespace
}  // namespace zetasql::linter

class B {
 public:
 private:
  std::vector<std::unique_ptr<bool>> v;
};

void ff(const B& a) {}

int main(int argc, char* argv[]) {
  B a;
  ff(a);
  // std::function<int(const B &)>> x;
  if (argc < 2) {
    std::cerr << "Usage: ./runner --config=<config_file> <file_names>\n"
              << std::endl;
    return 1;
  }

  std::vector<std::string> sql_files;
  for (char* file : absl::ParseCommandLine(argc, argv))
    sql_files.push_back(std::string(file));
  std::string config_file = absl::GetFlag(FLAGS_config);
  bool quick = absl::GetFlag(FLAGS_quick);

  zetasql::linter::Config config =
      zetasql::linter::ReadFromConfigFile(config_file);

  if (quick)
    zetasql::linter::quick_run(config);
  else
    zetasql::linter::run(sql_files, config);

  return 0;
}
<commit_msg>review changes<commit_after>//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <cctype>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "google/protobuf/text_format.h"
#include "src/config.pb.h"
#include "src/linter.h"

ABSL_FLAG(std::string, config, "",
          "A prototxt file having configuration options.");

ABSL_FLAG(bool, quick, false,
          "Read from standart input. It will read one"
          "statement and continue until reading semicolon ';'");

ABSL_FLAG(bool, parsed_ast, false, "Print parsed AST for the input queries.");

namespace zetasql::linter {
namespace {

std::string ReadFile(std::string filename) {
  std::ifstream file(filename.c_str());
  std::string str = "";
  for (std::string line; std::getline(file, line);) {
    str += line + "\n";
  }
  return str;
}

Config ReadFromConfigFile(std::string filename) {
  Config config;
  std::string str = ReadFile(filename);
  if (!google::protobuf::TextFormat::ParseFromString(str, &config)) {
    std::cerr << "Configuration file couldn't be parsed." << std::endl;
    config = Config();
  }
  return config;
}

bool HasValidExtension(std::string filename) {
  std::vector<std::string> supported_extensions{".sql", ".sqlm", ".sqlp",
                                                ".sqlt", ".gsql"};

  std::string extension_str = absl::StrJoin(supported_extensions.begin(),
                                            supported_extensions.end(), ", ");

  bool ok = false;
  std::string extension = "";
  // Find until last '.';
  for (int i = filename.size() - 1; i >= 0; i--) {
    extension = filename[i] + extension;
    if (filename[i] == '.') break;
  }

  for (std::string supported_extension : supported_extensions)
    if (supported_extension == extension) ok = true;
  if (!ok) {
    std::cerr << "Ignoring " << filename << ";  not have a valid extension ("
              << extension_str << ")" << std::endl;
    return 0;
  }
  return 1;
}

void quick_run(Config config) {
  std::string str = "";
  for (std::string line; std::getline(std::cin, line);) {
    bool end = false;
    for (char c : line) {
      str += c;
      if (c == ';') {
        end = true;
        break;
      }
    }
    str += "\n";
    if (end) break;
  }
  zetasql::linter::LinterResult result =
      zetasql::linter::RunChecks(absl::string_view(str), config, "");

  result.PrintResult();
}

void run(std::vector<std::string> sql_files, Config config) {
  bool debug = absl::GetFlag(FLAGS_parsed_ast);
  bool runner = true;
  for (std::string filename : sql_files) {
    // The first argument is './runner'.
    if (runner || !HasValidExtension(filename)) {
      runner = false;
      continue;
    }
    std::string str = ReadFile(filename);
    if (debug) PrintASTTree(str);
    LinterResult result = RunChecks(absl::string_view(str), config, filename);

    result.PrintResult();
  }
}

}  // namespace
}  // namespace zetasql::linter

int main(int argc, char* argv[]) {
  if (argc < 2) {
    std::cerr << "Usage: ./runner --config=<config_file> <file_names>\n"
              << std::endl;
    return 1;
  }

  std::vector<std::string> sql_files;
  for (char* file : absl::ParseCommandLine(argc, argv))
    sql_files.push_back(std::string(file));
  std::string config_file = absl::GetFlag(FLAGS_config);
  bool quick = absl::GetFlag(FLAGS_quick);

  zetasql::linter::Config config =
      zetasql::linter::ReadFromConfigFile(config_file);

  if (quick)
    zetasql::linter::quick_run(config);
  else
    zetasql::linter::run(sql_files, config);

  return 0;
}
<|endoftext|>


<commit_before>// stl include
#include <string>

// module include
#include "DefaultDigitizerModule.hpp"

// framework includes
#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"
#include "core/utils/random.h"
#include "core/utils/unit.h"

// ROOT includes
#include <TFile.h>
#include <TH1D.h>
#include <TProfile.h>

#include "objects/PixelHit.hpp"

using namespace allpix;

// Constructor to load the module
DefaultDigitizerModule::DefaultDigitizerModule(Configuration config,
                                               Messenger* messenger,
                                               std::shared_ptr<Detector> detector)
    : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {

    // Require PixelCharge message for single detector
    messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);

    // Seed the random generator
    random_generator_.seed(get_random_seed());

    // Set defaults for config variables
    config_.setDefault<int>("electronics_noise", Units::get(110, "e"));
    config_.setDefault<int>("threshold", Units::get(600, "e"));
    config_.setDefault<int>("threshold_smearing", Units::get(30, "e"));
    config_.setDefault<int>("adc_smearing", Units::get(300, "e"));

    config_.setDefault<bool>("output_plots", false);
}

// Initialize output plots
void DefaultDigitizerModule::init() {
    if(config_.get<bool>("output_plots")) {
        LOG(TRACE) << "Creating output plots";

        // book histograms:
        h_pxq = new TH1D("pixelcharge", "raw pixel charge;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_noise = new TH1D("pixelcharge_noise_", "pixel charge w/ el. noise;pixel charge [ke];pixels", 100, 0, 10);
        h_thr = new TH1D("threshold", "applied threshold; threshold [ke];events", 100, 0, 10);
        h_pxq_thr = new TH1D("pixelcharge_threshold_", "pixel charge above threshold;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_adc = new TH1D("pixelcharge_adc", "pixel charge after ADC;pixel charge [ke];pixels", 100, 0, 10);
    }
}

// run method fetching a message and outputting its own
void DefaultDigitizerModule::run(unsigned int) {

    // Loop through all pixels with charges
    std::vector<PixelHit> hits;
    for(auto& pixel_charge : pixel_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto charge = static_cast<double>(pixel_charge.getCharge());

        LOG(DEBUG) << "Received pixel (" << pixel.x() << "," << pixel.y() << "), charge " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq->Fill(charge / 1e3);
        }

        // Add electronics noise from Gaussian:
        std::normal_distribution<double> el_noise(0, config_.get<unsigned int>("electronics_noise"));
        charge += el_noise(random_generator_);

        LOG(DEBUG) << "Charge with noise: " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_noise->Fill(charge / 1e3);
        }

        // FIXME Simulate gain / gain smearing

        // Smear the threshold, Gaussian distribution around "threshold" with width "threshold_smearing"
        std::normal_distribution<double> thr_smearing(config_.get<unsigned int>("threshold"),
                                                      config_.get<unsigned int>("threshold_smearing"));
        double threshold = thr_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_thr->Fill(threshold / 1e3);
        }

        // Discard charges below threshold:
        if(charge < threshold) {
            LOG(DEBUG) << "Below smeared threshold: " << Units::display(charge, "e") << " < "
                       << Units::display(threshold, "e");
            continue;
        }

        LOG(DEBUG) << "Passed threshold: " << Units::display(charge, "e") << " > " << Units::display(threshold, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_thr->Fill(charge / 1e3);
        }

        // Add ADC smearing:
        std::normal_distribution<double> adc_smearing(0, config_.get<unsigned int>("adc_smearing"));
        charge += adc_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_pxq_adc->Fill(charge / 1e3);
        }

        // Add the hit to the hitmap
        hits.emplace_back(pixel);

        // FIXME Simulate analog / digital cross talk
        // double crosstalk_neigubor_row = 0.00;
        // double crosstalk_neigubor_column = 0.00;
    }

    // output summary and update statistics
    LOG(INFO) << "Digitized " << hits.size() << " pixel hits";
    total_hits_ += hits.size();

    if(!hits.empty()) {
        // Create and dispatch hit message
        auto hits_message = std::make_shared<PixelHitMessage>(std::move(hits), getDetector());
        messenger_->dispatchMessage(this, hits_message);
    }
}

// Create file and write the histograms to it if we have plots enabled
void DefaultDigitizerModule::finalize() {
    if(config_.get<bool>("output_plots")) {
        // Write histograms
        LOG(TRACE) << "Writing output plots to file";
        h_pxq->Write();
        h_pxq_noise->Write();
        h_thr->Write();
        h_pxq_thr->Write();
        h_pxq_adc->Write();
    }

    LOG(INFO) << "Digitized " << total_hits_ << " pixel hits in total";
}
<commit_msg>DefaultDigitizer stores pixel hit charge<commit_after>// stl include
#include <string>

// module include
#include "DefaultDigitizerModule.hpp"

// framework includes
#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"
#include "core/utils/random.h"
#include "core/utils/unit.h"

// ROOT includes
#include <TFile.h>
#include <TH1D.h>
#include <TProfile.h>

#include "objects/PixelHit.hpp"

using namespace allpix;

// Constructor to load the module
DefaultDigitizerModule::DefaultDigitizerModule(Configuration config,
                                               Messenger* messenger,
                                               std::shared_ptr<Detector> detector)
    : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {

    // Require PixelCharge message for single detector
    messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);

    // Seed the random generator
    random_generator_.seed(get_random_seed());

    // Set defaults for config variables
    config_.setDefault<int>("electronics_noise", Units::get(110, "e"));
    config_.setDefault<int>("threshold", Units::get(600, "e"));
    config_.setDefault<int>("threshold_smearing", Units::get(30, "e"));
    config_.setDefault<int>("adc_smearing", Units::get(300, "e"));

    config_.setDefault<bool>("output_plots", false);
}

// Initialize output plots
void DefaultDigitizerModule::init() {
    if(config_.get<bool>("output_plots")) {
        LOG(TRACE) << "Creating output plots";

        // book histograms:
        h_pxq = new TH1D("pixelcharge", "raw pixel charge;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_noise = new TH1D("pixelcharge_noise_", "pixel charge w/ el. noise;pixel charge [ke];pixels", 100, 0, 10);
        h_thr = new TH1D("threshold", "applied threshold; threshold [ke];events", 100, 0, 10);
        h_pxq_thr = new TH1D("pixelcharge_threshold_", "pixel charge above threshold;pixel charge [ke];pixels", 100, 0, 10);
        h_pxq_adc = new TH1D("pixelcharge_adc", "pixel charge after ADC;pixel charge [ke];pixels", 100, 0, 10);
    }
}

// run method fetching a message and outputting its own
void DefaultDigitizerModule::run(unsigned int) {

    // Loop through all pixels with charges
    std::vector<PixelHit> hits;
    for(auto& pixel_charge : pixel_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto charge = static_cast<double>(pixel_charge.getCharge());

        LOG(DEBUG) << "Received pixel (" << pixel.x() << "," << pixel.y() << "), charge " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq->Fill(charge / 1e3);
        }

        // Add electronics noise from Gaussian:
        std::normal_distribution<double> el_noise(0, config_.get<unsigned int>("electronics_noise"));
        charge += el_noise(random_generator_);

        LOG(DEBUG) << "Charge with noise: " << Units::display(charge, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_noise->Fill(charge / 1e3);
        }

        // FIXME Simulate gain / gain smearing

        // Smear the threshold, Gaussian distribution around "threshold" with width "threshold_smearing"
        std::normal_distribution<double> thr_smearing(config_.get<unsigned int>("threshold"),
                                                      config_.get<unsigned int>("threshold_smearing"));
        double threshold = thr_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_thr->Fill(threshold / 1e3);
        }

        // Discard charges below threshold:
        if(charge < threshold) {
            LOG(DEBUG) << "Below smeared threshold: " << Units::display(charge, "e") << " < "
                       << Units::display(threshold, "e");
            continue;
        }

        LOG(DEBUG) << "Passed threshold: " << Units::display(charge, "e") << " > " << Units::display(threshold, "e");
        if(config_.get<bool>("output_plots")) {
            h_pxq_thr->Fill(charge / 1e3);
        }

        // Add ADC smearing:
        std::normal_distribution<double> adc_smearing(0, config_.get<unsigned int>("adc_smearing"));
        charge += adc_smearing(random_generator_);
        if(config_.get<bool>("output_plots")) {
            h_pxq_adc->Fill(charge / 1e3);
        }

        // Add the hit to the hitmap
        hits.emplace_back(pixel, 0, charge);

        // FIXME Simulate analog / digital cross talk
        // double crosstalk_neigubor_row = 0.00;
        // double crosstalk_neigubor_column = 0.00;
    }

    // output summary and update statistics
    LOG(INFO) << "Digitized " << hits.size() << " pixel hits";
    total_hits_ += hits.size();

    if(!hits.empty()) {
        // Create and dispatch hit message
        auto hits_message = std::make_shared<PixelHitMessage>(std::move(hits), getDetector());
        messenger_->dispatchMessage(this, hits_message);
    }
}

// Create file and write the histograms to it if we have plots enabled
void DefaultDigitizerModule::finalize() {
    if(config_.get<bool>("output_plots")) {
        // Write histograms
        LOG(TRACE) << "Writing output plots to file";
        h_pxq->Write();
        h_pxq_noise->Write();
        h_thr->Write();
        h_pxq_thr->Write();
        h_pxq_adc->Write();
    }

    LOG(INFO) << "Digitized " << total_hits_ << " pixel hits in total";
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
//   File: list.cpp
//
//   Class: list
//   Functions: main
//-----------------------------------------------------------------------------

#include "list.h"

using namespace std;

namespace NP_ADT
{
	// Constructors

	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	inline CDLL<datatype>::CDLL(void) : handle(nullptr), m_size(0) {}

	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
		:m_size(0), handle(nullptr)
	{
		if (n_elements <= 0)
			throw out_of_range("Empty list");
		for (size_t i = 0; i < n_elements; i++)
			push_front(datum);
	}

	//-------------------------------------------------------------------------
	// copy constructor
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & rlist)
		: m_size(0), handle(nullptr)
	{
		if (&rlist != this && !rlist.empty())
		{
			auto r_it = rlist.begin();
			release();
			while (r_it != rlist.end())
				push_back(*r_it++);
			push_back(*r_it);
		}
	}

	//-------------------------------------------------------------------------
	// insert element at front of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_front(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
		handle = temp;
	}

	//-------------------------------------------------------------------------
	// insert element at end of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_back(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
			handle = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
	}

	//-------------------------------------------------------------------------
	// removes front element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_front()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = head()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * oldHead = head();
			node * newHead = head()->next;
			newHead->prev = head()->prev;
			head()->prev->next = newHead;
			handle = newHead;
			delete oldHead;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// removes back element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_back()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = tail()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * oldTail = tail();
			node * newTail = tail()->prev;
			newTail->next = tail()->next;
			tail()->next->prev = newTail;
			delete oldTail;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// returns data of the first item
	//-------------------------------------------------------------------------
	template<class datatype>
	datatype & CDLL<datatype>::front() const
	{
		if (head() != nullptr)
			return head()->data;
		else
			throw runtime_error("Empty list");
	}

	//-------------------------------------------------------------------------
	// returns data of the last item
	//-------------------------------------------------------------------------
	template<class datatype>
	inline datatype & CDLL<datatype>::back() const
	{
		if (tail() != nullptr)
			return tail()->data;
		else
			throw runtime_error("Empty list");
	}

	//-----------------------------------------------------------------------------
	// empties the list
	//-----------------------------------------------------------------------------
	template<typename datatype>
	inline void NP_ADT::CDLL<datatype>::release()
	{
		while (handle != nullptr)
			pop_front();
	}

	//-------------------------------------------------------------------------
	// constructor using iterators, copies from begin to one before end
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
		:m_size(0), handle(nullptr)
	{
		while (begin != end)
			push_back(*begin++);
		push_back(*begin++);
	}

	//-------------------------------------------------------------------------
	// prints out a list
	//-------------------------------------------------------------------------
	template<typename datatype>
	const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
	{
		if (index >= m_size) {
			throw domain_error("Index larger than list size");
		}
		iterator cursor = begin();
		for (int x = 0; x < index; x++) { cursor++; }
		return *cursor;
	}

	//-------------------------------------------------------------------------
	// returns a copy of rlist
	//-------------------------------------------------------------------------
	template<typename datatype>
	CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
	{
		if (&rlist != this && !rlist.empty())
		{
			auto r_it = rlist.begin();
			release();
			while (r_it != rlist.end())
				push_back(*r_it++);
			push_back(*r_it);
		}
		return *this;
	}

	//-------------------------------------------------------------------------
	// pre-increment
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->next;
		return *this;
	}

	//-------------------------------------------------------------------------
	// post-increment
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->next;
		return temp;
	}

	//-------------------------------------------------------------------------
	// pre-decrement
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->prev;
		return *this;
	}

	//-------------------------------------------------------------------------
	// post-decrement
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->prev;
		return temp;
	}

	//-------------------------------------------------------------------------
	// [] operator -- l-value
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	datatype & NP_ADT::CDLL<datatype>::operator[](int index)
	{
		iterator it;
		if (index >= 0)
		{
			if (index >= static_cast<int>(getSize()))
				throw out_of_range("index out-of-range");
			it = begin();
			for (int i = 0; i < index; i++)
				it++;
		}
		else
		{
			if (index < -(static_cast<int>(getSize())))
				throw out_of_range("index out-of-range");
			it = end();
			for (int i = -1; i > index; i--)
				it--;
		}
		return *it;
	}*/

	//-------------------------------------------------------------------------
	// ostream << overload
	//-------------------------------------------------------------------------
	template <typename datatype>
	ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
	{
		auto it = cdll.begin();
		sout << "[";
		if (!cdll.empty()) {
			while (it != cdll.end())
				sout << *it++ << ", ";
			sout << *it;
		}
		sout << "]";
		return sout;
	}

} // end namespace NP_ADT

<commit_msg>require positive index<commit_after>//-----------------------------------------------------------------------------
//   File: list.cpp
//
//   Class: list
//   Functions: main
//-----------------------------------------------------------------------------

#include "list.h"

using namespace std;

namespace NP_ADT
{
	// Constructors

	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	inline CDLL<datatype>::CDLL(void) : handle(nullptr), m_size(0) {}

	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
		:m_size(0), handle(nullptr)
	{
		if (n_elements <= 0)
			throw out_of_range("Empty list");
		for (size_t i = 0; i < n_elements; i++)
			push_front(datum);
	}

	//-------------------------------------------------------------------------
	// copy constructor
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & rlist)
		: m_size(0), handle(nullptr)
	{
		if (&rlist != this && !rlist.empty())
		{
			auto r_it = rlist.begin();
			release();
			while (r_it != rlist.end())
				push_back(*r_it++);
			push_back(*r_it);
		}
	}

	//-------------------------------------------------------------------------
	// insert element at front of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_front(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
		handle = temp;
	}

	//-------------------------------------------------------------------------
	// insert element at end of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_back(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
			handle = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
	}

	//-------------------------------------------------------------------------
	// removes front element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_front()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = head()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * oldHead = head();
			node * newHead = head()->next;
			newHead->prev = head()->prev;
			head()->prev->next = newHead;
			handle = newHead;
			delete oldHead;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// removes back element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_back()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = tail()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * oldTail = tail();
			node * newTail = tail()->prev;
			newTail->next = tail()->next;
			tail()->next->prev = newTail;
			delete oldTail;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// returns data of the first item
	//-------------------------------------------------------------------------
	template<class datatype>
	datatype & CDLL<datatype>::front() const
	{
		if (head() != nullptr)
			return head()->data;
		else
			throw runtime_error("Empty list");
	}

	//-------------------------------------------------------------------------
	// returns data of the last item
	//-------------------------------------------------------------------------
	template<class datatype>
	inline datatype & CDLL<datatype>::back() const
	{
		if (tail() != nullptr)
			return tail()->data;
		else
			throw runtime_error("Empty list");
	}

	//-----------------------------------------------------------------------------
	// empties the list
	//-----------------------------------------------------------------------------
	template<typename datatype>
	inline void NP_ADT::CDLL<datatype>::release()
	{
		while (handle != nullptr)
			pop_front();
	}

	//-------------------------------------------------------------------------
	// constructor using iterators, copies from begin to one before end
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
		:m_size(0), handle(nullptr)
	{
		while (begin != end)
			push_back(*begin++);
		push_back(*begin++);
	}

	//-------------------------------------------------------------------------
	// get the nth item of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
	{
		if (index >= int(m_size) || index < 0)
			throw out_of_range("out of range");

		iterator cursor = begin();
		for (int x = 0; x < index; x++) { cursor++; }
		return *cursor;
	}

	//-------------------------------------------------------------------------
	// returns a copy of rlist
	//-------------------------------------------------------------------------
	template<typename datatype>
	CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
	{
		if (&rlist != this && !rlist.empty())
		{
			auto r_it = rlist.begin();
			release();
			while (r_it != rlist.end())
				push_back(*r_it++);
			push_back(*r_it);
		}
		return *this;
	}

	//-------------------------------------------------------------------------
	// pre-increment
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->next;
		return *this;
	}

	//-------------------------------------------------------------------------
	// post-increment
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->next;
		return temp;
	}

	//-------------------------------------------------------------------------
	// pre-decrement
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->prev;
		return *this;
	}

	//-------------------------------------------------------------------------
	// post-decrement
	//-------------------------------------------------------------------------
	template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->prev;
		return temp;
	}

	//-------------------------------------------------------------------------
	// [] operator -- l-value
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	datatype & NP_ADT::CDLL<datatype>::operator[](int index)
	{
		iterator it;
		if (index >= 0)
		{
			if (index >= static_cast<int>(getSize()))
				throw out_of_range("index out-of-range");
			it = begin();
			for (int i = 0; i < index; i++)
				it++;
		}
		else
		{
			if (index < -(static_cast<int>(getSize())))
				throw out_of_range("index out-of-range");
			it = end();
			for (int i = -1; i > index; i--)
				it--;
		}
		return *it;
	}*/

	//-------------------------------------------------------------------------
	// ostream << overload
	//-------------------------------------------------------------------------
	template <typename datatype>
	ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
	{
		auto it = cdll.begin();
		sout << "[";
		if (!cdll.empty()) {
			while (it != cdll.end())
				sout << *it++ << ", ";
			sout << *it;
		}
		sout << "]";
		return sout;
	}

} // end namespace NP_ADT

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>
#include <vector>
#include <thread>
#include <unistd.h>

#include <boost/asio.hpp>

#include "logger.hpp"
#include "cmd.hpp"
#include "util.hpp"
#include "ftp_server.hpp"

using namespace ftp;
using namespace boost::asio;

int StatusCode(const string& response) {
    return std::stoi(Split(response, ' ').front());
}

void StartServer() {
    static bool started = false;
    if (started == false) {
        started = true;
        std::thread server([=]() {
                FTPServer s(8080, 8081);
                s.Run();
                });
        server.detach();
        sleep(1);
    }
}

bool TestLogger() {
    const char* log_path = "./test.log";
    Logger logger(log_path);
    logger.Log("wow, amazing", Logger::INFO);
    logger.Log("oh, no");
    logger.Log("oh, shit", Logger::ERROR);
    puts("pass-test: logger");
    return true;
}

bool TestCMD() {
    assert(ResolveCMD("USER") == CMD::USER);
    assert(ResolveCMD("PASS") == CMD::PASS);
    assert(ResolveCMD("shit") == CMD::BAD);
    assert(ResolveCMD("user") == CMD::USER);
    assert(ResolveCMD("pass") == CMD::PASS);
    puts("pass-test: cmd");
    return true;
}

bool TestResponse() {
    assert(Response(200) == "Command okay.");
    assert(Response(214) == "Help message.");
    assert(Response(530) == "Not logged in.");
    puts("pass-test: response");
    return true;
}

bool TestSplit() {
    std::string str = "USER anonymous";
    std::vector<std::string> res = { "USER", "anonymous" };
    auto splited = Split(str, ' ');
    assert(res == splited);

    str = "shit";
    res = { "shit" };
    splited = Split(str, ' ');
    assert(res == splited);
    puts("pass-test: split");
    return true;
}

/* Long request */
template<typename Fn>
void Request(Fn callback) {
    StartServer();

    io_service ios;
    ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 8080);
    ip::tcp::socket socket(ios);
    socket.connect(ep);

    assert(StatusCode(ReadLine(socket)) == 220);
    callback(socket);
    socket.write_some(buffer("QUIT\r\n"));
}

/**
 * Short request.
 * Send a req sequence, and receive the response.
 */
template<typename Fn>
void Request(const string& req, Fn callback) {
    Request([&](auto& socket) {
        WriteLine(socket, req);
    });
}

template<typename Fn>
void Receive(ip::tcp::endpoint& ep, Fn fn) {
    StartServer();

    std::thread anon([&]() {
        try {
            io_service ios;
            ip::tcp::acceptor acceptor(ios, ep);
            ip::tcp::socket socket(ios);

            acceptor.accept(socket);
            fn(socket);
            acceptor.close();
        } catch (std::exception& e) {
            printf("file: %s line %d: %s\n", __FILE__,  __LINE__, e.what());
        }
    });
    anon.detach();
}

bool TestSignin() {
    Request("USER ming\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 331);
    });

    puts("pass-test: sign in");

    return true;
}

bool TestPWD() {
    Request("PWD\r\n", [](auto& socket) {
        ReadLine(socket);
        assert(StatusCode(ReadLine(socket)) == 257);
    });

    puts("pass-test: pwd");
    return true;
}

bool TestCWD() {
    Request("CWD /shit\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 250);
    });

    puts("pass-test: cwd");
    return true;
}

bool TestPORT() {
    /* port 1025 */
    /* Nobody listening at 1025, so this request will fail. */
    Request("PORT 127,0,0,1,4,1\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 425);
    });

    /* set a listener at 1025, then send request. */
    ip::tcp::endpoint ep(ip::tcp::v4(), 1025);
    Receive(ep, [](auto& socket) {
        assert(socket.remote_endpoint().address().to_string() == "127.0.0.1");
    });

    Request("PORT 127,0,0,1,4,1\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 200);
    });
    puts("pass-test: port");
    return true;
}

bool TestFileInfo() {
    std::cout << make_file_info("/") << std::endl;
    puts("pass-test: file info");
    return true;
}

bool TestLIST() {
    ip::tcp::endpoint ep(ip::tcp::v4(), 1026);
    Receive(ep, [](auto& socket) {
        boost::system::error_code ec;
        while (!ec) {
            std::string res = ReadLine(socket, ec);
            std::cout << res << std::endl;
        }
    });

    Request([](auto& socket){
        WriteLine(socket, "PORT 127,0,0,1,4,2");
        assert(StatusCode(ReadLine(socket)) == 200);

        WriteLine(socket, "LIST /");

        assert(StatusCode(ReadLine(socket)) == 150);
        assert(StatusCode(ReadLine(socket)) == 226);
    });

    puts("pass-test: list");
    return true;
}

bool TestRETR() {
    ip::tcp::endpoint ep(ip::tcp::v4(), 1027);
    Receive(ep, [](auto& socket) {
        FILE* file = fopen("test.cc", "r");
        char buff[128];
        char file_buff[128];
        size_t len;
        boost::system::error_code ec;

        while (!ec) {
            len = socket.read_some(buffer(buff, 128), ec);
            fread(file_buff, 1, len, file);
            assert(memcmp(buff, file_buff, len) == 0);
        }
        fclose(file);
    });

    Request([](auto& socket) {
        WriteLine(socket, "PORT 127,0,0,1,4,3");
        assert(StatusCode(ReadLine(socket)) == 200);

        WriteLine(socket, "RETR /test.cc");
        assert(StatusCode(ReadLine(socket)) == 150);
        assert(StatusCode(ReadLine(socket)) == 226);
    });
    puts("pass-tes: retr");
    return true;
}

int main()
{
    assert(TestLogger());
    assert(TestCMD());
    assert(TestResponse());
    assert(TestSplit());
    assert(TestSignin());
    assert(TestPWD());
    assert(TestCWD());
    assert(TestPORT());
    assert(TestFileInfo());
    assert(TestLIST());
    assert(TestRETR());
    puts("pass all test!");
    return 0;
}
<commit_msg>some optimization<commit_after>#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>
#include <vector>
#include <thread>
#include <unistd.h>

#include <boost/asio.hpp>

#include "logger.hpp"
#include "cmd.hpp"
#include "util.hpp"
#include "ftp_server.hpp"

using namespace ftp;
using namespace boost::asio;

int StatusCode(const string& response) {
    return std::stoi(Split(response, ' ').front());
}

void StartServer() {
    static bool started = false;
    if (started == false) {
        started = true;
        std::thread anon([]{
            FTPServer s(8080, 8081);
            s.Run();
        });
        anon.detach();
        sleep(1);
    }
}

bool TestLogger() {
    const char* log_path = "./test.log";
    Logger logger(log_path);
    logger.Log("wow, amazing", Logger::INFO);
    logger.Log("oh, no");
    logger.Log("oh, shit", Logger::ERROR);
    remove(log_path);
    puts("pass-test: logger");
    return true;
}

bool TestCMD() {
    assert(ResolveCMD("USER") == CMD::USER);
    assert(ResolveCMD("PASS") == CMD::PASS);
    assert(ResolveCMD("shit") == CMD::BAD);
    assert(ResolveCMD("user") == CMD::USER);
    assert(ResolveCMD("pass") == CMD::PASS);
    puts("pass-test: cmd");
    return true;
}

bool TestResponse() {
    assert(Response(200) == "Command okay.");
    assert(Response(214) == "Help message.");
    assert(Response(530) == "Not logged in.");
    puts("pass-test: response");
    return true;
}

bool TestSplit() {
    std::string str = "USER anonymous";
    std::vector<std::string> res = { "USER", "anonymous" };
    auto splited = Split(str, ' ');
    assert(res == splited);

    str = "shit";
    res = { "shit" };
    splited = Split(str, ' ');
    assert(res == splited);
    puts("pass-test: split");
    return true;
}

/**
 * Callback with a socket.
 */
template<typename Fn>
void Request(Fn callback) {
    StartServer();

    io_service ios;
    ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 8080);
    ip::tcp::socket socket(ios);
    socket.connect(ep);

    assert(StatusCode(ReadLine(socket)) == 220);
    callback(socket);
    socket.write_some(buffer("QUIT\r\n"));
}

/**
 * Launch a request with a string.
 */
template<typename Fn>
void Request(const string& req, Fn callback) {
    Request([&](auto& socket) {
        WriteLine(socket, req);
    });
}

/**
 * Create a listener at specific port, and forward the socket to callback.
 */
template<typename Fn>
void Receive(ip::tcp::endpoint& ep, Fn fn) {
    StartServer();

    std::thread anon([&]() {
        try {
            io_service ios;
            ip::tcp::acceptor acceptor(ios, ep);
            ip::tcp::socket socket(ios);

            acceptor.accept(socket);
            fn(socket);
            acceptor.close();
        } catch (std::exception& e) {
            printf("file: %s line %d: %s\n", __FILE__,  __LINE__, e.what());
        }
    });
    anon.detach();
}

bool TestSignin() {
    Request("USER ming\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 331);
    });

    puts("pass-test: sign in");

    return true;
}

bool TestPWD() {
    Request("PWD\r\n", [](auto& socket) {
        ReadLine(socket);
        assert(StatusCode(ReadLine(socket)) == 257);
    });

    puts("pass-test: pwd");
    return true;
}

bool TestCWD() {
    Request("CWD /shit\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 250);
    });

    puts("pass-test: cwd");
    return true;
}

bool TestPORT() {
    /* port 1025 */
    /* Nobody listening at 1025, so this request will fail with a 425 response.*/
    Request("PORT 127,0,0,1,4,1\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 425);
    });

    /* set a listener at 1025, then send request. */
    ip::tcp::endpoint ep(ip::tcp::v4(), 1025);
    Receive(ep, [](auto& socket) {
        assert(socket.remote_endpoint().address().to_string() == "127.0.0.1");
    });

    Request("PORT 127,0,0,1,4,1\r\n", [](auto& socket) {
        assert(StatusCode(ReadLine(socket)) == 200);
    });
    puts("pass-test: port");
    return true;
}

bool TestFileInfo() {
    std::cout << make_file_info("/") << std::endl;
    puts("pass-test: file info");
    return true;
}

bool TestLIST() {
    ip::tcp::endpoint ep(ip::tcp::v4(), 1026);
    Receive(ep, [](auto& socket) {
        boost::system::error_code ec;
        while (!ec) {
            std::string res = ReadLine(socket, ec);
            std::cout << res << std::endl;
        }
    });

    Request([](auto& socket){
        WriteLine(socket, "PORT 127,0,0,1,4,2");
        assert(StatusCode(ReadLine(socket)) == 200);

        WriteLine(socket, "LIST /");

        assert(StatusCode(ReadLine(socket)) == 150);
        assert(StatusCode(ReadLine(socket)) == 226);
    });

    puts("pass-test: list");
    return true;
}

bool TestRETR() {
    ip::tcp::endpoint ep(ip::tcp::v4(), 1027);
    Receive(ep, [](auto& socket) {
        FILE* file = fopen("test.cc", "r");
        char buff[128];
        char file_buff[128];
        size_t len;
        boost::system::error_code ec;

        while (!ec) {
            len = socket.read_some(buffer(buff, 128), ec);
            fread(file_buff, 1, len, file);
            assert(memcmp(buff, file_buff, len) == 0);
        }
        fclose(file);
    });

    Request([](auto& socket) {
        WriteLine(socket, "PORT 127,0,0,1,4,3");
        assert(StatusCode(ReadLine(socket)) == 200);

        WriteLine(socket, "RETR /test.cc");
        assert(StatusCode(ReadLine(socket)) == 150);
        assert(StatusCode(ReadLine(socket)) == 226);
    });
    puts("pass-tes: retr");
    return true;
}

int main()
{
    assert(TestLogger());
    assert(TestCMD());
    assert(TestResponse());
    assert(TestSplit());
    assert(TestSignin());
    assert(TestPWD());
    assert(TestCWD());
    assert(TestPORT());
    assert(TestFileInfo());
    assert(TestLIST());
    assert(TestRETR());
    puts("pass all test!");
    return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "NeonDepthwiseConv.h"
#include "paddle/function/ConvOp.h"

namespace paddle {

#if defined(__ARM_NEON__) || defined(__ARM_NEON)

template <DeviceType Device>
class NeonDepthwiseConvFunction : public ConvFunctionBase {
 public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();
    checkShape(input, filter, output);
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    check(inputs, outputs);

    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();

    int batchSize = input[0];
    int inputChannels = input[1];
    int inputHeight = input[2];
    int inputWidth = input[3];
    int filterHeight = getFilterHeight(filter);
    int filterWidth = getFilterWidth(filter);
    int outputChannels = output[1];
    int outputHeight = output[2];
    int outputWidth = output[3];
    int filterMultiplier = outputChannels / groups_;
    CHECK_EQ(static_cast<size_t>(inputChannels), groups_);

    // only support strideH() == strideW() and filterHeight == filterWidth.
    CHECK_EQ(strideH(), strideW());
    CHECK_EQ(filterHeight, filterWidth);

    float* inputData = inputs[0].data<float>();
    float* filterData = inputs[1].data<float>();
    float* outputData = outputs[0].data<float>();

    // padding the input
    float* inputPadding = inputData;
    int padInputHeight = inputHeight + 2 * paddingH();
    int padInputWidth = inputWidth + 2 * paddingW();
    int newSize = batchSize * (inputChannels + 1) * padInputHeight * padInputWidth;
    resizeBuffer<Device>(newSize);
    inputPadding = reinterpret_cast<float*>(memory_->getBuf());
    neon::Padding<float>::run(inputData,
                                inputPadding,
                                batchSize * inputChannels,
                                inputHeight,
                                inputWidth,
                                padInputHeight,
                                padInputWidth);

    std::function<void(
        const float*, const float*, int, int, int, int, int, int, float*)>
        DepthWiseConv;

    if (filterWidth == 3 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 1>::run;
    } else if (filterWidth == 3 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 2>::run;
    } else if (filterWidth == 4 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 1>::run;
    } else if (filterWidth == 4 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 2>::run;
    } else {
      LOG(FATAL) << "Not supported";
    }

    for (int i = 0; i < batchSize; i++) {
      DepthWiseConv(inputPadding,
                    filterData,
                    padInputHeight,
                    padInputWidth,
                    outputChannels,
                    outputHeight,
                    outputWidth,
                    filterMultiplier,
                    outputData);
      inputPadding += inputChannels * padInputHeight * padInputWidth;
      outputData += outputChannels * outputHeight * outputWidth;
    }
  }
};

#ifndef PADDLE_TYPE_DOUBLE
REGISTER_TYPED_FUNC(NeonDepthwiseConv, CPU, NeonDepthwiseConvFunction);
#endif

#endif

}  // namespace paddle
<commit_msg>fix code format<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "NeonDepthwiseConv.h"
#include "paddle/function/ConvOp.h"

namespace paddle {

#if defined(__ARM_NEON__) || defined(__ARM_NEON)

template <DeviceType Device>
class NeonDepthwiseConvFunction : public ConvFunctionBase {
 public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();
    checkShape(input, filter, output);
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    check(inputs, outputs);

    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();

    int batchSize = input[0];
    int inputChannels = input[1];
    int inputHeight = input[2];
    int inputWidth = input[3];
    int filterHeight = getFilterHeight(filter);
    int filterWidth = getFilterWidth(filter);
    int outputChannels = output[1];
    int outputHeight = output[2];
    int outputWidth = output[3];
    int filterMultiplier = outputChannels / groups_;
    CHECK_EQ(static_cast<size_t>(inputChannels), groups_);

    // only support strideH() == strideW() and filterHeight == filterWidth.
    CHECK_EQ(strideH(), strideW());
    CHECK_EQ(filterHeight, filterWidth);

    float* inputData = inputs[0].data<float>();
    float* filterData = inputs[1].data<float>();
    float* outputData = outputs[0].data<float>();

    // padding the input
    float* inputPadding = inputData;
    int padInputHeight = inputHeight + 2 * paddingH();
    int padInputWidth = inputWidth + 2 * paddingW();
    int newSize =
        batchSize * (inputChannels + 1) * padInputHeight * padInputWidth;

    resizeBuffer<Device>(newSize);
    inputPadding = reinterpret_cast<float*>(memory_->getBuf());
    neon::Padding<float>::run(inputData,
                              inputPadding,
                              batchSize * inputChannels,
                              inputHeight,
                              inputWidth,
                              padInputHeight,
                              padInputWidth);

    std::function<void(
        const float*, const float*, int, int, int, int, int, int, float*)>
        DepthWiseConv;

    if (filterWidth == 3 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 1>::run;
    } else if (filterWidth == 3 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 2>::run;
    } else if (filterWidth == 4 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 1>::run;
    } else if (filterWidth == 4 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 2>::run;
    } else {
      LOG(FATAL) << "Not supported";
    }

    for (int i = 0; i < batchSize; i++) {
      DepthWiseConv(inputPadding,
                    filterData,
                    padInputHeight,
                    padInputWidth,
                    outputChannels,
                    outputHeight,
                    outputWidth,
                    filterMultiplier,
                    outputData);
      inputPadding += inputChannels * padInputHeight * padInputWidth;
      outputData += outputChannels * outputHeight * outputWidth;
    }
  }
};

#ifndef PADDLE_TYPE_DOUBLE
REGISTER_TYPED_FUNC(NeonDepthwiseConv, CPU, NeonDepthwiseConvFunction);
#endif

#endif

}  // namespace paddle
<|endoftext|>


<commit_before>/*
 * mp3stream - encode /dev/dsp and send it to a shoutcast server
 * 2005 - bl0rg.net - public domain
 *
 * mp3stream.cc - main file, contains command-line option decoding and
 * mainloop.
 */

#include <assert.h>
#include <unistd.h>

#include <iostream>
#include <list>
#include <string>
#include <map>
using namespace std;

#include "Error.h"
#include "AudioCard.h"
#include "Streamer.h"
#include "Url.h"
#include "LameEncoder.h"

static const string usageString =
"Usage:\n\n"
"mp3stream [-h] [-b bitrate] [-n name] [-g genre] [-p publicstr]\n"
"          [-d description] [-c contentid] [-u url] [-t streamurl]\n\n"
"-b bitrate: set the bitrate of the stream in kbps (default 128 kbps)\n\n"
"To send streams to multiple url, specify one or more streamurls.\n"
"The stream description will consist of the last parameters given.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost:8001/stream128 \n"
"          -b 64 -n \"64 kbps\" -t xaudio://localhost:8001/stream64\n\n"
"will send a 128 kbps encoded stream to the icecast server under the\n"
"mountpoint /stream128 and a 64 kbps encoded stream to the icecast server\n"
"under the mountpoint /stream64.\n\n"
"mp3stream can also log the encoded data to a file by using a file:/// URL.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost/bla -t file:///var/mp3-log.mp3\n\n"
"will send the 128 kbps encoded data to localhost and log it into mp3-log.mp3.\n";

static void usage(const char *program) {
  cerr << usageString;
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    usage(argv[0]);
    return 1;
  }

  unsigned long bitrate = 128;
  string name = "";
  string genre = "";
  string publicStr = "";
  string description = "";
  string url = "";
  string contentid = "";
  list<Streamer *> streamerList;
  int retval = 0;

  int c;
  while ((c = getopt(argc, argv, "hb:n:g:p:d:c:u:t:")) >= 0) {
    switch (c) {
    case 'h':
      usage(argv[0]);
      return 0;

    case 'b':
      bitrate = atoi(optarg);
      break;

    case 'n':
      name = string(optarg);
      break;

    case 'g':
      genre = string(optarg);
      break;

    case 'p':
      publicStr = string(optarg);
      break;

    case 'd':
      description = string(optarg);
      break;

    case 'c':
      contentid = string(optarg);
      break;

    case 'u':
      url = string(optarg);
      break;

    case 't':
      try {
	Stream stream(bitrate, name, genre, url,
		      publicStr, description, contentid);
	Url streamUrl(optarg);
	Streamer *streamer = new Streamer(stream, streamUrl);
	streamerList.push_front(streamer);
      } catch (Error &e) {
	cerr << "Could not parse URL \"" << optarg << "\": "
	     << e.getMessage() << endl;
	retval = 1;
	goto exit;
      }
      break;

    default:
      cerr << "Unknown switch " << c << endl;
      usage(argv[0]);
      return 1;
    }
  }

  try {
    AudioCard *audioCard = NULL;
    map<LameEncoder *,list<Streamer *> > encoderMap;

    try {
      audioCard = new AudioCard(false);
    } catch (AudioError &e) {
      cerr << "Could not initialize soundcard: " << e.getMessage() << endl;
      retval = 1;
      goto exit;
    }

    for (list<Streamer *>::iterator pStreamer = streamerList.begin();
	 pStreamer != streamerList.end(); pStreamer++) {
      Streamer &streamer = *(*pStreamer);
      unsigned long bitrate = streamer.getBitrate();

      map<LameEncoder *,list<Streamer *> >::iterator p;
      for (p = encoderMap.begin();
	   p != encoderMap.end(); p++) {
	const LameEncoder &encoder = *(p->first);
	list<Streamer *> &listStreamer = p->second;
	if (encoder.getBitrate() == bitrate) {
	  listStreamer.push_back((*pStreamer));
	  break;
	}
      }
      if (p == encoderMap.end()) {
	try {
	  LameEncoder *encoder = new LameEncoder(*audioCard, bitrate);
	  list<Streamer *> &listStreamer = encoderMap[encoder];
	  listStreamer.push_back((*pStreamer));
	} catch (LameError &e) {
	  cerr << "Could not create an encoder with " << bitrate << " kbps: "
	       << endl
	       << "        " << e.getMessage() << endl;
	  retval = 1;
	  goto cleanup;
	}
      }
    }

    /* Print information about setup */
    cerr << endl
	 << "Streaming setup:" << endl
	 << "----------------" << endl;

    for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	 p != encoderMap.end(); p++) {
      LameEncoder *encoder = p->first;
      list<Streamer *> &l = p->second;

      cerr << "Streaming " << encoder->getBitrate()
	   << " kbps stream to: " << endl;

      for (list<Streamer *>::iterator pStreamer = l.begin();
	   pStreamer != l.end(); pStreamer++) {
	cerr << "  " << (*pStreamer)->getUrl()
	     << " " << (*pStreamer)->getInfo() << endl;
      }

      cerr << endl;
    }

    for (list<Streamer *>::iterator pStreamer = streamerList.begin();
	 pStreamer != streamerList.end(); pStreamer++) {
      Streamer &streamer = *(*pStreamer);
      cerr << "Logging in to " << streamer.getUrl() << "... ";
      try {
	streamer.Login();
      } catch (Error &e) {
	cerr << endl;
	cerr << "       " << e.getMessage() << endl;
	retval = 1;
	goto cleanup;
      }
      cerr << "OK" << endl;
    }

    cerr << "Streaming..." << endl;

    /* main loop */
    static short buf[rawDataBlockSize / 2];
    static unsigned char mp3Buf[rawDataBlockSize];
    for (;;) {
      audioCard->Read(buf);
      for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	   p != encoderMap.end(); p++) {
	LameEncoder *encoder = p->first;
	list<Streamer *> &l = p->second;

	int ret = encoder->EncodeBuffer(buf, sizeof(buf),
				       mp3Buf, sizeof(mp3Buf));

	if (ret > 0) {
	  for (list<Streamer *>::iterator pStreamer = l.begin();
	       pStreamer != l.end(); pStreamer++) {
	    Streamer &streamer = *(*pStreamer);
	    streamer.Write(mp3Buf, ret);
	  }
	}
      }
    }

  cleanup:
    for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	 p != encoderMap.end(); p++) {
      LameEncoder *encoder = p->first;
      delete encoder;
    }
    delete audioCard;

  } catch (Error &e) {
    cerr << e.getMessage() << endl;
    retval = 1;
    goto exit;
  }

 exit:
  for (list<Streamer *>::iterator pStreamer = streamerList.begin();
       pStreamer != streamerList.end(); pStreamer++) {
    delete (*pStreamer);
  }

  return retval;
}
<commit_msg>visual display<commit_after>/*
 * mp3stream - encode /dev/dsp and send it to a shoutcast server
 * 2005 - bl0rg.net - public domain
 *
 * mp3stream.cc - main file, contains command-line option decoding and
 * mainloop.
 */

#include <assert.h>
#include <unistd.h>

#include <iostream>
#include <list>
#include <string>
#include <map>
using namespace std;

#include "Error.h"
#include "AudioCard.h"
#include "Streamer.h"
#include "Url.h"
#include "LameEncoder.h"

static const string usageString =
"Usage:\n\n"
"mp3stream [-h] [-b bitrate] [-n name] [-g genre] [-p publicstr]\n"
"          [-d description] [-c contentid] [-u url] [-t streamurl]\n\n"
"-b bitrate: set the bitrate of the stream in kbps (default 128 kbps)\n\n"
"To send streams to multiple url, specify one or more streamurls.\n"
"The stream description will consist of the last parameters given.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost:8001/stream128 \n"
"          -b 64 -n \"64 kbps\" -t xaudio://localhost:8001/stream64\n\n"
"will send a 128 kbps encoded stream to the icecast server under the\n"
"mountpoint /stream128 and a 64 kbps encoded stream to the icecast server\n"
"under the mountpoint /stream64.\n\n"
"mp3stream can also log the encoded data to a file by using a file:/// URL.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost/bla -t file:///var/mp3-log.mp3\n\n"
"will send the 128 kbps encoded data to localhost and log it into mp3-log.mp3.\n";

static void usage(const char *program) {
  cerr << usageString;
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    usage(argv[0]);
    return 1;
  }

  unsigned long bitrate = 128;
  string name = "";
  string genre = "";
  string publicStr = "";
  string description = "";
  string url = "";
  string contentid = "";
  list<Streamer *> streamerList;
  int retval = 0;
  bool bDisplay = false;

  int c;
  while ((c = getopt(argc, argv, "hb:n:g:p:d:c:u:t:v")) >= 0) {
    switch (c) {
    case 'h':
      usage(argv[0]);
      return 0;

    case 'v':
      bDisplay = true;
      break;

    case 'b':
      bitrate = atoi(optarg);
      break;

    case 'n':
      name = string(optarg);
      break;

    case 'g':
      genre = string(optarg);
      break;

    case 'p':
      publicStr = string(optarg);
      break;

    case 'd':
      description = string(optarg);
      break;

    case 'c':
      contentid = string(optarg);
      break;

    case 'u':
      url = string(optarg);
      break;

    case 't':
      try {
	Stream stream(bitrate, name, genre, url,
		      publicStr, description, contentid);
	Url streamUrl(optarg);
	Streamer *streamer = new Streamer(stream, streamUrl);
	streamerList.push_front(streamer);
      } catch (Error &e) {
	cerr << "Could not parse URL \"" << optarg << "\": "
	     << e.getMessage() << endl;
	retval = 1;
	goto exit;
      }
      break;

    default:
      cerr << "Unknown switch " << c << endl;
      usage(argv[0]);
      return 1;
    }
  }

  try {
    AudioCard *audioCard = NULL;
    map<LameEncoder *,list<Streamer *> > encoderMap;

    try {
      audioCard = new AudioCard(false);
    } catch (AudioError &e) {
      cerr << "Could not initialize soundcard: " << e.getMessage() << endl;
      retval = 1;
      goto exit;
    }

    for (list<Streamer *>::iterator pStreamer = streamerList.begin();
	 pStreamer != streamerList.end(); pStreamer++) {
      Streamer &streamer = *(*pStreamer);
      unsigned long bitrate = streamer.getBitrate();

      map<LameEncoder *,list<Streamer *> >::iterator p;
      for (p = encoderMap.begin();
	   p != encoderMap.end(); p++) {
	const LameEncoder &encoder = *(p->first);
	list<Streamer *> &listStreamer = p->second;
	if (encoder.getBitrate() == bitrate) {
	  listStreamer.push_back((*pStreamer));
	  break;
	}
      }
      if (p == encoderMap.end()) {
	try {
	  LameEncoder *encoder = new LameEncoder(*audioCard, bitrate);
	  list<Streamer *> &listStreamer = encoderMap[encoder];
	  listStreamer.push_back((*pStreamer));
	} catch (LameError &e) {
	  cerr << "Could not create an encoder with " << bitrate << " kbps: "
	       << endl
	       << "        " << e.getMessage() << endl;
	  retval = 1;
	  goto cleanup;
	}
      }
    }

    /* Print information about setup */
    cerr << endl
	 << "Streaming setup:" << endl
	 << "----------------" << endl;

    for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	 p != encoderMap.end(); p++) {
      LameEncoder *encoder = p->first;
      list<Streamer *> &l = p->second;

      cerr << "Streaming " << encoder->getBitrate()
	   << " kbps stream to: " << endl;

      for (list<Streamer *>::iterator pStreamer = l.begin();
	   pStreamer != l.end(); pStreamer++) {
	cerr << "  " << (*pStreamer)->getUrl()
	     << " " << (*pStreamer)->getInfo() << endl;
      }

      cerr << endl;
    }

    for (list<Streamer *>::iterator pStreamer = streamerList.begin();
	 pStreamer != streamerList.end(); pStreamer++) {
      Streamer &streamer = *(*pStreamer);
      cerr << "Logging in to " << streamer.getUrl() << "... ";
      try {
	streamer.Login();
      } catch (Error &e) {
	cerr << endl;
	cerr << "       " << e.getMessage() << endl;
	retval = 1;
	goto cleanup;
      }
      cerr << "OK" << endl;
    }

    cerr << "Streaming..." << endl;

    /* main loop */
    static short buf[rawDataBlockSize / 2];
    static unsigned char mp3Buf[rawDataBlockSize];
    for (;;) {
      audioCard->Read(buf);

      static int count = 0;
      if (bDisplay && ((count++ % 300) == 0)) {
	unsigned short maxVol = 0;
	for (unsigned int i = 0; i < rawDataBlockSize / 2; i++) {
	  if (abs(buf[i]) > maxVol)
	    maxVol = abs(buf[i]);
	}
	cout << "\r                                                                       ";
	if (maxVol > 32000) {
	  cout << "\r*clip*";
	} else {
	  cout << "\r=";
	  for (unsigned short j = 0; j <= maxVol; j += 500)
	    cout << "=";
	}
	cout.flush();
      }

      for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	   p != encoderMap.end(); p++) {
	LameEncoder *encoder = p->first;
	list<Streamer *> &l = p->second;

	int ret = encoder->EncodeBuffer(buf, sizeof(buf),
				       mp3Buf, sizeof(mp3Buf));

	if (ret > 0) {
	  for (list<Streamer *>::iterator pStreamer = l.begin();
	       pStreamer != l.end(); pStreamer++) {
	    Streamer &streamer = *(*pStreamer);
	    streamer.Write(mp3Buf, ret);
	  }
	}
      }
    }

  cleanup:
    for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
	 p != encoderMap.end(); p++) {
      LameEncoder *encoder = p->first;
      delete encoder;
    }
    delete audioCard;

  } catch (Error &e) {
    cerr << e.getMessage() << endl;
    retval = 1;
    goto exit;
  }

 exit:
  for (list<Streamer *>::iterator pStreamer = streamerList.begin();
       pStreamer != streamerList.end(); pStreamer++) {
    delete (*pStreamer);
  }

  return retval;
}
<|endoftext|>


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

#include <tvm/relay/transform.h>

namespace tvm {
namespace parser {

using tvm::relay::transform::CreateFunctionPass;
using tvm::transform::PassContext;

void SpanChecker::VisitExpr(const Expr& e) {
  this->expression = e;
  VisitSpan(e->span);
  span_stack.push_back(e->span);
  ExprVisitor::VisitExpr(e);
  this->expression = e;
  span_stack.pop_back();
}

// TODO(@jroesch, @junru): we need to deal with unique spans for global/var.
void SpanChecker::VisitExpr_(const VarNode* op) {}
void SpanChecker::VisitExpr_(const GlobalVarNode* op) {}
void SpanChecker::VisitExpr_(const ConstantNode* op) {}

void SpanChecker::VisitExpr_(const TupleNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const FunctionNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const CallNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const LetNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const IfNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const OpNode* op) {}

void SpanChecker::VisitExpr_(const TupleGetItemNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefCreateNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefReadNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefWriteNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const ConstructorNode* op) {}  // ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const MatchNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitSpan(const Span& sp) {
  if (!sp.defined()) {
    Span span;
    int i = 0;
    for (auto spans = this->span_stack.rbegin(); spans != this->span_stack.rend(); spans++) {
      i += 1;
      span = this->span_stack.back();
      if (span.defined()) {
        diag_ctx.Emit(Diagnostic::Warning(span) << "found null-span, i-nodes deep from this span.");
        return;
      }
    }
    auto warning = Diagnostic::Warning(span);
    warning << "\tAll spans are null\n";
    warning << "\t" << this->expression;
    diag_ctx.Emit(warning);
  }
}

void SpanChecker::VisitType(const Type& t) {}
void SpanChecker::VisitClause(const Clause& c) {}
void SpanChecker::VisitPattern(const Pattern& c) {}

Pass SpanCheck() {
  return CreateFunctionPass(
      [](const Function& func, const IRModule& mod, const PassContext& ctx) {
        ICHECK(ctx->diag_ctx) << "Diagnostic context must be set.";
        SpanChecker checker(ctx->diag_ctx.value());
        checker.VisitExpr(func);
        ctx->diag_ctx.value().Render();
        return func;
      },
      0, "SpanCheck", {});
}

TVM_REGISTER_GLOBAL("parser.SpanCheck").set_body_typed([]() { return SpanCheck(); });

}  // namespace parser
}  // namespace tvm
<commit_msg>refact: rm unused variable (#8290)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*!
 * \file span_check.cc
 * \brief A utility for checking and reporting malformed span information.
 */
#include "./span_check.h"

#include <tvm/relay/transform.h>

namespace tvm {
namespace parser {

using tvm::relay::transform::CreateFunctionPass;
using tvm::transform::PassContext;

void SpanChecker::VisitExpr(const Expr& e) {
  this->expression = e;
  VisitSpan(e->span);
  span_stack.push_back(e->span);
  ExprVisitor::VisitExpr(e);
  this->expression = e;
  span_stack.pop_back();
}

// TODO(@jroesch, @junru): we need to deal with unique spans for global/var.
void SpanChecker::VisitExpr_(const VarNode* op) {}
void SpanChecker::VisitExpr_(const GlobalVarNode* op) {}
void SpanChecker::VisitExpr_(const ConstantNode* op) {}

void SpanChecker::VisitExpr_(const TupleNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const FunctionNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const CallNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const LetNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const IfNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const OpNode* op) {}

void SpanChecker::VisitExpr_(const TupleGetItemNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefCreateNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefReadNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const RefWriteNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const ConstructorNode* op) {}  // ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitExpr_(const MatchNode* op) { ExprVisitor::VisitExpr_(op); }

void SpanChecker::VisitSpan(const Span& sp) {
  if (!sp.defined()) {
    Span span;
    for (auto spans = this->span_stack.rbegin(); spans != this->span_stack.rend(); spans++) {
      span = this->span_stack.back();
      if (span.defined()) {
        diag_ctx.Emit(Diagnostic::Warning(span) << "found null-span, i-nodes deep from this span.");
        return;
      }
    }
    auto warning = Diagnostic::Warning(span);
    warning << "\tAll spans are null\n";
    warning << "\t" << this->expression;
    diag_ctx.Emit(warning);
  }
}

void SpanChecker::VisitType(const Type& t) {}
void SpanChecker::VisitClause(const Clause& c) {}
void SpanChecker::VisitPattern(const Pattern& c) {}

Pass SpanCheck() {
  return CreateFunctionPass(
      [](const Function& func, const IRModule& mod, const PassContext& ctx) {
        ICHECK(ctx->diag_ctx) << "Diagnostic context must be set.";
        SpanChecker checker(ctx->diag_ctx.value());
        checker.VisitExpr(func);
        ctx->diag_ctx.value().Render();
        return func;
      },
      0, "SpanCheck", {});
}

TVM_REGISTER_GLOBAL("parser.SpanCheck").set_body_typed([]() { return SpanCheck(); });

}  // namespace parser
}  // namespace tvm
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// 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

// Local includes
#include "libmesh/equation_systems.h"
#include "libmesh/mesh_output.h"
#include "libmesh/parallel.h"
#include "libmesh/parallel_mesh.h"
#include "libmesh/unstructured_mesh.h"

namespace libMesh
{

template <class MT>
void MeshOutput<MT>::
_build_variable_names_and_solution_vector (const EquationSystems& es,
					   std::vector<Number>& soln,
					   std::vector<std::string>& names,
					   const std::set<std::string>* system_names)
{
  if(!_is_parallel_format)
  {
    // We need a serial mesh for MeshOutput for now
    const_cast<EquationSystems&>(es).allgather();
  }

  es.build_variable_names  (names, NULL, system_names);
  es.build_solution_vector (soln, system_names);

  // For now, if we're doing a parallel format we're going to broadcast the vector from processor 0
  // to all of the processors to mimic what build_solution_vector used to do.
  // this is TERRIBLE and WASTEFUL but it's only temporary until we redesign the output of build_solution_vector
  // and the inputs to the I/O... both of which should actually be NumericVectors....
  if(_is_parallel_format)
    _obj->comm().broadcast(soln);
}

// Instantiate for our Mesh types.  If this becomes too cumbersome later,
// move any functions in this file to the header file instead.
template class MeshOutput<MeshBase>;
template class MeshOutput<UnstructuredMesh>;
template class MeshOutput<ParallelMesh>;

} // namespace libMesh
<commit_msg>fixup Nemesis writing<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// 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

// Local includes
#include "libmesh/equation_systems.h"
#include "libmesh/mesh_output.h"
#include "libmesh/parallel.h"
#include "libmesh/parallel_mesh.h"
#include "libmesh/unstructured_mesh.h"

namespace libMesh
{

template <class MT>
void MeshOutput<MT>::
_build_variable_names_and_solution_vector (const EquationSystems& es,
					   std::vector<Number>& soln,
					   std::vector<std::string>& names,
					   const std::set<std::string>* system_names)
{
  if(!_is_parallel_format)
  {
    // We need a serial mesh for MeshOutput for now
    const_cast<EquationSystems&>(es).allgather();
  }

  es.build_variable_names  (names, NULL, system_names);
  es.build_solution_vector (soln, system_names);

  // For now, if we're doing a parallel format we're going to broadcast the vector from processor 0
  // to all of the processors to mimic what build_solution_vector used to do.
  // this is TERRIBLE and WASTEFUL but it's only temporary until we redesign the output of build_solution_vector
  // and the inputs to the I/O... both of which should actually be NumericVectors....
  if(_is_parallel_format)
  {
    size_t size = soln.size();
    _obj->comm().broadcast(size);

    if(_obj->comm().rank())
      soln.resize(size);

    _obj->comm().broadcast(soln);
  }
}

// Instantiate for our Mesh types.  If this becomes too cumbersome later,
// move any functions in this file to the header file instead.
template class MeshOutput<MeshBase>;
template class MeshOutput<UnstructuredMesh>;
template class MeshOutput<ParallelMesh>;

} // namespace libMesh
<|endoftext|>