<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// 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 <unistd.h>

#include <functional>
#include <iostream>
#include <map>
#include <string>

#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "common/strings/compare.h"
#include "common/strings/patch.h"
#include "common/util/container_iterator_range.h"
#include "common/util/file_util.h"
#include "common/util/init_command_line.h"

// TODO(b/160323522): refactor into common/utils/ for other subcommand-using
// tools
using SubcommandArgs = std::vector<char*>;
using SubcommandArgsIterator = SubcommandArgs::const_iterator;
using SubcommandArgsRange =
    verible::container_iterator_range<SubcommandArgsIterator>;

using SubcommandFunction =
    std::function<absl::Status(const SubcommandArgsRange&, std::istream& ins,
                               std::ostream& outs, std::ostream& errs)>;

// Represents a function selected by the user.
struct SubcommandEntry {
  // sub-main function
  const SubcommandFunction main;

  // maybe a const std::string 'brief' for a half-line description

  // full description of command
  const std::string usage;
};

using SubcommandMap =
    std::map<std::string, SubcommandEntry, verible::StringViewCompare>;

// forward declarations of subcommand functions
static absl::Status ChangedLines(const SubcommandArgsRange&, std::istream&,
                                 std::ostream&, std::ostream&);
static absl::Status ApplyPick(const SubcommandArgsRange&, std::istream&,
                              std::ostream&, std::ostream&);
static absl::Status StdinTest(const SubcommandArgsRange&, std::istream&,
                              std::ostream&, std::ostream&);
static absl::Status CatTest(const SubcommandArgsRange&, std::istream&,
                            std::ostream&, std::ostream&);
static absl::Status Help(const SubcommandArgsRange&, std::istream&,
                         std::ostream&, std::ostream&);

static absl::Status Error(const SubcommandArgsRange& args, std::istream& ins,
                          std::ostream& outs, std::ostream& errs) {
  const auto unused_status = Help(args, ins, outs, errs);
  return absl::InvalidArgumentError("Unknown subcommand.");
}

static const SubcommandMap& GetSubcommandMap() {
  static const auto* kCommands = new SubcommandMap{
      {"help",
       {&Help,
        "help [command]\n"
        "Prints command help.  "
        "With no command or unknown command, this lists available "
        "commands.\n"}},

      // TODO(fangism): this should be a hidden command
      {"error",
       {&Error, "same as 'help', but exits non-zero to signal a user-error\n"}},

      {"changed-lines",  //
       {&ChangedLines,   //
        R"(changed-lines patchfile

Input:
  'patchfile' is a unified-diff file from 'diff -u' or other version-controlled
  equivalents like {p4,git,hg,cvs,svn} diff.  Use '-' to read from stdin.

Output: (stdout)
  This prints output in the following format per line:

    filename [line-ranges]

  where line-ranges (optional) is suitable for tools that accept a set of lines
  to operate on, e.g. "1-4,8,21-42".
  line-ranges is omitted for files that are considered new in the patchfile.
)"}},

      // TODO(b/156530527): add options like -p for path pruning
      // TODO(fangism): Support '-' as patchfile.
      {"apply-pick",
       {&ApplyPick,
        R"(apply-pick patchfile
Input:
  'patchfile' is a unified-diff file from 'diff -u' or other version-controlled
  equivalents like {p4,git,hg,cvs,svn} diff.

Effect:
  Modifies patched files in-place, following user selections on which patch
  hunks to apply.
)"}},

      // These are diagnostic tools and should be hidden from most users.
      {"stdin-test",  //
       {&StdinTest,   //
        R"(Test for re-opening stdin.

This interactivel prompts the user to enter text, separating files with an EOF
(Ctrl-D), and echoes the input text back to stdout.
)"}},
      {"cat-test",  //
       {&CatTest,   //
        R"(Test for (UNIX) cat-like functionality.

Usage: cat-test ARGS...

where each ARG could point to a file on the filesystem or be '-' to read from stdin.
Each '-' will prompt the user to enter text until EOF (Ctrl-D).
Each 'file' echoed back to stdout will be enclosed in banner lines with
<<<< and >>>>.
)"}},
  };
  return *kCommands;
}

absl::Status ChangedLines(const SubcommandArgsRange& args, std::istream& ins,
                          std::ostream& outs, std::ostream& errs) {
  if (args.empty()) {
    return absl::InvalidArgumentError(
        "Missing patchfile argument.  Use '-' for stdin.");
  }
  const auto patchfile = args[0];
  std::string patch_contents;
  {
    const auto status = verible::file::GetContents(patchfile, &patch_contents);
    if (!status.ok()) return status;
  }
  verible::PatchSet patch_set;
  {
    const auto status = patch_set.Parse(patch_contents);
    if (!status.ok()) return status;
  }
  const verible::FileLineNumbersMap changed_lines(
      patch_set.AddedLinesMap(false));
  for (const auto& file_lines : changed_lines) {
    outs << file_lines.first;
    if (!file_lines.second.empty()) {
      file_lines.second.FormatInclusive(outs << ' ', true);
    }
    outs << std::endl;
  }
  return absl::OkStatus();
}

absl::Status ApplyPick(const SubcommandArgsRange& args, std::istream& ins,
                       std::ostream& outs, std::ostream& errs) {
  if (args.empty()) {
    return absl::InvalidArgumentError("Missing patchfile argument.");
  }
  const auto patchfile = args[0];
  std::string patch_contents;
  {
    const auto status = verible::file::GetContents(patchfile, &patch_contents);
    if (!status.ok()) return status;
  }
  verible::PatchSet patch_set;
  {
    const auto status = patch_set.Parse(patch_contents);
    if (!status.ok()) return status;
  }
  return patch_set.PickApplyInPlace(ins, outs);
}

absl::Status StdinTest(const SubcommandArgsRange& args, std::istream& ins,
                       std::ostream& outs, std::ostream& errs) {
  constexpr size_t kOpenLimit = 10;
  outs << "This is a demo of re-opening std::cin, up to " << kOpenLimit
       << " times.\n"
          "Enter text when prompted.\n"
          "Ctrl-D sends an EOF to start the next file.\n"
          "Ctrl-C terminates the loop and exits the program."
       << std::endl;
  size_t file_count = 0;
  std::string line;
  for (; file_count < kOpenLimit; ++file_count) {
    outs << "==== file " << file_count << " ====" << std::endl;
    while (ins) {
      if (isatty(0)) outs << "enter text: ";
      std::getline(ins, line);
      outs << "echo: " << line << std::endl;
    }
    if (ins.eof()) {
      outs << "EOF reached.  Re-opening for next file" << std::endl;
      ins.clear();  // allows std::cin to read the next file
    }
  }
  return absl::OkStatus();
}

absl::Status CatTest(const SubcommandArgsRange& args, std::istream& ins,
                     std::ostream& outs, std::ostream& errs) {
  size_t file_count = 0;
  for (const auto& arg : args) {
    std::string contents;
    const auto status = verible::file::GetContents(arg, &contents);
    if (!status.ok()) return status;
    outs << "<<<< contents of file[" << file_count << "] (" << arg << ") <<<<"
         << std::endl;
    outs << contents;
    outs << ">>>> end of file[" << file_count << "] (" << arg << ") >>>>"
         << std::endl;
    ++file_count;
  }
  return absl::OkStatus();
}

static std::string ListCommands() {
  static const SubcommandMap& commands(GetSubcommandMap());
  return absl::StrCat("  ",
                      absl::StrJoin(commands, "\n  ",
                                    [](std::string* out,
                                       const SubcommandMap::value_type& entry) {
                                      *out += entry.first;  // command name
                                    }),
                      "\n");
}

static const SubcommandEntry& GetSubcommandEntry(absl::string_view command) {
  static const SubcommandMap& commands(GetSubcommandMap());
#if __cplusplus >= 201402L
  const auto iter = commands.find(command);  // heterogenous lookup
#else
  // without hetergenous lookup
  const auto iter = commands.find(std::string(command));
#endif
  if (iter == commands.end()) {
    // Command not found, print help and exit non-zero.
    return commands.find("error")->second;
  }
  return iter->second;
}

absl::Status Help(const SubcommandArgsRange& args, std::istream&, std::ostream&,
                  std::ostream& errs) {
  if (args.empty()) {
    errs << "available commands:\n" << ListCommands() << std::endl;
    return absl::OkStatus();
  }

  const SubcommandEntry& entry = GetSubcommandEntry(args.front());
  errs << entry.usage << std::endl;
  return absl::OkStatus();
}

int main(int argc, char* argv[]) {
  const std::string usage = absl::StrCat("usage: ", argv[0],
                                         " command args...\n"
                                         "available commands:\n",
                                         ListCommands());

  const auto args = verible::InitCommandLine(usage, &argc, &argv);
  if (args.size() == 1) {
    std::cerr << absl::ProgramUsageMessage() << std::endl;
    return 1;
  }
  // args[0] is the program name
  // args[1] is the subcommand
  // subcommand args start at [2]
  const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend());

  const auto& sub = GetSubcommandEntry(args[1]);
  // Run the subcommand.
  const auto status = sub.main(command_args, std::cin, std::cout, std::cerr);
  if (!status.ok()) {
    std::cerr << status.message() << std::endl;
    return 1;
  }
  return 0;
}
<commit_msg>patch_tool: Suppress hidden commands from help.<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// 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 <unistd.h>

#include <functional>
#include <iostream>
#include <map>
#include <string>

#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "common/strings/compare.h"
#include "common/strings/patch.h"
#include "common/util/container_iterator_range.h"
#include "common/util/file_util.h"
#include "common/util/init_command_line.h"

// TODO(b/160323522): refactor into common/utils/ for other subcommand-using
// tools
using SubcommandArgs = std::vector<char*>;
using SubcommandArgsIterator = SubcommandArgs::const_iterator;
using SubcommandArgsRange =
    verible::container_iterator_range<SubcommandArgsIterator>;

using SubcommandFunction =
    std::function<absl::Status(const SubcommandArgsRange&, std::istream& ins,
                               std::ostream& outs, std::ostream& errs)>;

// Represents a function selected by the user.
struct SubcommandEntry {
  // sub-main function
  const SubcommandFunction main;

  // maybe a const std::string 'brief' for a half-line description

  // full description of command
  const std::string usage;

  // If true, display this subcommand in 'help'.
  const bool show_in_help = true;
};

using SubcommandMap =
    std::map<std::string, SubcommandEntry, verible::StringViewCompare>;

// forward declarations of subcommand functions
static absl::Status ChangedLines(const SubcommandArgsRange&, std::istream&,
                                 std::ostream&, std::ostream&);
static absl::Status ApplyPick(const SubcommandArgsRange&, std::istream&,
                              std::ostream&, std::ostream&);
static absl::Status StdinTest(const SubcommandArgsRange&, std::istream&,
                              std::ostream&, std::ostream&);
static absl::Status CatTest(const SubcommandArgsRange&, std::istream&,
                            std::ostream&, std::ostream&);
static absl::Status Help(const SubcommandArgsRange&, std::istream&,
                         std::ostream&, std::ostream&);

static absl::Status Error(const SubcommandArgsRange& args, std::istream& ins,
                          std::ostream& outs, std::ostream& errs) {
  const auto unused_status = Help(args, ins, outs, errs);
  return absl::InvalidArgumentError("Unknown subcommand.");
}

static const SubcommandMap& GetSubcommandMap() {
  static const auto* kCommands = new SubcommandMap{
      {"help",
       {&Help,
        "help [command]\n"
        "Prints command help.  "
        "With no command or unknown command, this lists available "
        "commands.\n"}},

      {"error",
       {&Error, "same as 'help', but exits non-zero to signal a user-error\n",
        false}},

      {"changed-lines",  //
       {&ChangedLines,   //
        R"(changed-lines patchfile

Input:
  'patchfile' is a unified-diff file from 'diff -u' or other version-controlled
  equivalents like {p4,git,hg,cvs,svn} diff.  Use '-' to read from stdin.

Output: (stdout)
  This prints output in the following format per line:

    filename [line-ranges]

  where line-ranges (optional) is suitable for tools that accept a set of lines
  to operate on, e.g. "1-4,8,21-42".
  line-ranges is omitted for files that are considered new in the patchfile.
)"}},

      // TODO(b/156530527): add options like -p for path pruning
      // TODO(fangism): Support '-' as patchfile.
      {"apply-pick",
       {&ApplyPick,
        R"(apply-pick patchfile
Input:
  'patchfile' is a unified-diff file from 'diff -u' or other version-controlled
  equivalents like {p4,git,hg,cvs,svn} diff.

Effect:
  Modifies patched files in-place, following user selections on which patch
  hunks to apply.
)"}},

      {"stdin-test",  //
       {&StdinTest,   //
        R"(Test for re-opening stdin.

This interactivel prompts the user to enter text, separating files with an EOF
(Ctrl-D), and echoes the input text back to stdout.
)",
        false}},
      {"cat-test",  //
       {&CatTest,   //
        R"(Test for (UNIX) cat-like functionality.

Usage: cat-test ARGS...

where each ARG could point to a file on the filesystem or be '-' to read from stdin.
Each '-' will prompt the user to enter text until EOF (Ctrl-D).
Each 'file' echoed back to stdout will be enclosed in banner lines with
<<<< and >>>>.
)",
        false}},
  };
  return *kCommands;
}

absl::Status ChangedLines(const SubcommandArgsRange& args, std::istream& ins,
                          std::ostream& outs, std::ostream& errs) {
  if (args.empty()) {
    return absl::InvalidArgumentError(
        "Missing patchfile argument.  Use '-' for stdin.");
  }
  const auto patchfile = args[0];
  std::string patch_contents;
  {
    const auto status = verible::file::GetContents(patchfile, &patch_contents);
    if (!status.ok()) return status;
  }
  verible::PatchSet patch_set;
  {
    const auto status = patch_set.Parse(patch_contents);
    if (!status.ok()) return status;
  }
  const verible::FileLineNumbersMap changed_lines(
      patch_set.AddedLinesMap(false));
  for (const auto& file_lines : changed_lines) {
    outs << file_lines.first;
    if (!file_lines.second.empty()) {
      file_lines.second.FormatInclusive(outs << ' ', true);
    }
    outs << std::endl;
  }
  return absl::OkStatus();
}

absl::Status ApplyPick(const SubcommandArgsRange& args, std::istream& ins,
                       std::ostream& outs, std::ostream& errs) {
  if (args.empty()) {
    return absl::InvalidArgumentError("Missing patchfile argument.");
  }
  const auto patchfile = args[0];
  std::string patch_contents;
  {
    const auto status = verible::file::GetContents(patchfile, &patch_contents);
    if (!status.ok()) return status;
  }
  verible::PatchSet patch_set;
  {
    const auto status = patch_set.Parse(patch_contents);
    if (!status.ok()) return status;
  }
  return patch_set.PickApplyInPlace(ins, outs);
}

absl::Status StdinTest(const SubcommandArgsRange& args, std::istream& ins,
                       std::ostream& outs, std::ostream& errs) {
  constexpr size_t kOpenLimit = 10;
  outs << "This is a demo of re-opening std::cin, up to " << kOpenLimit
       << " times.\n"
          "Enter text when prompted.\n"
          "Ctrl-D sends an EOF to start the next file.\n"
          "Ctrl-C terminates the loop and exits the program."
       << std::endl;
  size_t file_count = 0;
  std::string line;
  for (; file_count < kOpenLimit; ++file_count) {
    outs << "==== file " << file_count << " ====" << std::endl;
    while (ins) {
      if (isatty(0)) outs << "enter text: ";
      std::getline(ins, line);
      outs << "echo: " << line << std::endl;
    }
    if (ins.eof()) {
      outs << "EOF reached.  Re-opening for next file" << std::endl;
      ins.clear();  // allows std::cin to read the next file
    }
  }
  return absl::OkStatus();
}

absl::Status CatTest(const SubcommandArgsRange& args, std::istream& ins,
                     std::ostream& outs, std::ostream& errs) {
  size_t file_count = 0;
  for (const auto& arg : args) {
    std::string contents;
    const auto status = verible::file::GetContents(arg, &contents);
    if (!status.ok()) return status;
    outs << "<<<< contents of file[" << file_count << "] (" << arg << ") <<<<"
         << std::endl;
    outs << contents;
    outs << ">>>> end of file[" << file_count << "] (" << arg << ") >>>>"
         << std::endl;
    ++file_count;
  }
  return absl::OkStatus();
}

static std::string ListCommands() {
  static const SubcommandMap& commands(GetSubcommandMap());
  std::vector<absl::string_view> public_commands;
  for (const auto& command : commands) {
    // List only public commands.
    if (command.second.show_in_help) {
      public_commands.emplace_back(command.first);
    }
  }
  return absl::StrCat("  ", absl::StrJoin(public_commands, "\n  "), "\n");
}

static const SubcommandEntry& GetSubcommandEntry(absl::string_view command) {
  static const SubcommandMap& commands(GetSubcommandMap());
#if __cplusplus >= 201402L
  const auto iter = commands.find(command);  // heterogenous lookup
#else
  // without hetergenous lookup
  const auto iter = commands.find(std::string(command));
#endif
  if (iter == commands.end()) {
    // Command not found, print help and exit non-zero.
    return commands.find("error")->second;
  }
  return iter->second;
}

absl::Status Help(const SubcommandArgsRange& args, std::istream&, std::ostream&,
                  std::ostream& errs) {
  if (args.empty()) {
    errs << "available commands:\n" << ListCommands() << std::endl;
    return absl::OkStatus();
  }

  const SubcommandEntry& entry = GetSubcommandEntry(args.front());
  errs << entry.usage << std::endl;
  return absl::OkStatus();
}

int main(int argc, char* argv[]) {
  const std::string usage = absl::StrCat("usage: ", argv[0],
                                         " command args...\n"
                                         "available commands:\n",
                                         ListCommands());

  const auto args = verible::InitCommandLine(usage, &argc, &argv);
  if (args.size() == 1) {
    std::cerr << absl::ProgramUsageMessage() << std::endl;
    return 1;
  }
  // args[0] is the program name
  // args[1] is the subcommand
  // subcommand args start at [2]
  const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend());

  const auto& sub = GetSubcommandEntry(args[1]);
  // Run the subcommand.
  const auto status = sub.main(command_args, std::cin, std::cout, std::cerr);
  if (!status.ok()) {
    std::cerr << status.message() << std::endl;
    return 1;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <pthread.h>
#include "simulator.h"
#include "thread_manager.h"
#include "tile_manager.h"
#include "tile.h"
#include "core_model.h"
#include "clock_converter.h"
#include "config_file.hpp"
#include "handle_args.h"
#include "fxsupport.h"
#include "carbon_user.h"
#include "thread_support_private.h"

static config::ConfigFile cfg;

tile_id_t CarbonGetTileId()
{
   return Sim()->getTileManager()->getCurrentTileID();
}

int CarbonStartSim(int argc, char **argv)
{
   string_vec args;

   // Set the default config path if it isn't
   // overwritten on the command line.
   std::string config_path = "carbon_sim.cfg";

   // Parse the arguments that are relative
   // to the config file changes as well
   // as extracting the config_path
   parse_args(args, config_path, argc, argv);

   cfg.load(config_path);
   handle_args(args, cfg);

   Simulator::setConfig(&cfg);

   Simulator::allocate();
   Sim()->start();

   if (Config::getSingleton()->getCurrentProcessNum() == 0)
   {
      // Main process
      Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));

      CarbonSpawnThreadSpawner();

      LOG_PRINT("Returning to main()...");
      return 0;
   }
   else
   {
      LOG_PRINT("Replacing main()...");

      CarbonThreadSpawner (NULL);

      // Not main process
      while (!Sim()->finished())
         usleep(100);

      CarbonStopSim();

      // Otherwise we will run main ...
      exit(0);
   }
}

void CarbonStopSim()
{
   Simulator::release();
}

UInt64 CarbonGetTime()
{
   // Floating Point Save/Restore
   FloatingPointHandler floating_point_handler;

   Core* core = Sim()->getTileManager()->getCurrentCore();
   UInt64 time = convertCycleCount(core->getModel()->getCycleCount(), core->getTile()->getFrequency(), 1.0);

   return time;
}
<commit_msg>[absolute time] - changed CargonGetTime() to absolute time.<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <pthread.h>
#include "simulator.h"
#include "thread_manager.h"
#include "tile_manager.h"
#include "tile.h"
#include "core_model.h"
#include "clock_converter.h"
#include "config_file.hpp"
#include "handle_args.h"
#include "fxsupport.h"
#include "carbon_user.h"
#include "thread_support_private.h"

static config::ConfigFile cfg;

tile_id_t CarbonGetTileId()
{
   return Sim()->getTileManager()->getCurrentTileID();
}

int CarbonStartSim(int argc, char **argv)
{
   string_vec args;

   // Set the default config path if it isn't
   // overwritten on the command line.
   std::string config_path = "carbon_sim.cfg";

   // Parse the arguments that are relative
   // to the config file changes as well
   // as extracting the config_path
   parse_args(args, config_path, argc, argv);

   cfg.load(config_path);
   handle_args(args, cfg);

   Simulator::setConfig(&cfg);

   Simulator::allocate();
   Sim()->start();

   if (Config::getSingleton()->getCurrentProcessNum() == 0)
   {
      // Main process
      Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));

      CarbonSpawnThreadSpawner();

      LOG_PRINT("Returning to main()...");
      return 0;
   }
   else
   {
      LOG_PRINT("Replacing main()...");

      CarbonThreadSpawner (NULL);

      // Not main process
      while (!Sim()->finished())
         usleep(100);

      CarbonStopSim();

      // Otherwise we will run main ...
      exit(0);
   }
}

void CarbonStopSim()
{
   Simulator::release();
}

UInt64 CarbonGetTime()
{
   // Floating Point Save/Restore
   FloatingPointHandler floating_point_handler;

   Core* core = Sim()->getTileManager()->getCurrentCore();
   UInt64 time = core->getModel()->getCurrTime().toNanosec();

   return time;
}
<|endoftext|>


<commit_before>#include "hal.h"
#include "markAncestors.h"

using namespace std;
using namespace hal;

static void initParser(CLParser &optionsParser) {
    optionsParser.addArgument("inFile", "existing tree");
    optionsParser.addArgument("botAlignmentFile", "tree containing insert, its "
                                                  "proper bottom segments, and the new leaf genome");
    optionsParser.addArgument("topAlignmentFile", "tree containing insert, its "
                                                  "parent, and its proper top segments");
    optionsParser.addArgument("parentName", "insert's future parent");
    optionsParser.addArgument("insertName", "insert name");
    optionsParser.addArgument("childName", "insert's future child");
    optionsParser.addArgument("leafName", "name of new leaf genome");
    optionsParser.addArgument("upperBranchLength", "length of branch from parent"
                                                   " to insert");
    optionsParser.addArgument("leafBranchLength", "leaf branch length");
    optionsParser.addOptionFlag("noMarkAncestors", "don't mark ancestors for"
                                                   " update",
                                false);
}

int main(int argc, char *argv[]) {
    CLParser optionsParser(WRITE_ACCESS);
    initParser(optionsParser);
    string inPath, botAlignmentPath, topAlignmentPath, parentName, insertName, childName, leafName;
    double upperBranchLength, leafBranchLength;
    bool noMarkAncestors;
    try {
        optionsParser.parseOptions(argc, argv);
        inPath = optionsParser.getArgument<string>("inFile");
        botAlignmentPath = optionsParser.getArgument<string>("botAlignmentFile");
        topAlignmentPath = optionsParser.getArgument<string>("topAlignmentFile");
        parentName = optionsParser.getArgument<string>("parentName");
        insertName = optionsParser.getArgument<string>("insertName");
        childName = optionsParser.getArgument<string>("childName");
        leafName = optionsParser.getArgument<string>("leafName");
        upperBranchLength = optionsParser.getArgument<double>("upperBranchLength");
        leafBranchLength = optionsParser.getArgument<double>("leafBranchLength");
        noMarkAncestors = optionsParser.getFlag("noMarkAncestors");
    } catch (exception &e) {
        optionsParser.printUsage(cerr);
        return 1;
    }
    AlignmentPtr mainAlignment(openHalAlignment(inPath, &optionsParser, READ_ACCESS | WRITE_ACCESS));
    AlignmentConstPtr botAlignment(openHalAlignment(botAlignmentPath, &optionsParser));
    AlignmentConstPtr topAlignment(openHalAlignment(topAlignmentPath, &optionsParser));
    mainAlignment->insertGenome(insertName, parentName, childName, upperBranchLength);
    mainAlignment->addLeafGenome(leafName, insertName, leafBranchLength);
    // Insert the new intermediate node.
    Genome *insertGenome = mainAlignment->openGenome(insertName);
    const Genome *topInsertGenome = topAlignment->openGenome(insertName);
    const Genome *botInsertGenome = botAlignment->openGenome(insertName);
    topInsertGenome->copyDimensions(insertGenome);
    topInsertGenome->copyTopDimensions(insertGenome);
    botInsertGenome->copyBottomDimensions(insertGenome);
    topInsertGenome->copySequence(insertGenome);
    topInsertGenome->copyTopSegments(insertGenome);
    topInsertGenome->copyMetadata(insertGenome);
    botInsertGenome->copyBottomSegments(insertGenome);
    insertGenome->fixParseInfo();

    // Copy the bottom segments for the parent genome from the top alignment.
    Genome *parentGenome = mainAlignment->openGenome(parentName);
    const Genome *botParentGenome = topAlignment->openGenome(parentName);
    botParentGenome->copyBottomDimensions(parentGenome);
    botParentGenome->copyBottomSegments(parentGenome);
    parentGenome->fixParseInfo();

    // Fix the parent's other children as well.
    vector<string> allChildren = mainAlignment->getChildNames(parentName);
    for (size_t i = 0; i < allChildren.size(); i++) {
        if (allChildren[i] != insertName) {
            Genome *outGenome = mainAlignment->openGenome(allChildren[i]);
            const Genome *topSegmentsGenome = topAlignment->openGenome(allChildren[i]);
            topSegmentsGenome->copyTopDimensions(outGenome);
            topSegmentsGenome->copyTopSegments(outGenome);
            outGenome->fixParseInfo();
        }
    }

    // Copy the top segments for the child genome from the bottom alignment.
    Genome *childGenome = mainAlignment->openGenome(childName);
    const Genome *topChildGenome = botAlignment->openGenome(childName);
    topChildGenome->copyTopDimensions(childGenome);
    topChildGenome->copyTopSegments(childGenome);
    childGenome->fixParseInfo();

    // Copy the entire genome for the leaf from the bottom alignment.
    Genome *outLeafGenome = mainAlignment->openGenome(leafName);
    const Genome *inLeafGenome = botAlignment->openGenome(leafName);
    inLeafGenome->copy(outLeafGenome);
    if (!noMarkAncestors) {
        markAncestorsForUpdate(mainAlignment.get(), insertName);
    }
}
<commit_msg>Copy sequence dimensions in halAddToBranch<commit_after>#include "hal.h"
#include "markAncestors.h"

using namespace std;
using namespace hal;

static void initParser(CLParser &optionsParser) {
    optionsParser.addArgument("inFile", "existing tree");
    optionsParser.addArgument("botAlignmentFile", "tree containing insert, its "
                                                  "proper bottom segments, and the new leaf genome");
    optionsParser.addArgument("topAlignmentFile", "tree containing insert, its "
                                                  "parent, and its proper top segments");
    optionsParser.addArgument("parentName", "insert's future parent");
    optionsParser.addArgument("insertName", "insert name");
    optionsParser.addArgument("childName", "insert's future child");
    optionsParser.addArgument("leafName", "name of new leaf genome");
    optionsParser.addArgument("upperBranchLength", "length of branch from parent"
                                                   " to insert");
    optionsParser.addArgument("leafBranchLength", "leaf branch length");
    optionsParser.addOptionFlag("noMarkAncestors", "don't mark ancestors for"
                                                   " update",
                                false);
}

int main(int argc, char *argv[]) {
    CLParser optionsParser(WRITE_ACCESS);
    initParser(optionsParser);
    string inPath, botAlignmentPath, topAlignmentPath, parentName, insertName, childName, leafName;
    double upperBranchLength, leafBranchLength;
    bool noMarkAncestors;
    try {
        optionsParser.parseOptions(argc, argv);
        inPath = optionsParser.getArgument<string>("inFile");
        botAlignmentPath = optionsParser.getArgument<string>("botAlignmentFile");
        topAlignmentPath = optionsParser.getArgument<string>("topAlignmentFile");
        parentName = optionsParser.getArgument<string>("parentName");
        insertName = optionsParser.getArgument<string>("insertName");
        childName = optionsParser.getArgument<string>("childName");
        leafName = optionsParser.getArgument<string>("leafName");
        upperBranchLength = optionsParser.getArgument<double>("upperBranchLength");
        leafBranchLength = optionsParser.getArgument<double>("leafBranchLength");
        noMarkAncestors = optionsParser.getFlag("noMarkAncestors");
    } catch (exception &e) {
        optionsParser.printUsage(cerr);
        return 1;
    }
    AlignmentPtr mainAlignment(openHalAlignment(inPath, &optionsParser, READ_ACCESS | WRITE_ACCESS));
    AlignmentConstPtr botAlignment(openHalAlignment(botAlignmentPath, &optionsParser));
    AlignmentConstPtr topAlignment(openHalAlignment(topAlignmentPath, &optionsParser));

    // Add in the insert genome.
    mainAlignment->insertGenome(insertName, parentName, childName, upperBranchLength);

    // Add in the new leaf genome and its dimensions (so that it has the proper number of sequences).
    mainAlignment->addLeafGenome(leafName, insertName, leafBranchLength);
    Genome *outLeafGenome = mainAlignment->openGenome(leafName);
    const Genome *inLeafGenome = botAlignment->openGenome(leafName);
    inLeafGenome->copyDimensions(outLeafGenome);

    // Insert the new intermediate node.
    Genome *insertGenome = mainAlignment->openGenome(insertName);
    const Genome *topInsertGenome = topAlignment->openGenome(insertName);
    const Genome *botInsertGenome = botAlignment->openGenome(insertName);
    topInsertGenome->copyDimensions(insertGenome);
    topInsertGenome->copyTopDimensions(insertGenome);
    botInsertGenome->copyBottomDimensions(insertGenome);
    topInsertGenome->copySequence(insertGenome);
    topInsertGenome->copyTopSegments(insertGenome);
    topInsertGenome->copyMetadata(insertGenome);
    botInsertGenome->copyBottomSegments(insertGenome);
    insertGenome->fixParseInfo();

    // Copy the bottom segments for the parent genome from the top alignment.
    Genome *parentGenome = mainAlignment->openGenome(parentName);
    const Genome *botParentGenome = topAlignment->openGenome(parentName);
    botParentGenome->copyBottomDimensions(parentGenome);
    botParentGenome->copyBottomSegments(parentGenome);
    parentGenome->fixParseInfo();

    // Fix the parent's other children as well.
    vector<string> allChildren = mainAlignment->getChildNames(parentName);
    for (size_t i = 0; i < allChildren.size(); i++) {
        if (allChildren[i] != insertName) {
            Genome *outGenome = mainAlignment->openGenome(allChildren[i]);
            const Genome *topSegmentsGenome = topAlignment->openGenome(allChildren[i]);
            topSegmentsGenome->copyTopDimensions(outGenome);
            topSegmentsGenome->copyTopSegments(outGenome);
            outGenome->fixParseInfo();
        }
    }

    // Copy the top segments for the child genome from the bottom alignment.
    Genome *childGenome = mainAlignment->openGenome(childName);
    const Genome *topChildGenome = botAlignment->openGenome(childName);
    topChildGenome->copyTopDimensions(childGenome);
    topChildGenome->copyTopSegments(childGenome);
    childGenome->fixParseInfo();

    // Copy the entire genome for the leaf from the bottom alignment.
    inLeafGenome->copy(outLeafGenome);
    if (!noMarkAncestors) {
        markAncestorsForUpdate(mainAlignment.get(), insertName);
    }
}
<|endoftext|>


<commit_before>/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2010 Red Hat, Inc.

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

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

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef WIN32
#include "config.h"
#endif

#include "common.h"
#include "debug.h"
#include "utils.h"
#include "mjpeg_decoder.h"

enum {
    STATE_READ_HEADER,
    STATE_START_DECOMPRESS,
    STATE_READ_SCANLINES,
    STATE_FINISH_DECOMPRESS
};

extern "C" {

    static void init_source(j_decompress_ptr cinfo)
    {
    }

    static boolean fill_input_buffer(j_decompress_ptr cinfo)
    {
        return FALSE;
    }

    void mjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
    {
        MJpegDecoder *decoder = (MJpegDecoder *)cinfo;
        if (num_bytes > 0) {
            if (cinfo->src->bytes_in_buffer >= (size_t)num_bytes) {
                cinfo->src->next_input_byte += (size_t) num_bytes;
                cinfo->src->bytes_in_buffer -= (size_t) num_bytes;
            } else {
                decoder->_extra_skip = num_bytes - cinfo->src->bytes_in_buffer;
                cinfo->src->bytes_in_buffer = 0;
            }
        }
    }

    static void term_source (j_decompress_ptr cinfo)
    {
        return;
    }
}

MJpegDecoder::MJpegDecoder(int width, int height,
                           int stride,
                           uint8_t *frame) :
    _data(NULL)
    , _data_size(0)
    , _data_start(0)
    , _data_end(0)
    , _extra_skip(0)
    , _width(width)
    , _height(height)
    , _stride(stride)
    , _frame(frame)
    , _y(0)
    , _state(0)
{
    memset(&_cinfo, 0, sizeof(_cinfo));
    _cinfo.err = jpeg_std_error (&_jerr);
    jpeg_create_decompress (&_cinfo);

    _cinfo.src = &_jsrc;
    _cinfo.src->init_source = init_source;
    _cinfo.src->fill_input_buffer = fill_input_buffer;
    _cinfo.src->skip_input_data = mjpeg_skip_input_data;
    _cinfo.src->resync_to_restart = jpeg_resync_to_restart;
    _cinfo.src->term_source = term_source;

    _scanline = new uint8_t[width * 3];
}

MJpegDecoder::~MJpegDecoder()
{
    delete [] _scanline;
    if (_data) {
        delete [] _data;
    }
}

void MJpegDecoder::convert_scanline(void)
{
    uint32_t *row;
    uint32_t c;
    uint8_t *s;
    int x;

    ASSERT(_width % 2 == 0);
    ASSERT(_height % 2 == 0);

   row = (uint32_t *)(_frame + _y * _stride);
    s = _scanline;
    for (x = 0; x < _width; x++) {
        /* This switches the order of red and blue.
           This is not accidental, but for backwards
           compatibility, since a bug in the old
           ffmpeg-using mjpeg code got these switched
           due to endianness issues. */
        c = s[0] | s[1] << 8 | s[2] << 16;
        s += 3;
        *row++ = c;
    }
}

bool MJpegDecoder::decode_data(uint8_t *data, size_t length)
{
    uint8_t *new_data;
    size_t data_len;
    int res;
    bool got_picture;

    got_picture = false;

    if (_extra_skip > 0) {
        if (_extra_skip >= length) {
            _extra_skip -= length;
            return false;
        } else {
            data += _extra_skip;
            length -= _extra_skip;
            _extra_skip = 0;
        }
    }

    if (_data_size - _data_end < length) {
        /* Can't fit in tail */

        data_len = _data_end - _data_start;
        if (_data_size - data_len < length) {
            /* Can't fit at all, grow a bit */
            _data_size = _data_size + length * 2;
            new_data = new uint8_t[_data_size];
            memcpy (new_data, _data + _data_start, data_len);
            delete [] _data;
            _data = new_data;
        } else {
            /* Just needs to compact */
            memmove (_data, _data + _data_start, data_len);
        }
        _data_start = 0;
        _data_end = data_len;
    }

    memcpy (_data + _data_end, data, length);
    _data_end += length;

    _jsrc.next_input_byte = _data + _data_start;
    _jsrc.bytes_in_buffer = _data_end - _data_start;

    switch (_state) {
    case STATE_READ_HEADER:
        res = jpeg_read_header(&_cinfo, TRUE);
        if (res == JPEG_SUSPENDED) {
            break;
        }

        _cinfo.do_fancy_upsampling = FALSE;
        _cinfo.do_block_smoothing = FALSE;
        _cinfo.out_color_space = JCS_RGB;

        PANIC_ON(_cinfo.image_width != _width);
        PANIC_ON(_cinfo.image_height != _height);

        _state = STATE_START_DECOMPRESS;

        /* fall through */
    case STATE_START_DECOMPRESS:
        res = jpeg_start_decompress (&_cinfo);

        if (!res) {
            break;
        }

        _state = STATE_READ_SCANLINES;

        /* fall through */
    case STATE_READ_SCANLINES:
        res = 0;
        while (_y < _height) {
            res = jpeg_read_scanlines(&_cinfo, &_scanline, 1);

            if (res == 0) {
                break;
            }

            convert_scanline();
            _y++;
        }
        if (res == 0) {
            break;
        }

        _state = STATE_FINISH_DECOMPRESS;

        /* fall through */
    case STATE_FINISH_DECOMPRESS:
        res = jpeg_finish_decompress (&_cinfo);

        if (!res) {
            break;
        }

        _y = 0;
        _state = STATE_READ_HEADER;
        got_picture = true;

        break;
    }

    _data_start = _jsrc.next_input_byte - _data;
    _data_end = _data_start + _jsrc.bytes_in_buffer;

    return got_picture;
}
<commit_msg>Free the jpeg decoder with the stream<commit_after>/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2010 Red Hat, Inc.

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

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

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef WIN32
#include "config.h"
#endif

#include "common.h"
#include "debug.h"
#include "utils.h"
#include "mjpeg_decoder.h"

enum {
    STATE_READ_HEADER,
    STATE_START_DECOMPRESS,
    STATE_READ_SCANLINES,
    STATE_FINISH_DECOMPRESS
};

extern "C" {

    static void init_source(j_decompress_ptr cinfo)
    {
    }

    static boolean fill_input_buffer(j_decompress_ptr cinfo)
    {
        return FALSE;
    }

    void mjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
    {
        MJpegDecoder *decoder = (MJpegDecoder *)cinfo;
        if (num_bytes > 0) {
            if (cinfo->src->bytes_in_buffer >= (size_t)num_bytes) {
                cinfo->src->next_input_byte += (size_t) num_bytes;
                cinfo->src->bytes_in_buffer -= (size_t) num_bytes;
            } else {
                decoder->_extra_skip = num_bytes - cinfo->src->bytes_in_buffer;
                cinfo->src->bytes_in_buffer = 0;
            }
        }
    }

    static void term_source (j_decompress_ptr cinfo)
    {
        return;
    }
}

MJpegDecoder::MJpegDecoder(int width, int height,
                           int stride,
                           uint8_t *frame) :
    _data(NULL)
    , _data_size(0)
    , _data_start(0)
    , _data_end(0)
    , _extra_skip(0)
    , _width(width)
    , _height(height)
    , _stride(stride)
    , _frame(frame)
    , _y(0)
    , _state(0)
{
    memset(&_cinfo, 0, sizeof(_cinfo));
    _cinfo.err = jpeg_std_error (&_jerr);
    jpeg_create_decompress (&_cinfo);

    _cinfo.src = &_jsrc;
    _cinfo.src->init_source = init_source;
    _cinfo.src->fill_input_buffer = fill_input_buffer;
    _cinfo.src->skip_input_data = mjpeg_skip_input_data;
    _cinfo.src->resync_to_restart = jpeg_resync_to_restart;
    _cinfo.src->term_source = term_source;

    _scanline = new uint8_t[width * 3];
}

MJpegDecoder::~MJpegDecoder()
{
    jpeg_destroy_decompress(&_cinfo);
    delete [] _scanline;
    if (_data) {
        delete [] _data;
    }
}

void MJpegDecoder::convert_scanline(void)
{
    uint32_t *row;
    uint32_t c;
    uint8_t *s;
    int x;

    ASSERT(_width % 2 == 0);
    ASSERT(_height % 2 == 0);

   row = (uint32_t *)(_frame + _y * _stride);
    s = _scanline;
    for (x = 0; x < _width; x++) {
        /* This switches the order of red and blue.
           This is not accidental, but for backwards
           compatibility, since a bug in the old
           ffmpeg-using mjpeg code got these switched
           due to endianness issues. */
        c = s[0] | s[1] << 8 | s[2] << 16;
        s += 3;
        *row++ = c;
    }
}

bool MJpegDecoder::decode_data(uint8_t *data, size_t length)
{
    uint8_t *new_data;
    size_t data_len;
    int res;
    bool got_picture;

    got_picture = false;

    if (_extra_skip > 0) {
        if (_extra_skip >= length) {
            _extra_skip -= length;
            return false;
        } else {
            data += _extra_skip;
            length -= _extra_skip;
            _extra_skip = 0;
        }
    }

    if (_data_size - _data_end < length) {
        /* Can't fit in tail */

        data_len = _data_end - _data_start;
        if (_data_size - data_len < length) {
            /* Can't fit at all, grow a bit */
            _data_size = _data_size + length * 2;
            new_data = new uint8_t[_data_size];
            memcpy (new_data, _data + _data_start, data_len);
            delete [] _data;
            _data = new_data;
        } else {
            /* Just needs to compact */
            memmove (_data, _data + _data_start, data_len);
        }
        _data_start = 0;
        _data_end = data_len;
    }

    memcpy (_data + _data_end, data, length);
    _data_end += length;

    _jsrc.next_input_byte = _data + _data_start;
    _jsrc.bytes_in_buffer = _data_end - _data_start;

    switch (_state) {
    case STATE_READ_HEADER:
        res = jpeg_read_header(&_cinfo, TRUE);
        if (res == JPEG_SUSPENDED) {
            break;
        }

        _cinfo.do_fancy_upsampling = FALSE;
        _cinfo.do_block_smoothing = FALSE;
        _cinfo.out_color_space = JCS_RGB;

        PANIC_ON(_cinfo.image_width != _width);
        PANIC_ON(_cinfo.image_height != _height);

        _state = STATE_START_DECOMPRESS;

        /* fall through */
    case STATE_START_DECOMPRESS:
        res = jpeg_start_decompress (&_cinfo);

        if (!res) {
            break;
        }

        _state = STATE_READ_SCANLINES;

        /* fall through */
    case STATE_READ_SCANLINES:
        res = 0;
        while (_y < _height) {
            res = jpeg_read_scanlines(&_cinfo, &_scanline, 1);

            if (res == 0) {
                break;
            }

            convert_scanline();
            _y++;
        }
        if (res == 0) {
            break;
        }

        _state = STATE_FINISH_DECOMPRESS;

        /* fall through */
    case STATE_FINISH_DECOMPRESS:
        res = jpeg_finish_decompress (&_cinfo);

        if (!res) {
            break;
        }

        _y = 0;
        _state = STATE_READ_HEADER;
        got_picture = true;

        break;
    }

    _data_start = _jsrc.next_input_byte - _data;
    _data_end = _data_start + _jsrc.bytes_in_buffer;

    return got_picture;
}
<|endoftext|>


<commit_before>#include "vtrc-rpc-channel.h"

#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>

#include "protocol/vtrc-rpc-lowlevel.pb.h"

#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-closure-holder.h"

namespace vtrc { namespace client {

    namespace gpb = google::protobuf;

    struct rpc_channel::impl {

        vtrc::weak_ptr<common::connection_iface> connection_;

        rpc_channel *parent_;

        impl(vtrc::shared_ptr<common::connection_iface> c)
            :connection_(c)
        {}

        void CallMethod(const gpb::MethodDescriptor* method,
                        gpb::RpcController* controller,
                        const gpb::Message* request,
                        gpb::Message* response,
                        gpb::Closure* done)
        {
            common::closure_holder hold(done);

            common::connection_iface_sptr cl(connection_.lock( ));

            if( cl.get( ) == NULL ) {
                throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
                                               "Connection is lost");
            }

            vtrc_rpc_lowlevel::options call_opt
                             ( cl->get_protocol( ).get_method_options(method) );

            std::string service_name(method->service( )->full_name( ));
            std::string method_name(method->name( ));

            vtrc::shared_ptr<
                    vtrc_rpc_lowlevel::lowlevel_unit
            > llu(new vtrc_rpc_lowlevel::lowlevel_unit);

            llu->mutable_call( )->set_service( service_name );
            llu->mutable_call( )->set_method( method_name );

            llu->set_request( request->SerializeAsString( ) );
            llu->set_response( response->SerializeAsString( ) );

            llu->mutable_info( )->set_message_type(
                               vtrc_rpc_lowlevel::message_info::MESSAGE_CALL );

            uint64_t call_id = cl->get_protocol( ).next_index( );

            llu->set_id( call_id );

            if( call_opt.wait( ) ) { // WAITABLE CALL

                cl->get_protocol( ).call_rpc_method( call_id, *llu );

                std::deque< vtrc::shared_ptr <
                            vtrc_rpc_lowlevel::lowlevel_unit
                          >
                > data_list;

                cl->get_protocol( ).wait_call_slot( call_id, data_list,
                                                    call_opt.call_timeout( ) );

                vtrc::shared_ptr<vtrc_rpc_lowlevel::lowlevel_unit> top
                                                        ( data_list.front( ) );

                if( top->error( ).code( ) != vtrc_errors::ERR_NO_ERROR )
                    throw vtrc::common::exception( top->error( ).code( ),
                                                 top->error( ).category( ),
                                                 top->error( ).additional( ) );

                response->ParseFromString( top->response( ) );

                cl->get_protocol( ).close_slot( call_id );

            } else { // NOT WAITABLE CALL
                cl->get_protocol( ).call_rpc_method( *llu );
            }
        }
    };

    rpc_channel::rpc_channel( common::connection_iface_sptr c )
        :impl_(new impl(c))
    {
        impl_->parent_ = this;
    }

    rpc_channel::~rpc_channel( )
    {
        delete impl_;
    }

    void rpc_channel::CallMethod(const gpb::MethodDescriptor* method,
                    gpb::RpcController* controller,
                    const gpb::Message* request,
                    gpb::Message* response,
                    gpb::Closure* done)
    {
        impl_->CallMethod( method, controller, request, response, done );
    }

}}
<commit_msg>protocol<commit_after>#include "vtrc-rpc-channel.h"

#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>

#include "protocol/vtrc-rpc-lowlevel.pb.h"

#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-protocol-layer.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-closure-holder.h"

namespace vtrc { namespace client {

    namespace gpb = google::protobuf;

    struct rpc_channel::impl {

        vtrc::weak_ptr<common::connection_iface> connection_;

        rpc_channel *parent_;

        impl(vtrc::shared_ptr<common::connection_iface> c)
            :connection_(c)
        {}

        void CallMethod(const gpb::MethodDescriptor* method,
                        gpb::RpcController* controller,
                        const gpb::Message* request,
                        gpb::Message* response,
                        gpb::Closure* done)
        {
            common::closure_holder hold(done);

            common::connection_iface_sptr cl(connection_.lock( ));

            if( cl.get( ) == NULL ) {
                throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
                                               "Connection lost");
            }

            vtrc_rpc_lowlevel::options call_opt
                             ( cl->get_protocol( ).get_method_options(method) );

            std::string service_name(method->service( )->full_name( ));
            std::string method_name(method->name( ));

            vtrc::shared_ptr<
                    vtrc_rpc_lowlevel::lowlevel_unit
            > llu(new vtrc_rpc_lowlevel::lowlevel_unit);

            llu->mutable_call( )->set_service( service_name );
            llu->mutable_call( )->set_method( method_name );

            llu->set_request( request->SerializeAsString( ) );
            llu->set_response( response->SerializeAsString( ) );

            llu->mutable_info( )->set_message_type(
                               vtrc_rpc_lowlevel::message_info::MESSAGE_CALL );

            uint64_t call_id = cl->get_protocol( ).next_index( );

            llu->set_id( call_id );

            if( call_opt.wait( ) ) { // WAITABLE CALL

                cl->get_protocol( ).call_rpc_method( call_id, *llu );

                std::deque< vtrc::shared_ptr <
                            vtrc_rpc_lowlevel::lowlevel_unit
                          >
                > data_list;

                cl->get_protocol( ).wait_call_slot( call_id, data_list,
                                                    call_opt.call_timeout( ) );

                vtrc::shared_ptr<vtrc_rpc_lowlevel::lowlevel_unit> top
                                                        ( data_list.front( ) );

                if( top->error( ).code( ) != vtrc_errors::ERR_NO_ERROR )
                    throw vtrc::common::exception( top->error( ).code( ),
                                                 top->error( ).category( ),
                                                 top->error( ).additional( ) );

                response->ParseFromString( top->response( ) );

                cl->get_protocol( ).close_slot( call_id );

            } else { // NOT WAITABLE CALL
                cl->get_protocol( ).call_rpc_method( *llu );
            }
        }
    };

    rpc_channel::rpc_channel( common::connection_iface_sptr c )
        :impl_(new impl(c))
    {
        impl_->parent_ = this;
    }

    rpc_channel::~rpc_channel( )
    {
        delete impl_;
    }

    void rpc_channel::CallMethod(const gpb::MethodDescriptor* method,
                    gpb::RpcController* controller,
                    const gpb::Message* request,
                    gpb::Message* response,
                    gpb::Closure* done)
    {
        impl_->CallMethod( method, controller, request, response, done );
    }

}}
<|endoftext|>


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

#include "chrome/browser/translate/translate_manager.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/translation_service.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobars_delegates.h"
#include "chrome/browser/translate/translate_prefs.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_service.h"

TranslateManager::~TranslateManager() {
}

void TranslateManager::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::NAV_ENTRY_COMMITTED: {
      // We have navigated to a new page.
      NavigationController* controller =
          Source<NavigationController>(source).ptr();
      NavigationEntry* entry = controller->GetActiveEntry();
      if (!entry->language().empty()) {
        // The language for that page is known (it must be a back/forward
        // navigation to a page we already visited).
        InitiateTranslation(controller->tab_contents(), entry->language());
      }
      break;
    }
    case NotificationType::TAB_LANGUAGE_DETERMINED: {
      TabContents* tab = Source<TabContents>(source).ptr();
      std::string language = *(Details<std::string>(details).ptr());
      InitiateTranslation(tab, language);
      break;
    }
    case NotificationType::PAGE_TRANSLATED: {
      TabContents* tab = Source<TabContents>(source).ptr();
      std::pair<std::string, std::string>* language_pair =
          (Details<std::pair<std::string, std::string> >(details).ptr());
      PrefService* prefs = GetPrefService(tab);
      tab->AddInfoBar(new AfterTranslateInfoBarDelegate(tab, prefs,
                                                        language_pair->first,
                                                        language_pair->second));
      break;
    }
    default:
      NOTREACHED();
  }
}

TranslateManager::TranslateManager() {
  if (!TranslationService::IsTranslationEnabled())
    return;

  notification_registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                              NotificationService::AllSources());
  notification_registrar_.Add(this, NotificationType::TAB_LANGUAGE_DETERMINED,
                              NotificationService::AllSources());
  notification_registrar_.Add(this, NotificationType::PAGE_TRANSLATED,
                              NotificationService::AllSources());
}

void TranslateManager::InitiateTranslation(TabContents* tab,
                                           const std::string& page_lang) {
  PrefService* prefs = GetPrefService(tab);
  NavigationEntry* entry = tab->controller().GetActiveEntry();
  if (!entry) {
    NOTREACHED();
    return;
  }

  std::string chrome_lang = g_browser_process->GetApplicationLocale();

  // We don't want to translate:
  // - any Chrome specific page (New Tab Page, Download, History... pages).
  // - similar languages (ex: en-US to en).
  // - any user black-listed URLs or user selected language combination.
  if (entry->url().SchemeIs("chrome") || page_lang == chrome_lang ||
      !TranslationService::ShouldTranslatePage(page_lang, chrome_lang) ||
      !TranslatePrefs::CanTranslate(prefs, page_lang, entry->url())) {
    return;
  }
  if (TranslatePrefs::ShouldAutoTranslate(prefs, page_lang, chrome_lang)) {
    // The user has previously select "always translate" for this language.
    tab->TranslatePage(page_lang, chrome_lang);
    return;
  }

  // Prompts the user if he/she wants the page translated.
  tab->AddInfoBar(new BeforeTranslateInfoBarDelegate(tab, prefs,
                                                     entry->url(),
                                                     page_lang, chrome_lang));
}

PrefService* TranslateManager::GetPrefService(TabContents* tab) {
  PrefService* prefs = NULL;
  if (tab->profile())
    prefs = tab->profile()->GetPrefs();
  if (prefs)
    return prefs;

  return g_browser_process->local_state();
}
<commit_msg>The "after infobar" could be sticky in some cases. Make sure we always remove it before showing a new "before translate" infobar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/translate/translate_manager.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/translation_service.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobars_delegates.h"
#include "chrome/browser/translate/translate_prefs.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_service.h"

TranslateManager::~TranslateManager() {
}

void TranslateManager::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::NAV_ENTRY_COMMITTED: {
      // We have navigated to a new page.
      NavigationController* controller =
          Source<NavigationController>(source).ptr();
      NavigationEntry* entry = controller->GetActiveEntry();
      if (!entry->language().empty()) {
        // The language for that page is known (it must be a back/forward
        // navigation to a page we already visited).
        InitiateTranslation(controller->tab_contents(), entry->language());
      }
      break;
    }
    case NotificationType::TAB_LANGUAGE_DETERMINED: {
      TabContents* tab = Source<TabContents>(source).ptr();
      std::string language = *(Details<std::string>(details).ptr());
      InitiateTranslation(tab, language);
      break;
    }
    case NotificationType::PAGE_TRANSLATED: {
      TabContents* tab = Source<TabContents>(source).ptr();
      std::pair<std::string, std::string>* language_pair =
          (Details<std::pair<std::string, std::string> >(details).ptr());
      PrefService* prefs = GetPrefService(tab);
      tab->AddInfoBar(new AfterTranslateInfoBarDelegate(tab, prefs,
                                                        language_pair->first,
                                                        language_pair->second));
      break;
    }
    default:
      NOTREACHED();
  }
}

TranslateManager::TranslateManager() {
  if (!TranslationService::IsTranslationEnabled())
    return;

  notification_registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                              NotificationService::AllSources());
  notification_registrar_.Add(this, NotificationType::TAB_LANGUAGE_DETERMINED,
                              NotificationService::AllSources());
  notification_registrar_.Add(this, NotificationType::PAGE_TRANSLATED,
                              NotificationService::AllSources());
}

void TranslateManager::InitiateTranslation(TabContents* tab,
                                           const std::string& page_lang) {
  PrefService* prefs = GetPrefService(tab);
  NavigationEntry* entry = tab->controller().GetActiveEntry();
  if (!entry) {
    NOTREACHED();
    return;
  }

  std::string chrome_lang = g_browser_process->GetApplicationLocale();

  // We don't want to translate:
  // - any Chrome specific page (New Tab Page, Download, History... pages).
  // - similar languages (ex: en-US to en).
  // - any user black-listed URLs or user selected language combination.
  if (entry->url().SchemeIs("chrome") || page_lang == chrome_lang ||
      !TranslationService::ShouldTranslatePage(page_lang, chrome_lang) ||
      !TranslatePrefs::CanTranslate(prefs, page_lang, entry->url())) {
    return;
  }
  if (TranslatePrefs::ShouldAutoTranslate(prefs, page_lang, chrome_lang)) {
    // The user has previously select "always translate" for this language.
    tab->TranslatePage(page_lang, chrome_lang);
    return;
  }

  // If we already have an "after translate" infobar, it sometimes might be
  // sticky when running in frames.  So we need to proactively remove any
  // translate related infobars as they would prevent any new infobar from
  // showing. (As TabContents will not add an infobar if there is already one
  // showing equal to the one being added.)
  for (int i = 0; i < tab->infobar_delegate_count(); ++i) {
    InfoBarDelegate* info_bar = tab->GetInfoBarDelegateAt(i);
    if (info_bar->AsTranslateInfoBarDelegate())
      tab->RemoveInfoBar(info_bar);
  }

  // Prompts the user if he/she wants the page translated.
  tab->AddInfoBar(new BeforeTranslateInfoBarDelegate(tab, prefs,
                                                     entry->url(),
                                                     page_lang, chrome_lang));
}

PrefService* TranslateManager::GetPrefService(TabContents* tab) {
  PrefService* prefs = NULL;
  if (tab->profile())
    prefs = tab->profile()->GetPrefs();
  if (prefs)
    return prefs;

  return g_browser_process->local_state();
}
<|endoftext|>


<commit_before>//====================================================================
#include "AliCentraldNdetaTask.h"
#include <TMath.h>
#include <TH2D.h>
#include <TH1D.h>
#include <THStack.h>
#include <TList.h>
#include <AliAnalysisManager.h>
#include <AliAODEvent.h>
#include <AliAODHandler.h>
#include <AliAODInputHandler.h>
#include "AliForwardUtil.h"
#include "AliAODForwardMult.h"
#include "AliAODCentralMult.h"

ClassDef(AliCentraldNdetaTask)
#ifdef DOXY_INPUT
;
#endif

//____________________________________________________________________
AliCentraldNdetaTask::AliCentraldNdetaTask(const char*)
  : AliBasedNdetaTask("Central")
{
  fSymmetrice = false;
  fCorrEmpty  = false;
}

//____________________________________________________________________
TH2D*
AliCentraldNdetaTask::GetHistogram(const AliAODEvent* aod, Bool_t mc)
{
  // Get objects from the event structure
  TObject* obj = 0;
  if (mc) obj = aod->FindListObject("CentralClustersMC");
  else    obj = aod->FindListObject("CentralClusters");

  // We should have a central object at least
  if (!obj) {
    if (!mc) AliWarning("No Central object found AOD");
    return 0;
  }

  // Cast to good types
  AliAODCentralMult* central   = static_cast<AliAODCentralMult*>(obj);

  return &(central->GetHistogram());
}

//
// EOF
//
<commit_msg>Fixed problem<commit_after>//====================================================================
#include "AliCentraldNdetaTask.h"
#include <TMath.h>
#include <TH2D.h>
#include <TH1D.h>
#include <THStack.h>
#include <TList.h>
#include <AliAnalysisManager.h>
#include <AliAODEvent.h>
#include <AliAODHandler.h>
#include <AliAODInputHandler.h>
#include "AliForwardUtil.h"
#include "AliAODForwardMult.h"
#include "AliAODCentralMult.h"

ClassImp(AliCentraldNdetaTask)
#ifdef DOXY_INPUT
;
#endif

//____________________________________________________________________
AliCentraldNdetaTask::AliCentraldNdetaTask(const char*)
  : AliBasedNdetaTask("Central")
{
  fSymmetrice = false;
  fCorrEmpty  = false;
}

//____________________________________________________________________
TH2D*
AliCentraldNdetaTask::GetHistogram(const AliAODEvent* aod, Bool_t mc)
{
  // Get objects from the event structure
  TObject* obj = 0;
  if (mc) obj = aod->FindListObject("CentralClustersMC");
  else    obj = aod->FindListObject("CentralClusters");

  // We should have a central object at least
  if (!obj) {
    if (!mc) AliWarning("No Central object found AOD");
    return 0;
  }

  // Cast to good types
  AliAODCentralMult* central   = static_cast<AliAODCentralMult*>(obj);

  return &(central->GetHistogram());
}

//
// EOF
//
<|endoftext|>


<commit_before>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode)
{
  // Check if user has a valid token, otherwise make one. This has limitations.
  // One can always follow the standard procedure of calling alien-token-init then
  //   source /tmp/gclient_env_$UID in the current shell.
  if (!AliAnalysisGrid::CreateToken()) return NULL;
  AliAnalysisAlien *plugin = new AliAnalysisAlien();

  // Overwrite all generated files, datasets and output results from a previous session
  plugin->SetOverwriteMode();
  // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
  // plugin->SetRunMode("full");  // VERY IMPORTANT - DECRIBED BELOW
  // plugin->SetRunMode("test");  // VERY IMPORTANT - DECRIBED BELOW
  plugin->SetRunMode(pluginRunMode);  // VERY IMPORTANT - DECRIBED BELOW

  // Set versions of used packages
  plugin->SetAPIVersion("V1.1x");
  plugin->SetROOTVersion("v5-27-05");
  plugin->SetAliROOTVersion("v4-20-08-AN");
  // Declare input data to be processed.

  // Method 1: Create automatically XML collections using alien 'find' command.
  // Define production directory LFN
  //   plugin->SetGridDataDir("/alice/sim/LHC10a18");
  // Set data search pattern
  //   plugin->SetDataPattern("*ESDs.root");  // simulated, tags not used
  //   plugin->SetDataPattern("*ESDs/pass4/*ESDs.root"); // real data check reco pass and data base directory
  //   plugin->SetRunPrefix("000");   // real data
  //   plugin->SetDataPattern("*tag.root");  // Use ESD tags (same applies for AOD's)
  // ...then add run numbers to be considered
  //   plugin->AddRunNumber(125020);    // simulated
  //   plugin->AddRunNumber(104065);  // real data

  // Method 2: Declare existing data files (raw collections, xml collections, root file)
  // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
  // XML collections added via this method can be combined with the first method if
  // the content is compatible (using or not tags)
  plugin->AddDataFile("tag.xml");
  // file generated with:  find -x tag /alice/sim/LHC10d1/117222/* AliESDs.root > tag.xml

  // Define alien work directory where all files will be copied. Relative to alien $HOME.
  plugin->SetGridWorkingDir(outputDir.Data());
  // Declare alien output directory. Relative to working directory.
  plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output
  // Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED
  // using ACLiC on the worker nodes.
  plugin->SetAnalysisSource("AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx");
  // Declare all libraries (other than the default ones for the framework. These will be
  // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
  plugin->SetAdditionalLibs("AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx");

  // No need for output file names. Procedure is automatic. <-- not true
  plugin->SetDefaultOutputs(kFALSE);
  plugin->SetOutputFiles(outputName.Data());
  // No need define the files to be archived. Note that this is handled automatically by the plugin.
  //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
  // Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique !
  plugin->SetAnalysisMacro("DavidEtAnalysis.C");
  // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore). The optimum for an analysis
  // is correlated with the run time - count few hours TTL per job, not minutes !
  plugin->SetSplitMaxInputFileNumber(100);
  // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
  plugin->SetMaxInitFailed(5);
  // Optionally resubmit threshold.
  plugin->SetMasterResubmitThreshold(90);
  // Optionally set time to live (default 30000 sec)
  plugin->SetTTL(20000);
  // Optionally set input format (default xml-single)
  plugin->SetInputFormat("xml-single");
  // Optionally modify the name of the generated JDL (default analysis.jdl)
  plugin->SetJDLName("TaskEt.jdl");
  // Optionally modify job price (default 1)
  plugin->SetPrice(1);
  // Optionally modify split mode (default 'se')
  plugin->SetSplitMode("se");
  return plugin;
}
<commit_msg>add missing source file for running with plugin<commit_after>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode)
{
  // Check if user has a valid token, otherwise make one. This has limitations.
  // One can always follow the standard procedure of calling alien-token-init then
  //   source /tmp/gclient_env_$UID in the current shell.
  if (!AliAnalysisGrid::CreateToken()) return NULL;
  AliAnalysisAlien *plugin = new AliAnalysisAlien();

  // Overwrite all generated files, datasets and output results from a previous session
  plugin->SetOverwriteMode();
  // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
  // plugin->SetRunMode("full");  // VERY IMPORTANT - DECRIBED BELOW
  // plugin->SetRunMode("test");  // VERY IMPORTANT - DECRIBED BELOW
  plugin->SetRunMode(pluginRunMode);  // VERY IMPORTANT - DECRIBED BELOW

  // Set versions of used packages
  plugin->SetAPIVersion("V1.1x");
  plugin->SetROOTVersion("v5-27-05");
  plugin->SetAliROOTVersion("v4-20-08-AN");
  // Declare input data to be processed.

  // Method 1: Create automatically XML collections using alien 'find' command.
  // Define production directory LFN
  //   plugin->SetGridDataDir("/alice/sim/LHC10a18");
  // Set data search pattern
  //   plugin->SetDataPattern("*ESDs.root");  // simulated, tags not used
  //   plugin->SetDataPattern("*ESDs/pass4/*ESDs.root"); // real data check reco pass and data base directory
  //   plugin->SetRunPrefix("000");   // real data
  //   plugin->SetDataPattern("*tag.root");  // Use ESD tags (same applies for AOD's)
  // ...then add run numbers to be considered
  //   plugin->AddRunNumber(125020);    // simulated
  //   plugin->AddRunNumber(104065);  // real data

  // Method 2: Declare existing data files (raw collections, xml collections, root file)
  // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
  // XML collections added via this method can be combined with the first method if
  // the content is compatible (using or not tags)
  plugin->AddDataFile("tag.xml");
  //  plugin->AddDataFile("wn.xml"); // test
  // file generated with:  find -x tag /alice/sim/LHC10d1/117222/* AliESDs.root > tag.xml

  // Define alien work directory where all files will be copied. Relative to alien $HOME.
  plugin->SetGridWorkingDir(outputDir.Data());
  // Declare alien output directory. Relative to working directory.
  plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output
  // Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED
  // using ACLiC on the worker nodes.
  plugin->SetAnalysisSource("AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx");
  // Declare all libraries (other than the default ones for the framework. These will be
  // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
  plugin->SetAdditionalLibs("AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx");

  // No need for output file names. Procedure is automatic. <-- not true
  plugin->SetDefaultOutputs(kFALSE);
  plugin->SetOutputFiles(outputName.Data());
  // No need define the files to be archived. Note that this is handled automatically by the plugin.
  //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
  // Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique !
  plugin->SetAnalysisMacro("DavidEtAnalysis.C");
  // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore). The optimum for an analysis
  // is correlated with the run time - count few hours TTL per job, not minutes !
  plugin->SetSplitMaxInputFileNumber(100);
  // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
  plugin->SetMaxInitFailed(5);
  // Optionally resubmit threshold.
  plugin->SetMasterResubmitThreshold(90);
  // Optionally set time to live (default 30000 sec)
  plugin->SetTTL(20000);
  // Optionally set input format (default xml-single)
  plugin->SetInputFormat("xml-single");
  // Optionally modify the name of the generated JDL (default analysis.jdl)
  plugin->SetJDLName("TaskEt.jdl");
  // Optionally modify job price (default 1)
  plugin->SetPrice(1);
  // Optionally modify split mode (default 'se')
  plugin->SetSplitMode("se");
  return plugin;
}
<|endoftext|>


<commit_before>#include <deal.II/base/polynomials_bernstein.h>

#include <boost/math/special_functions/binomial.hpp>

#include <vector>

DEAL_II_NAMESPACE_OPEN

namespace Binomial
{
  template <typename number>
  std::vector<number>
  get_bernstein_coefficients (
    const unsigned int k, const unsigned int n)
  {
    Assert(n>0, ExcMessage("Bernstein polynomial needs to be of degree > 0."));
    AssertIndexRange(k, n+1);
    std::vector<number> coeff(n + 1, number(0.0));
    for (unsigned int i = k; i < n + 1; ++i)
      {
        coeff[i] = pow(number(-1), number(i - k))
                   * boost::math::binomial_coefficient<number>(n, i)
                   * boost::math::binomial_coefficient<number>(i, k);
      }
    return coeff;
  }
}

template <typename number>
PolynomialsBernstein<number>:: PolynomialsBernstein (
  const unsigned int index, const unsigned int degree)
  :
  Polynomials::Polynomial<number>(
    Binomial::get_bernstein_coefficients<number>(index, degree))
{
}

#include "polynomials_bernstein.inst"

DEAL_II_NAMESPACE_CLOSE
<commit_msg>Compute powers of -1 by checking exponent parity.<commit_after>#include <deal.II/base/polynomials_bernstein.h>

#include <boost/math/special_functions/binomial.hpp>

#include <vector>

DEAL_II_NAMESPACE_OPEN

namespace Binomial
{
  template <typename number>
  std::vector<number>
  get_bernstein_coefficients (
    const unsigned int k, const unsigned int n)
  {
    Assert(n>0, ExcMessage("Bernstein polynomial needs to be of degree > 0."));
    AssertIndexRange(k, n+1);
    std::vector<number> coeff(n + 1, number(0.0));
    for (unsigned int i = k; i < n + 1; ++i)
      {
        coeff[i] = ((i - k) % 2 == 0 ? 1 : -1)
                   * boost::math::binomial_coefficient<number>(n, i)
                   * boost::math::binomial_coefficient<number>(i, k);
      }
    return coeff;
  }
}

template <typename number>
PolynomialsBernstein<number>:: PolynomialsBernstein (
  const unsigned int index, const unsigned int degree)
  :
  Polynomials::Polynomial<number>(
    Binomial::get_bernstein_coefficients<number>(index, degree))
{
}

#include "polynomials_bernstein.inst"

DEAL_II_NAMESPACE_CLOSE
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "QueueWorkingModule.h"

//--- project modules used -----------------------------------------------------

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "Server.h"
#include "AppLog.h"
#include "StringStream.h"

//--- c-modules used -----------------------------------------------------------

//---- QueueWorkingModule ---------------------------------------------------------------
QueueWorkingModule::QueueWorkingModule(const char *name)
	: WDModule(name)
	, fpQueue(NULL)
	, fpContext(NULL)
	, fContextLock("QueueWorkingModuleContextLock")
	, fFailedPutbackMessages(Storage::Global())
	, fAlive(0UL)
{
	StartTrace(QueueWorkingModule.QueueWorkingModule);
}

QueueWorkingModule::~QueueWorkingModule()
{
}

void QueueWorkingModule::LogError(String strMessage)
{
	StartTrace(QueueWorkingModule.LogError);
	SYSERROR(strMessage);
	Log(strMessage, fErrorLogName);
}

void QueueWorkingModule::LogWarning(String strMessage)
{
	StartTrace(QueueWorkingModule.LogWarning);
	SYSWARNING(strMessage);
	Log(strMessage, fWarningLogName);
}

void QueueWorkingModule::LogInfo(String strMessage)
{
	StartTrace(QueueWorkingModule.LogInfo);
	Log(strMessage, fInfoLogName);
}

void QueueWorkingModule::Log(String strMessage, const char *channel)
{
	StartTrace(QueueWorkingModule.Log);
	Trace(strMessage);
	if ( IsAlive() && fpContext ) {
		MutexEntry me(fContextLock);
		me.Use();
		if ( IsAlive() && fpContext ) {
			fpContext->GetTmpStore()["LogMessage"] = strMessage;
			AppLogModule::Log(*fpContext, channel);
		}
	}
}

void QueueWorkingModule::Log(Anything &anyStatus, const char *channel)
{
	StartTrace(QueueWorkingModule.Log);
	TraceAny(anyStatus, "content to log");
	if ( IsAlive() && fpContext ) {
		MutexEntry me(fContextLock);
		me.Use();
		if ( IsAlive() && fpContext ) {
			fpContext->GetTmpStore()["QueueWorkingStatus"] = anyStatus;
			AppLogModule::Log(*fpContext, channel);
		}
	}
}

bool QueueWorkingModule::Init(const ROAnything config)
{
	StartTrace(QueueWorkingModule.Init);
	SubTraceAny(FullConfig, config, "Config: ");
	ROAnything roaConfig;
	if ( config.LookupPath(roaConfig, fName) ) {
		fConfig = roaConfig.DeepClone();
		TraceAny(fConfig, "Module config");
		fErrorLogName = GetNamedConfig("Logging")["ErrorChannel"].AsCharPtr("ErrorLog");
		fWarningLogName = GetNamedConfig("Logging")["WarningChannel"].AsCharPtr("WarningLog");
		fInfoLogName = GetNamedConfig("Logging")["InfoChannel"].AsCharPtr("AccessLog");
		const char *pServerName = GetNamedConfig("Logging")["Servername"].AsCharPtr("Server");
		Server *pServer = Server::FindServer(pServerName);
		Anything dummy;
		fpContext = new Context(fConfig, dummy, pServer, 0, 0);
		IntInitQueue(GetConfig());
		fAlive = 0xf007f007;
		return true;
	}
	return false;
}

bool QueueWorkingModule::Finis()
{
	StartTrace(QueueWorkingModule.Finis);

	SetDead();

	Anything anyStat;
	if ( GetQueueStatistics(anyStat) ) {
		StringStream aStream;
		aStream << "Statistics for [" << GetName() << "]\n";
		anyStat.PrintOn(aStream, true) << flush;
		SysLog::WriteToStderr(aStream.str());
	}

	// delete Queue, also wakes up blocked threads, threads MUST be in termination sequence!!
	IntCleanupQueue();

	{
		MutexEntry me(fContextLock);
		me.Use();
		delete fpContext;
		fpContext = NULL;
	}

	return true;
}

bool QueueWorkingModule::ResetInit(const ROAnything config)
{
	StartTrace(QueueWorkingModule.ResetInit);
	// calls Init
	return WDModule::ResetInit(config);
}

bool QueueWorkingModule::ResetFinis(const ROAnything config)
{
	StartTrace(QueueWorkingModule.ResetFinis);
	// calls Finis
	return WDModule::ResetFinis(config);
}

void QueueWorkingModule::IntInitQueue(const ROAnything roaConfig)
{
	StartTrace(QueueWorkingModule.IntInitQueue);
	long lQueueSize = roaConfig["QueueSize"].AsLong(100L);
	fpQueue = new Queue(GetName(), lQueueSize);
	fFailedPutbackMessages = Anything();
}

void QueueWorkingModule::IntCleanupQueue()
{
	StartTrace(QueueWorkingModule.IntCleanupQueue);
	// we could do something here to persist the content of the queue and the putback message buffer
	delete fpQueue;
	fpQueue = NULL;
	fFailedPutbackMessages = Anything();
}

Queue::StatusCode QueueWorkingModule::PutElement(Anything &anyELement, bool bTryLock)
{
	StartTrace(QueueWorkingModule.PutElement);
	Queue::StatusCode eRet = Queue::eDead;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		eRet = fpQueue->Put(anyELement, bTryLock);
		if ( eRet != Queue::eSuccess ) {
			SYSWARNING("Queue->Put failed, Queue::StatusCode:" << eRet << " !");
		}
	}
	return eRet;
}

ROAnything QueueWorkingModule::GetConfig()
{
	StartTrace(QueueWorkingModule.GetConfig);
	return ((ROAnything)fConfig);
}

ROAnything QueueWorkingModule::GetNamedConfig(const char *name)
{
	StartTrace(QueueWorkingModule.GetNamedConfig);
	return ((ROAnything)fConfig)[name];
}

Queue::StatusCode QueueWorkingModule::GetElement(Anything &anyValues, bool bTryLock)
{
	StartTrace(QueueWorkingModule.GetElement);
	Queue::StatusCode eRet = Queue::eDead;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		Trace("Queue still alive");
		// try to get a failed message first
		if ( fFailedPutbackMessages.GetSize() > 0 ) {
			Trace("getting failed message 1 of " << fFailedPutbackMessages.GetSize() );
			anyValues = fFailedPutbackMessages[0L];
			fFailedPutbackMessages.Remove(0L);
			eRet = Queue::eSuccess;
		} else {
			// Default is blocking get to save cpu time
			eRet = fpQueue->Get(anyValues, bTryLock);
			if ( ( eRet != Queue::eSuccess ) && ( eRet != Queue::eEmpty ) ) {
				SYSWARNING("Queue->Get failed, Queue::StatusCode:" << eRet << " !");
			}
		}
	}
	return eRet;
}

void QueueWorkingModule::PutBackElement(Anything &anyValues)
{
	StartTrace(QueueWorkingModule.PutBackElement);
	// put message back to the queue (Appends!) if possible
	// take care not to lock ourselves up here, thus we MUST use a trylock here!
	Queue::StatusCode eRet = PutElement(anyValues, true);
	if ( eRet != Queue::eSuccess && ( eRet & Queue::eFull ) ) {
		// no more room in Queue, need to store this message internally for later put back
		fFailedPutbackMessages.Append(anyValues);
	}
}

long QueueWorkingModule::FlushQueue(Anything &anyElements)
{
	StartTrace(QueueWorkingModule.FlushQueue);
	long lElements = 0L;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		fpQueue->EmptyQueue(anyElements);
		lElements = anyElements.GetSize();
		LogInfo(String(GetName()) << ": flushed " << lElements << " elements");
	}
	return lElements;
}

bool QueueWorkingModule::GetQueueStatistics(Anything &anyStat)
{
	StartTrace(QueueWorkingModule.GetQueueStatistics);
	if ( fpQueue ) {
		fpQueue->GetStatistics(anyStat);
		return true;
	}
	return false;
}
<commit_msg>added newling<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "QueueWorkingModule.h"

//--- project modules used -----------------------------------------------------

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "Server.h"
#include "AppLog.h"
#include "StringStream.h"

//--- c-modules used -----------------------------------------------------------

//---- QueueWorkingModule ---------------------------------------------------------------
QueueWorkingModule::QueueWorkingModule(const char *name)
	: WDModule(name)
	, fpQueue(NULL)
	, fpContext(NULL)
	, fContextLock("QueueWorkingModuleContextLock")
	, fFailedPutbackMessages(Storage::Global())
	, fAlive(0UL)
{
	StartTrace(QueueWorkingModule.QueueWorkingModule);
}

QueueWorkingModule::~QueueWorkingModule()
{
}

void QueueWorkingModule::LogError(String strMessage)
{
	StartTrace(QueueWorkingModule.LogError);
	SYSERROR(strMessage);
	Log(strMessage, fErrorLogName);
}

void QueueWorkingModule::LogWarning(String strMessage)
{
	StartTrace(QueueWorkingModule.LogWarning);
	SYSWARNING(strMessage);
	Log(strMessage, fWarningLogName);
}

void QueueWorkingModule::LogInfo(String strMessage)
{
	StartTrace(QueueWorkingModule.LogInfo);
	Log(strMessage, fInfoLogName);
}

void QueueWorkingModule::Log(String strMessage, const char *channel)
{
	StartTrace(QueueWorkingModule.Log);
	Trace(strMessage);
	if ( IsAlive() && fpContext ) {
		MutexEntry me(fContextLock);
		me.Use();
		if ( IsAlive() && fpContext ) {
			fpContext->GetTmpStore()["LogMessage"] = strMessage;
			AppLogModule::Log(*fpContext, channel);
		}
	}
}

void QueueWorkingModule::Log(Anything &anyStatus, const char *channel)
{
	StartTrace(QueueWorkingModule.Log);
	TraceAny(anyStatus, "content to log");
	if ( IsAlive() && fpContext ) {
		MutexEntry me(fContextLock);
		me.Use();
		if ( IsAlive() && fpContext ) {
			fpContext->GetTmpStore()["QueueWorkingStatus"] = anyStatus;
			AppLogModule::Log(*fpContext, channel);
		}
	}
}

bool QueueWorkingModule::Init(const ROAnything config)
{
	StartTrace(QueueWorkingModule.Init);
	SubTraceAny(FullConfig, config, "Config: ");
	ROAnything roaConfig;
	if ( config.LookupPath(roaConfig, fName) ) {
		fConfig = roaConfig.DeepClone();
		TraceAny(fConfig, "Module config");
		fErrorLogName = GetNamedConfig("Logging")["ErrorChannel"].AsCharPtr("ErrorLog");
		fWarningLogName = GetNamedConfig("Logging")["WarningChannel"].AsCharPtr("WarningLog");
		fInfoLogName = GetNamedConfig("Logging")["InfoChannel"].AsCharPtr("AccessLog");
		const char *pServerName = GetNamedConfig("Logging")["Servername"].AsCharPtr("Server");
		Server *pServer = Server::FindServer(pServerName);
		Anything dummy;
		fpContext = new Context(fConfig, dummy, pServer, 0, 0);
		IntInitQueue(GetConfig());
		fAlive = 0xf007f007;
		return true;
	}
	return false;
}

bool QueueWorkingModule::Finis()
{
	StartTrace(QueueWorkingModule.Finis);

	SetDead();

	Anything anyStat;
	if ( GetQueueStatistics(anyStat) ) {
		StringStream aStream;
		aStream << "Statistics for [" << GetName() << "]\n";
		anyStat.PrintOn(aStream, true) << "\n" << flush;
		SysLog::WriteToStderr(aStream.str());
	}

	// delete Queue, also wakes up blocked threads, threads MUST be in termination sequence!!
	IntCleanupQueue();

	{
		MutexEntry me(fContextLock);
		me.Use();
		delete fpContext;
		fpContext = NULL;
	}

	return true;
}

bool QueueWorkingModule::ResetInit(const ROAnything config)
{
	StartTrace(QueueWorkingModule.ResetInit);
	// calls Init
	return WDModule::ResetInit(config);
}

bool QueueWorkingModule::ResetFinis(const ROAnything config)
{
	StartTrace(QueueWorkingModule.ResetFinis);
	// calls Finis
	return WDModule::ResetFinis(config);
}

void QueueWorkingModule::IntInitQueue(const ROAnything roaConfig)
{
	StartTrace(QueueWorkingModule.IntInitQueue);
	long lQueueSize = roaConfig["QueueSize"].AsLong(100L);
	fpQueue = new Queue(GetName(), lQueueSize);
	fFailedPutbackMessages = Anything();
}

void QueueWorkingModule::IntCleanupQueue()
{
	StartTrace(QueueWorkingModule.IntCleanupQueue);
	// we could do something here to persist the content of the queue and the putback message buffer
	delete fpQueue;
	fpQueue = NULL;
	fFailedPutbackMessages = Anything();
}

Queue::StatusCode QueueWorkingModule::PutElement(Anything &anyELement, bool bTryLock)
{
	StartTrace(QueueWorkingModule.PutElement);
	Queue::StatusCode eRet = Queue::eDead;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		eRet = fpQueue->Put(anyELement, bTryLock);
		if ( eRet != Queue::eSuccess ) {
			SYSWARNING("Queue->Put failed, Queue::StatusCode:" << eRet << " !");
		}
	}
	return eRet;
}

ROAnything QueueWorkingModule::GetConfig()
{
	StartTrace(QueueWorkingModule.GetConfig);
	return ((ROAnything)fConfig);
}

ROAnything QueueWorkingModule::GetNamedConfig(const char *name)
{
	StartTrace(QueueWorkingModule.GetNamedConfig);
	return ((ROAnything)fConfig)[name];
}

Queue::StatusCode QueueWorkingModule::GetElement(Anything &anyValues, bool bTryLock)
{
	StartTrace(QueueWorkingModule.GetElement);
	Queue::StatusCode eRet = Queue::eDead;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		Trace("Queue still alive");
		// try to get a failed message first
		if ( fFailedPutbackMessages.GetSize() > 0 ) {
			Trace("getting failed message 1 of " << fFailedPutbackMessages.GetSize() );
			anyValues = fFailedPutbackMessages[0L];
			fFailedPutbackMessages.Remove(0L);
			eRet = Queue::eSuccess;
		} else {
			// Default is blocking get to save cpu time
			eRet = fpQueue->Get(anyValues, bTryLock);
			if ( ( eRet != Queue::eSuccess ) && ( eRet != Queue::eEmpty ) ) {
				SYSWARNING("Queue->Get failed, Queue::StatusCode:" << eRet << " !");
			}
		}
	}
	return eRet;
}

void QueueWorkingModule::PutBackElement(Anything &anyValues)
{
	StartTrace(QueueWorkingModule.PutBackElement);
	// put message back to the queue (Appends!) if possible
	// take care not to lock ourselves up here, thus we MUST use a trylock here!
	Queue::StatusCode eRet = PutElement(anyValues, true);
	if ( eRet != Queue::eSuccess && ( eRet & Queue::eFull ) ) {
		// no more room in Queue, need to store this message internally for later put back
		fFailedPutbackMessages.Append(anyValues);
	}
}

long QueueWorkingModule::FlushQueue(Anything &anyElements)
{
	StartTrace(QueueWorkingModule.FlushQueue);
	long lElements = 0L;
	if ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {
		fpQueue->EmptyQueue(anyElements);
		lElements = anyElements.GetSize();
		LogInfo(String(GetName()) << ": flushed " << lElements << " elements");
	}
	return lElements;
}

bool QueueWorkingModule::GetQueueStatistics(Anything &anyStat)
{
	StartTrace(QueueWorkingModule.GetQueueStatistics);
	if ( fpQueue ) {
		fpQueue->GetStatistics(anyStat);
		return true;
	}
	return false;
}
<|endoftext|>


<commit_before>#include <iostream>

class Point
{
    public:

        Point();

};

<commit_msg>Created accessor name to match declaration.closes #79<commit_after>#include <iostream>

class Point
{
    public:

        Point();
        Point(double , double);
        double x();
        void set_x(double);
        double y();
        void set_y(double);

    private:
        double m_x;
        double m_y;

};

void Point::set_x(double x)
{
    return m_x;
}
void Point::set_y(double y)
{
    return m_y;

}
Point::Point()
{
    set_x(0);
    set_y(0);

}

<|endoftext|>