<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DicomSeriesReadImageWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginLatex
//
//  This example illustrates how to read a DICOM series into a volume
//  and then save this volume in another file format.
//
//  Software Guide : EndLatex

#include "itkImageSeriesReader.h"
#include "itkDICOMImageIO2.h"
#include "itkDICOMSeriesFileNames.h"
#include "itkImageFileWriter.h"

int main( int argc, char* argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " DicomDirectory  outputFileName  [seriesName]" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<unsigned short,3>            ImageType;
  typedef itk::ImageSeriesReader< ImageType >     ReaderType;

  itk::DICOMImageIO2::Pointer dicomIO = itk::DICOMImageIO2::New();

  // Get the DICOM filenames from the directory
  itk::DICOMSeriesFileNames::Pointer nameGenerator = itk::DICOMSeriesFileNames::New();
  nameGenerator->SetDirectory( argv[1] );

  typedef std::vector<std::string> seriesIdContainer;
  const seriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs();

  seriesIdContainer::const_iterator seriesItr = seriesUID.begin();
  seriesIdContainer::const_iterator seriesEnd = seriesUID.end();

  std::cout << std::endl << "The directory: " << std::endl;
  std::cout << std::endl << argv[1] << std::endl << std::endl;
  std::cout << "Contains the following DICOM Series: ";
  std::cout << std::endl << std::endl;

  while( seriesItr != seriesEnd )
    {
    std::cout << seriesItr->c_str() << std::endl;
    seriesItr++;
    }

  std::cout << std::endl << std::endl;
  std::cout << "Now reading series: " << std::endl << std::endl;

  typedef std::vector<std::string> fileNamesContainer;
  fileNamesContainer fileNames;

  if( argc < 4 ) // If no optional third argument
    {
    std::cout << seriesUID.begin()->c_str() << std::endl;
    fileNames = nameGenerator->GetFileNames();
    }
  else
    {
    std::cout << argv[3] << std::endl;
    fileNames = nameGenerator->GetFileNames( argv[3] );
    }
  std::cout << std::endl << std::endl;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( fileNames );
  reader->SetImageIO( dicomIO );

  try
    {
    reader->Update();
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  std::cout  << "Writing the image as " << std::endl << std::endl;
  std::cout  << argv[2] << std::endl << std::endl;

  writer->SetFileName( argv[2] );

  writer->SetInput( reader->GetOutput() );

  try
    {
    writer->Update();
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<commit_msg>ERR: missing catch of bad directory name.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DicomSeriesReadImageWrite.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//  Software Guide : BeginLatex
//
//  This example illustrates how to read a DICOM series into a volume
//  and then save this volume in another file format.
//
//  Software Guide : EndLatex

#include "itkImageSeriesReader.h"
#include "itkDICOMImageIO2.h"
#include "itkDICOMSeriesFileNames.h"
#include "itkImageFileWriter.h"

int main( int argc, char* argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " DicomDirectory  outputFileName  [seriesName]" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<unsigned short,3>            ImageType;
  typedef itk::ImageSeriesReader< ImageType >     ReaderType;

  itk::DICOMImageIO2::Pointer dicomIO = itk::DICOMImageIO2::New();

  // Get the DICOM filenames from the directory
  itk::DICOMSeriesFileNames::Pointer nameGenerator = itk::DICOMSeriesFileNames::New();
  nameGenerator->SetDirectory( argv[1] );

  try
    {
    typedef std::vector<std::string> seriesIdContainer;
    const seriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs();

    seriesIdContainer::const_iterator seriesItr = seriesUID.begin();
    seriesIdContainer::const_iterator seriesEnd = seriesUID.end();

    std::cout << std::endl << "The directory: " << std::endl;
    std::cout << std::endl << argv[1] << std::endl << std::endl;
    std::cout << "Contains the following DICOM Series: ";
    std::cout << std::endl << std::endl;

    while( seriesItr != seriesEnd )
      {
      std::cout << seriesItr->c_str() << std::endl;
      seriesItr++;
      }

    std::cout << std::endl << std::endl;
    std::cout << "Now reading series: " << std::endl << std::endl;

    typedef std::vector<std::string> fileNamesContainer;
    fileNamesContainer fileNames;

    if( argc < 4 ) // If no optional third argument
      {
      std::cout << seriesUID.begin()->c_str() << std::endl;
      fileNames = nameGenerator->GetFileNames();
      }
    else
      {
      std::cout << argv[3] << std::endl;
      fileNames = nameGenerator->GetFileNames( argv[3] );
      }
    std::cout << std::endl << std::endl;

    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileNames( fileNames );
    reader->SetImageIO( dicomIO );

    try
      {
      reader->Update();
      }
    catch (itk::ExceptionObject &ex)
      {
      std::cout << ex << std::endl;
      return EXIT_FAILURE;
      }

    typedef itk::ImageFileWriter< ImageType > WriterType;
    WriterType::Pointer writer = WriterType::New();

    std::cout  << "Writing the image as " << std::endl << std::endl;
    std::cout  << argv[2] << std::endl << std::endl;

    writer->SetFileName( argv[2] );

    writer->SetInput( reader->GetOutput() );

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject &ex)
      {
      std::cout << ex;
      return EXIT_FAILURE;
      }
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <graphene/witness/witness.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/witness_object.hpp>

#include <graphene/utilities/key_conversion.hpp>

#include <fc/smart_ref_impl.hpp>
#include <fc/thread/thread.hpp>

#include <iostream>

using namespace graphene::witness_plugin;
using std::string;
using std::vector;

namespace bpo = boost::program_options;

void new_chain_banner( const graphene::chain::database& db )
{
   std::cerr << "\n"
      "********************************\n"
      "*                              *\n"
      "*   ------- NEW CHAIN ------   *\n"
      "*   - Welcome to Graphene! -   *\n"
      "*   ------------------------   *\n"
      "*                              *\n"
      "********************************\n"
      "\n";
   if( db.get_slot_at_time( fc::time_point::now() ) > 200 )
   {
      std::cerr << "Your genesis seems to have an old timestamp\n"
         "Please consider using the --genesis-timestamp option to give your genesis a recent timestamp\n"
         "\n"
         ;
   }
   return;
}

void witness_plugin::plugin_set_program_options(
   boost::program_options::options_description& command_line_options,
   boost::program_options::options_description& config_file_options)
{
   auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan")));
   string witness_id_example = fc::json::to_string(chain::witness_id_type(5));
   command_line_options.add_options()
         ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.")
         ("required-participation", bpo::bool_switch()->notifier([this](int e){_required_witness_participation = uint32_t(e*GRAPHENE_1_PERCENT);}), "Percent of witnesses (0-99) that must be participating in order to produce blocks")
         ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(),
          ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str())
         ("private-key", bpo::value<vector<string>>()->composing()->multitoken()->
          DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))),
          "Tuple of [PublicKey, WIF private key] (may specify multiple times)")
         ;
   config_file_options.add(command_line_options);
}

std::string witness_plugin::plugin_name()const
{
   return "witness";
}

void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options)
{ try {
   ilog("witness plugin:  plugin_initialize() begin");
   _options = &options;
   LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type)

   if( options.count("private-key") )
   {
      const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>();
      for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings)
      {
         auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> >(key_id_to_wif_pair_string);
         //idump((key_id_to_wif_pair));
         ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first));
         fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second);
         if (!private_key)
         {
            // the key isn't in WIF format; see if they are still passing the old native private key format.  This is
            // just here to ease the transition, can be removed soon
            try
            {
               private_key = fc::variant(key_id_to_wif_pair.second).as<fc::ecc::private_key>();
            }
            catch (const fc::exception&)
            {
               FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second));
            }
         }
         _private_keys[key_id_to_wif_pair.first] = *private_key;
      }
   }
   ilog("witness plugin:  plugin_initialize() end");
} FC_LOG_AND_RETHROW() }

void witness_plugin::plugin_startup()
{ try {
   ilog("witness plugin:  plugin_startup() begin");
   chain::database& d = database();

   if( !_witnesses.empty() )
   {
      ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size()));
      app().set_block_production(true);
      if( _production_enabled )
      {
         if( d.head_block_num() == 0 )
            new_chain_banner(d);
         _production_skip_flags |= graphene::chain::database::skip_undo_history_check;
      }
      schedule_production_loop();
   } else
      elog("No witnesses configured! Please add witness IDs and private keys to configuration.");
   ilog("witness plugin:  plugin_startup() end");
} FC_CAPTURE_AND_RETHROW() }

void witness_plugin::plugin_shutdown()
{
   return;
}

void witness_plugin::schedule_production_loop()
{
   //Schedule for the next second's tick regardless of chain state
   // If we would wait less than 50ms, wait for the whole second.
   fc::time_point now = fc::time_point::now();
   int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000);
   if( time_to_next_second < 50000 )      // we must sleep for at least 50ms
       time_to_next_second += 1000000;

   fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) );

   //wdump( (now.time_since_epoch().count())(next_wakeup.time_since_epoch().count()) );
   _block_production_task = fc::schedule([this]{block_production_loop();},
                                         next_wakeup, "Witness Block Production");
}

block_production_condition::block_production_condition_enum witness_plugin::block_production_loop()
{
   block_production_condition::block_production_condition_enum result;
   fc::mutable_variant_object capture;
   try
   {
      result = maybe_produce_block(capture);
   }
   catch( const fc::canceled_exception& )
   {
      //We're trying to exit. Go ahead and let this one out.
      throw;
   }
   catch( const fc::exception& e )
   {
      elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string()));
      result = block_production_condition::exception_producing_block;
   }

   switch( result )
   {
      case block_production_condition::produced:
         ilog("Generated block #${n} with timestamp ${t} at time ${c}", (capture));
         break;
      case block_production_condition::not_synced:
         ilog("Not producing block because production is disabled until we receive a recent block (see: --enable-stale-production)");
         break;
      case block_production_condition::not_my_turn:
         //ilog("Not producing block because it isn't my turn");
         break;
      case block_production_condition::not_time_yet:
         //ilog("Not producing block because slot has not yet arrived");
         break;
      case block_production_condition::no_private_key:
         ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) );
         break;
      case block_production_condition::low_participation:
         elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) );
         break;
      case block_production_condition::lag:
         elog("Not producing block because node didn't wake up within 500ms of the slot time.");
         break;
      case block_production_condition::consecutive:
         elog("Not producing block because the last block was generated by the same witness.\nThis node is probably disconnected from the network so block production has been disabled.\nDisable this check with --allow-consecutive option.");
         break;
      case block_production_condition::exception_producing_block:
         elog( "exception prodcing block" );
         break;
   }

   schedule_production_loop();
   return result;
}

block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::mutable_variant_object& capture )
{
   chain::database& db = database();
   fc::time_point now_fine = fc::time_point::now();
   fc::time_point_sec now = now_fine + fc::microseconds( 500000 );

   // If the next block production opportunity is in the present or future, we're synced.
   if( !_production_enabled )
   {
      if( db.get_slot_time(1) >= now )
         _production_enabled = true;
      else
         return block_production_condition::not_synced;
   }

   // is anyone scheduled to produce now or one second in the future?
   uint32_t slot = db.get_slot_at_time( now );
   if( slot == 0 )
   {
      capture("next_time", db.get_slot_time(1));
      return block_production_condition::not_time_yet;
   }

   //
   // this assert should not fail, because now <= db.head_block_time()
   // should have resulted in slot == 0.
   //
   // if this assert triggers, there is a serious bug in get_slot_at_time()
   // which would result in allowing a later block to have a timestamp
   // less than or equal to the previous block
   //
   assert( now > db.head_block_time() );

   graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot );
   // we must control the witness scheduled to produce the next block.
   if( _witnesses.find( scheduled_witness ) == _witnesses.end() )
   {
      capture("scheduled_witness", scheduled_witness);
      return block_production_condition::not_my_turn;
   }

   fc::time_point_sec scheduled_time = db.get_slot_time( slot );
   graphene::chain::public_key_type scheduled_key = scheduled_witness( db ).signing_key;
   auto private_key_itr = _private_keys.find( scheduled_key );

   if( private_key_itr == _private_keys.end() )
   {
      capture("scheduled_key", scheduled_key);
      return block_production_condition::no_private_key;
   }

   uint32_t prate = db.witness_participation_rate();
   if( prate < _required_witness_participation )
   {
      capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT));
      return block_production_condition::low_participation;
   }

   if( llabs((scheduled_time - now).count()) > fc::milliseconds( 500 ).count() )
   {
      capture("scheduled_time", scheduled_time)("now", now);
      return block_production_condition::lag;
   }

   auto block = db.generate_block(
      scheduled_time,
      scheduled_witness,
      private_key_itr->second,
      _production_skip_flags
      );
   capture("n", block.block_num())("t", block.timestamp)("c", now);
   fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } );

   return block_production_condition::produced;
}
<commit_msg>change welcome<commit_after>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <graphene/witness/witness.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/witness_object.hpp>

#include <graphene/utilities/key_conversion.hpp>

#include <fc/smart_ref_impl.hpp>
#include <fc/thread/thread.hpp>

#include <iostream>

using namespace graphene::witness_plugin;
using std::string;
using std::vector;

namespace bpo = boost::program_options;

void new_chain_banner( const graphene::chain::database& db )
{
   std::cerr << "\n"
      "********************************\n"
      "*                              *\n"
      "*   ------- NEW CHAIN ------   *\n"
      "*   - Welcome to FinChain! -   *\n"
      "*   ------------------------   *\n"
      "*   powered by Graphene        *\n"
      "********************************\n"
      "\n";
   if( db.get_slot_at_time( fc::time_point::now() ) > 200 )
   {
      std::cerr << "Your genesis seems to have an old timestamp\n"
         "Please consider using the --genesis-timestamp option to give your genesis a recent timestamp\n"
         "\n"
         ;
   }
   return;
}

void witness_plugin::plugin_set_program_options(
   boost::program_options::options_description& command_line_options,
   boost::program_options::options_description& config_file_options)
{
   auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan")));
   string witness_id_example = fc::json::to_string(chain::witness_id_type(5));
   command_line_options.add_options()
         ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.")
         ("required-participation", bpo::bool_switch()->notifier([this](int e){_required_witness_participation = uint32_t(e*GRAPHENE_1_PERCENT);}), "Percent of witnesses (0-99) that must be participating in order to produce blocks")
         ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(),
          ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str())
         ("private-key", bpo::value<vector<string>>()->composing()->multitoken()->
          DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))),
          "Tuple of [PublicKey, WIF private key] (may specify multiple times)")
         ;
   config_file_options.add(command_line_options);
}

std::string witness_plugin::plugin_name()const
{
   return "witness";
}

void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options)
{ try {
   ilog("witness plugin:  plugin_initialize() begin");
   _options = &options;
   LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type)

   if( options.count("private-key") )
   {
      const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>();
      for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings)
      {
         auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> >(key_id_to_wif_pair_string);
         //idump((key_id_to_wif_pair));
         ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first));
         fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second);
         if (!private_key)
         {
            // the key isn't in WIF format; see if they are still passing the old native private key format.  This is
            // just here to ease the transition, can be removed soon
            try
            {
               private_key = fc::variant(key_id_to_wif_pair.second).as<fc::ecc::private_key>();
            }
            catch (const fc::exception&)
            {
               FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second));
            }
         }
         _private_keys[key_id_to_wif_pair.first] = *private_key;
      }
   }
   ilog("witness plugin:  plugin_initialize() end");
} FC_LOG_AND_RETHROW() }

void witness_plugin::plugin_startup()
{ try {
   ilog("witness plugin:  plugin_startup() begin");
   chain::database& d = database();

   if( !_witnesses.empty() )
   {
      ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size()));
      app().set_block_production(true);
      if( _production_enabled )
      {
         if( d.head_block_num() == 0 )
            new_chain_banner(d);
         _production_skip_flags |= graphene::chain::database::skip_undo_history_check;
      }
      schedule_production_loop();
   } else
      elog("No witnesses configured! Please add witness IDs and private keys to configuration.");
   ilog("witness plugin:  plugin_startup() end");
} FC_CAPTURE_AND_RETHROW() }

void witness_plugin::plugin_shutdown()
{
   return;
}

void witness_plugin::schedule_production_loop()
{
   //Schedule for the next second's tick regardless of chain state
   // If we would wait less than 50ms, wait for the whole second.
   fc::time_point now = fc::time_point::now();
   int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000);
   if( time_to_next_second < 50000 )      // we must sleep for at least 50ms
       time_to_next_second += 1000000;

   fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) );

   //wdump( (now.time_since_epoch().count())(next_wakeup.time_since_epoch().count()) );
   _block_production_task = fc::schedule([this]{block_production_loop();},
                                         next_wakeup, "Witness Block Production");
}

block_production_condition::block_production_condition_enum witness_plugin::block_production_loop()
{
   block_production_condition::block_production_condition_enum result;
   fc::mutable_variant_object capture;
   try
   {
      result = maybe_produce_block(capture);
   }
   catch( const fc::canceled_exception& )
   {
      //We're trying to exit. Go ahead and let this one out.
      throw;
   }
   catch( const fc::exception& e )
   {
      elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string()));
      result = block_production_condition::exception_producing_block;
   }

   switch( result )
   {
      case block_production_condition::produced:
         ilog("Generated block #${n} with timestamp ${t} at time ${c}", (capture));
         break;
      case block_production_condition::not_synced:
         ilog("Not producing block because production is disabled until we receive a recent block (see: --enable-stale-production)");
         break;
      case block_production_condition::not_my_turn:
         //ilog("Not producing block because it isn't my turn");
         break;
      case block_production_condition::not_time_yet:
         //ilog("Not producing block because slot has not yet arrived");
         break;
      case block_production_condition::no_private_key:
         ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) );
         break;
      case block_production_condition::low_participation:
         elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) );
         break;
      case block_production_condition::lag:
         elog("Not producing block because node didn't wake up within 500ms of the slot time.");
         break;
      case block_production_condition::consecutive:
         elog("Not producing block because the last block was generated by the same witness.\nThis node is probably disconnected from the network so block production has been disabled.\nDisable this check with --allow-consecutive option.");
         break;
      case block_production_condition::exception_producing_block:
         elog( "exception prodcing block" );
         break;
   }

   schedule_production_loop();
   return result;
}

block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::mutable_variant_object& capture )
{
   chain::database& db = database();
   fc::time_point now_fine = fc::time_point::now();
   fc::time_point_sec now = now_fine + fc::microseconds( 500000 );

   // If the next block production opportunity is in the present or future, we're synced.
   if( !_production_enabled )
   {
      if( db.get_slot_time(1) >= now )
         _production_enabled = true;
      else
         return block_production_condition::not_synced;
   }

   // is anyone scheduled to produce now or one second in the future?
   uint32_t slot = db.get_slot_at_time( now );
   if( slot == 0 )
   {
      capture("next_time", db.get_slot_time(1));
      return block_production_condition::not_time_yet;
   }

   //
   // this assert should not fail, because now <= db.head_block_time()
   // should have resulted in slot == 0.
   //
   // if this assert triggers, there is a serious bug in get_slot_at_time()
   // which would result in allowing a later block to have a timestamp
   // less than or equal to the previous block
   //
   assert( now > db.head_block_time() );

   graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot );
   // we must control the witness scheduled to produce the next block.
   if( _witnesses.find( scheduled_witness ) == _witnesses.end() )
   {
      capture("scheduled_witness", scheduled_witness);
      return block_production_condition::not_my_turn;
   }

   fc::time_point_sec scheduled_time = db.get_slot_time( slot );
   graphene::chain::public_key_type scheduled_key = scheduled_witness( db ).signing_key;
   auto private_key_itr = _private_keys.find( scheduled_key );

   if( private_key_itr == _private_keys.end() )
   {
      capture("scheduled_key", scheduled_key);
      return block_production_condition::no_private_key;
   }

   uint32_t prate = db.witness_participation_rate();
   if( prate < _required_witness_participation )
   {
      capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT));
      return block_production_condition::low_participation;
   }

   if( llabs((scheduled_time - now).count()) > fc::milliseconds( 500 ).count() )
   {
      capture("scheduled_time", scheduled_time)("now", now);
      return block_production_condition::lag;
   }

   auto block = db.generate_block(
      scheduled_time,
      scheduled_witness,
      private_key_itr->second,
      _production_skip_flags
      );
   capture("n", block.block_num())("t", block.timestamp)("c", now);
   fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } );

   return block_production_condition::produced;
}
<|endoftext|>


<commit_before>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <svdpi.h>
#include <cassert>

#include "cosim.h"
#include "cosim_dpi.h"

int riscv_cosim_step(Cosim *cosim, const svBitVecVal *write_reg,
                     const svBitVecVal *write_reg_data, const svBitVecVal *pc,
                     svBit sync_trap) {
  assert(cosim);

  return cosim->step(write_reg[0], write_reg_data[0], pc[0], sync_trap) ? 1 : 0;
}

void riscv_cosim_set_mip(Cosim *cosim, const svBitVecVal *mip) {
  assert(cosim);

  cosim->set_mip(mip[0]);
}

void riscv_cosim_set_nmi(Cosim *cosim, svBit nmi) {
  assert(cosim);

  cosim->set_nmi(nmi);
}

void riscv_cosim_set_debug_req(Cosim *cosim, svBit debug_req) {
  assert(cosim);

  cosim->set_debug_req(debug_req);
}

void riscv_cosim_set_mcycle(Cosim *cosim, svBitVecVal *mcycle) {
  assert(cosim);

  uint64_t mcycle_full = mcycle[0] | (uint64_t)mcycle[1] << 32;
  cosim->set_mcycle(mcycle_full);
}

void riscv_cosim_notify_dside_access(Cosim *cosim, svBit store,
                                     svBitVecVal *addr, svBitVecVal *data,
                                     svBitVecVal *be, svBit error,
                                     svBit misaligned_first,
                                     svBit misaligned_second) {
  assert(cosim);

  cosim->notify_dside_access(
      DSideAccessInfo{.store = store,
                      .data = data[0],
                      .addr = addr[0],
                      .be = be[0],
                      .error = error,
                      .misaligned_first = misaligned_first,
                      .misaligned_second = misaligned_second});
}

void riscv_cosim_set_iside_error(Cosim *cosim, svBitVecVal *addr) {
  assert(cosim);

  cosim->set_iside_error(addr[0]);
}

int riscv_cosim_get_num_errors(Cosim *cosim) {
  assert(cosim);

  return cosim->get_errors().size();
}

const char *riscv_cosim_get_error(Cosim *cosim, int index) {
  assert(cosim);

  if (index >= cosim->get_errors().size()) {
    return nullptr;
  }

  return cosim->get_errors()[index].c_str();
}

void riscv_cosim_clear_errors(Cosim *cosim) {
  assert(cosim);

  cosim->clear_errors();
}

void riscv_cosim_write_mem_byte(Cosim *cosim, const svBitVecVal *addr,
                                const svBitVecVal *d) {
  assert(cosim);
  uint8_t byte = d[0] & 0xff;
  cosim->backdoor_write_mem(addr[0], 1, &byte);
}

int riscv_cosim_get_insn_cnt(Cosim *cosim) {
  assert(cosim);

  return cosim->get_insn_cnt();
}
<commit_msg>Fix narrowing conversion warning in cosim_dpi.cc<commit_after>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <svdpi.h>
#include <cassert>

#include "cosim.h"
#include "cosim_dpi.h"

int riscv_cosim_step(Cosim *cosim, const svBitVecVal *write_reg,
                     const svBitVecVal *write_reg_data, const svBitVecVal *pc,
                     svBit sync_trap) {
  assert(cosim);

  return cosim->step(write_reg[0], write_reg_data[0], pc[0], sync_trap) ? 1 : 0;
}

void riscv_cosim_set_mip(Cosim *cosim, const svBitVecVal *mip) {
  assert(cosim);

  cosim->set_mip(mip[0]);
}

void riscv_cosim_set_nmi(Cosim *cosim, svBit nmi) {
  assert(cosim);

  cosim->set_nmi(nmi);
}

void riscv_cosim_set_debug_req(Cosim *cosim, svBit debug_req) {
  assert(cosim);

  cosim->set_debug_req(debug_req);
}

void riscv_cosim_set_mcycle(Cosim *cosim, svBitVecVal *mcycle) {
  assert(cosim);

  uint64_t mcycle_full = mcycle[0] | (uint64_t)mcycle[1] << 32;
  cosim->set_mcycle(mcycle_full);
}

void riscv_cosim_notify_dside_access(Cosim *cosim, svBit store,
                                     svBitVecVal *addr, svBitVecVal *data,
                                     svBitVecVal *be, svBit error,
                                     svBit misaligned_first,
                                     svBit misaligned_second) {
  assert(cosim);

  cosim->notify_dside_access(
      DSideAccessInfo{.store = store != 0,
                      .data = data[0],
                      .addr = addr[0],
                      .be = be[0],
                      .error = error != 0,
                      .misaligned_first = misaligned_first != 0,
                      .misaligned_second = misaligned_second != 0});
}

void riscv_cosim_set_iside_error(Cosim *cosim, svBitVecVal *addr) {
  assert(cosim);

  cosim->set_iside_error(addr[0]);
}

int riscv_cosim_get_num_errors(Cosim *cosim) {
  assert(cosim);

  return cosim->get_errors().size();
}

const char *riscv_cosim_get_error(Cosim *cosim, int index) {
  assert(cosim);

  if (index >= cosim->get_errors().size()) {
    return nullptr;
  }

  return cosim->get_errors()[index].c_str();
}

void riscv_cosim_clear_errors(Cosim *cosim) {
  assert(cosim);

  cosim->clear_errors();
}

void riscv_cosim_write_mem_byte(Cosim *cosim, const svBitVecVal *addr,
                                const svBitVecVal *d) {
  assert(cosim);
  uint8_t byte = d[0] & 0xff;
  cosim->backdoor_write_mem(addr[0], 1, &byte);
}

int riscv_cosim_get_insn_cnt(Cosim *cosim) {
  assert(cosim);

  return cosim->get_insn_cnt();
}
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH

//#ifdef HAVE_EIGEN

// system
#include <vector>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// local
#include "../backend/container/eigen.hh"

namespace Dune
{

namespace Detailed {

namespace Discretizations
{

namespace LA
{

namespace Factory
{

//! \attention There might be a problem with the sparsity pattern.
//! \todo Understand the eigen sparsity pattern and which insertion method to use!
template< class EntryType >
class Eigen
{
public:
  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::SparseMatrix< EntryType > SparseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseMatrix< EntryType > DenseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseVector< EntryType > DenseVectorType;

  typedef std::map< unsigned int, std::set< unsigned int > > PatternType;

  template< class AnsatzSpaceType, class TestSpaceType >
  static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    // generate sparsity pattern
    const PatternType pattern = ansatzSpace.computePattern(testSpace);
    return createSparseMatrix(ansatzSpace.map().size(), testSpace.map().size(), pattern);
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  static SparseMatrixType createSparseMatrix(const unsigned int rows, const unsigned int cols, const PatternType& pattern)
  {
    // init
    SparseMatrixType matrix(rows, cols);

    // tell pattern to matrix
    for (typename PatternType::const_iterator rowSet = pattern.begin(); rowSet != pattern.end(); ++rowSet) {
      const unsigned int row = rowSet->first;
      const std::set< unsigned int >& rowEntries = rowSet->second;
//      matrix.storage()->startVec(row);
      for (typename std::set< unsigned int >::iterator rowEntry = rowEntries.begin();
          rowEntry != rowEntries.end(); ++rowEntry) {
        unsigned int column = *rowEntry;
        matrix.storage()->insert/*BackByOuterInner*/(row, column);
      }
    } // tell pattern to matrix

    // finalize matrix
    matrix.storage()->finalize();
    matrix.storage()->makeCompressed();

    // return
    return matrix;
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template< class AnsatzSpaceType, class TestSpaceType >
  static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    return createDenseMatrix(ansatzSpace.map().size(), testSpace.map().size());
  }

  static DenseMatrixType createDenseMatrix(const unsigned int rows, const unsigned int cols)
  {
    // init
    DenseMatrixType matrix(rows, cols);
    // reserve
    matrix.reserve();
    // return
    return matrix;
  } // static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template< class SpaceType >
  static DenseVectorType createDenseVector(const SpaceType& space)
  {
    return createDenseVector(space.map().size());
  }

  static DenseVectorType createDenseVector(const unsigned int size)
  {
    // init
    DenseVectorType vector(size);
    // reserve
    vector.reserve();
    // return
    return vector;
  } // static DenseVectorType createDenseVector(const SpaceType& space)
}; // class Eigen

} // namespace Factory

} // namespace LA

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

//#endif // HAVE_EIGEN

#endif // DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
<commit_msg>[la.factory.eigen] fixed very slow creation is still slow for patterns, which contain zero rows<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
#define DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH

//#ifdef HAVE_EIGEN

// system
#include <vector>
#include <set>

// dune-common
#include <dune/common/shared_ptr.hh>

// local
#include "../backend/container/eigen.hh"

namespace Dune
{

namespace Detailed {

namespace Discretizations
{

namespace LA
{

namespace Factory
{

//! \attention There might be a problem with the sparsity pattern.
//! \todo Understand the eigen sparsity pattern and which insertion method to use!
template< class EntryType >
class Eigen
{
public:
  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::SparseMatrix< EntryType > SparseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseMatrix< EntryType > DenseMatrixType;

  typedef Dune::Detailed::Discretizations::LA::Backend::Container::Eigen::DenseVector< EntryType > DenseVectorType;

  typedef std::map< unsigned int, std::set< unsigned int > > PatternType;

  template< class AnsatzSpaceType, class TestSpaceType >
  static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    // generate sparsity pattern
    const PatternType pattern = ansatzSpace.computePattern(testSpace);
    return createSparseMatrix(ansatzSpace.map().size(), testSpace.map().size(), pattern);
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  //! \attention  This is really slow if the pattern contains empty rows!
  //! \todo       Fix this, should be easy (call startVec() for each empty row)!
  static SparseMatrixType createSparseMatrix(const unsigned int rows, const unsigned int cols, const PatternType& pattern)
  {
    // init
    SparseMatrixType matrix(rows, cols);
    // use faster method if possible
    if (pattern.size() == rows) {
      // tell pattern to matrix
      for (typename PatternType::const_iterator rowSet = pattern.begin(); rowSet != pattern.end(); ++rowSet) {
        const unsigned int row = rowSet->first;
        const std::set< unsigned int >& rowEntries = rowSet->second;
        matrix.storage()->startVec(row);
        for (typename std::set< unsigned int >::iterator rowEntry = rowEntries.begin();
            rowEntry != rowEntries.end(); ++rowEntry) {
          unsigned int column = *rowEntry;
          matrix.storage()->insertBackByOuterInner(row, column);
        }
      } // tell pattern to matrix
    } else { // use faster method if possible
      // tell pattern to matrix
      for (typename PatternType::const_iterator rowSet = pattern.begin(); rowSet != pattern.end(); ++rowSet) {
        const unsigned int row = rowSet->first;
        const std::set< unsigned int >& rowEntries = rowSet->second;
        for (typename std::set< unsigned int >::iterator rowEntry = rowEntries.begin();
            rowEntry != rowEntries.end(); ++rowEntry) {
          unsigned int column = *rowEntry;
          matrix.storage()->insert(row, column);
        }
      } // tell pattern to matrix
    } // use faster method if possible
    // finalize matrix
    matrix.storage()->finalize();
    matrix.storage()->makeCompressed();
    // return
    return matrix;
  } // static SparseMatrixType createSparseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template< class AnsatzSpaceType, class TestSpaceType >
  static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)
  {
    return createDenseMatrix(ansatzSpace.map().size(), testSpace.map().size());
  }

  static DenseMatrixType createDenseMatrix(const unsigned int rows, const unsigned int cols)
  {
    // init
    DenseMatrixType matrix(rows, cols);
    // reserve
    matrix.reserve();
    // return
    return matrix;
  } // static DenseMatrixType createDenseMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace)

  template< class SpaceType >
  static DenseVectorType createDenseVector(const SpaceType& space)
  {
    return createDenseVector(space.map().size());
  }

  static DenseVectorType createDenseVector(const unsigned int size)
  {
    // init
    DenseVectorType vector(size);
    // reserve
    vector.reserve();
    // return
    return vector;
  } // static DenseVectorType createDenseVector(const SpaceType& space)
}; // class Eigen

} // namespace Factory

} // namespace LA

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

//#endif // HAVE_EIGEN

#endif // DUNE_DETAILED_DISCRETIZATIONS_CONTAINER_FACTORY_EIGEN_HH
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file dp_st_speed_optimizer.cc
 **/

#include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h"

#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_boundary_mapper.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_configuration.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_graph.h"
#include "modules/planning/optimizer/st_graph/st_graph_data.h"
#include "modules/common/adapters/adapter_manager.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::config::VehicleConfigHelper;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::localization::LocalizationEstimate;

DpStSpeedOptimizer::DpStSpeedOptimizer(const std::string& name)
    : SpeedOptimizer(name) {}

Status DpStSpeedOptimizer::Process(const PathData& path_data,
                                   const TrajectoryPoint& init_point,
                                   DecisionData* const decision_data,
                                   SpeedData* const speed_data) const {
  ::apollo::common::config::VehicleParam veh_param =
      VehicleConfigHelper::GetConfig().vehicle_param();

  // TODO: load boundary mapper and st graph configuration
  StBoundaryConfig st_boundary_config;
  DpStConfiguration dp_st_speed_config;
  //TODO(yifei) will change to pb later
  //DpStSpeedConfig dp_st_speed_config;
  //if (!common::util::GetProtoFromFile(FLAGS_dp_st_speed_config_file,
  //                                    &dp_st_speed_config)) {
  //  AERROR << "failed to load config file " << FLAGS_dp_st_speed_config_file;
  //  return Status(ErrorCode::PLANNING_ERROR_FAILED,
  //                "failed to load config file");
  //}

  // step 1 get boundaries
  DpStBoundaryMapper st_mapper(st_boundary_config, veh_param);
  double planning_distance = std::min(dp_st_speed_config.total_path_length(),
                                      path_data.path().param_length());

  std::vector<StGraphBoundary> boundaries;

  common::TrajectoryPoint initial_planning_point = DataCenter::instance()
                                                       ->current_frame()
                                                       ->mutable_planning_data()
                                                       ->init_planning_point();
  if (!st_mapper
           .get_graph_boundary(initial_planning_point, *decision_data,
                               path_data,
                               dp_st_speed_config.total_path_length(),
                               dp_st_speed_config.total_time(), &boundaries)
           .ok()) {
    const std::string msg =
        "Mapping obstacle for dp st speed optimizer failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  // step 2 perform graph search
  SpeedLimit speed_limit;
  auto localization_adapter = AdapterManager::GetLocalization();
  if (localization_adapter->Empty()) {
    AINFO << "No Localization msg yet. ";
    return Status(ErrorCode::PLANNING_ERROR_FAILED, "No localization msg");
  }
  LocalizationEstimate localization = localization_adapter->GetLatestObserved();

  if (st_mapper.get_speed_limits( localization.pose(),
      DataCenter::instance()->map(),
      path_data,
      planning_distance,
      dp_st_speed_config.matrix_dimension_s(),
      dp_st_speed_config.max_speed(),
      &speed_limit) != Status::OK()) {
    AERROR << "Getting speed limits for dp st speed optimizer failed!";
    return Status(ErrorCode::PLANNING_ERROR_FAILED,
                  "Getting speed limits for dp st speed optimizer failed!");

  }

  StGraphData st_graph_data(boundaries, init_point, speed_limit,
                            path_data.path().param_length());

  DpStGraph st_graph(dp_st_speed_config, veh_param);

  if (!st_graph.search(st_graph_data, decision_data, speed_data).ok()) {
    const std::string msg = "Failed to search graph with dynamic programming.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  return Status::OK();
}

}  // namespace planning
}  // namespace apollo
<commit_msg>fixed error code.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file dp_st_speed_optimizer.cc
 **/

#include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h"

#include <vector>

#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_boundary_mapper.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_configuration.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_graph.h"
#include "modules/planning/optimizer/st_graph/st_graph_data.h"
#include "modules/common/adapters/adapter_manager.h"

namespace apollo {
namespace planning {

using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::config::VehicleConfigHelper;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::localization::LocalizationEstimate;

DpStSpeedOptimizer::DpStSpeedOptimizer(const std::string& name)
    : SpeedOptimizer(name) {}

Status DpStSpeedOptimizer::Process(const PathData& path_data,
                                   const TrajectoryPoint& init_point,
                                   DecisionData* const decision_data,
                                   SpeedData* const speed_data) const {
  ::apollo::common::config::VehicleParam veh_param =
      VehicleConfigHelper::GetConfig().vehicle_param();

  // TODO: load boundary mapper and st graph configuration
  StBoundaryConfig st_boundary_config;
  DpStConfiguration dp_st_speed_config;
  //TODO(yifei) will change to pb later
  //DpStSpeedConfig dp_st_speed_config;
  //if (!common::util::GetProtoFromFile(FLAGS_dp_st_speed_config_file,
  //                                    &dp_st_speed_config)) {
  //  AERROR << "failed to load config file " << FLAGS_dp_st_speed_config_file;
  //  return Status(ErrorCode::PLANNING_ERROR_FAILED,
  //                "failed to load config file");
  //}

  // step 1 get boundaries
  DpStBoundaryMapper st_mapper(st_boundary_config, veh_param);
  double planning_distance = std::min(dp_st_speed_config.total_path_length(),
                                      path_data.path().param_length());

  std::vector<StGraphBoundary> boundaries;

  common::TrajectoryPoint initial_planning_point = DataCenter::instance()
                                                       ->current_frame()
                                                       ->mutable_planning_data()
                                                       ->init_planning_point();
  if (!st_mapper
           .get_graph_boundary(initial_planning_point, *decision_data,
                               path_data,
                               dp_st_speed_config.total_path_length(),
                               dp_st_speed_config.total_time(), &boundaries)
           .ok()) {
    const std::string msg =
        "Mapping obstacle for dp st speed optimizer failed.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  // step 2 perform graph search
  SpeedLimit speed_limit;
  auto localization_adapter = AdapterManager::GetLocalization();
  if (localization_adapter->Empty()) {
    AINFO << "No Localization msg yet. ";
    return Status(ErrorCode::PLANNING_ERROR, "No localization msg");
  }
  LocalizationEstimate localization = localization_adapter->GetLatestObserved();

  if (st_mapper.get_speed_limits( localization.pose(),
      DataCenter::instance()->map(),
      path_data,
      planning_distance,
      dp_st_speed_config.matrix_dimension_s(),
      dp_st_speed_config.max_speed(),
      &speed_limit) != Status::OK()) {
    AERROR << "Getting speed limits for dp st speed optimizer failed!";
    return Status(ErrorCode::PLANNING_ERROR,
                  "Getting speed limits for dp st speed optimizer failed!");

  }

  StGraphData st_graph_data(boundaries, init_point, speed_limit,
                            path_data.path().param_length());

  DpStGraph st_graph(dp_st_speed_config, veh_param);

  if (!st_graph.search(st_graph_data, decision_data, speed_data).ok()) {
    const std::string msg = "Failed to search graph with dynamic programming.";
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  return Status::OK();
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAppendCompositeDataLeaves.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkAppendCompositeDataLeaves.h"

#include "vtkAppendFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataSet.h"
#include "vtkDataSetAttributes.h"
#include "vtkDataSetCollection.h"
#include "vtkExecutive.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkAppendCompositeDataLeaves, "1.2");
vtkStandardNewMacro(vtkAppendCompositeDataLeaves);

//----------------------------------------------------------------------------
vtkAppendCompositeDataLeaves::vtkAppendCompositeDataLeaves()
{
  this->AppendFieldData = 0;
  this->AppendUG = 0;
  this->AppendPD = 0;
}

//----------------------------------------------------------------------------
vtkAppendCompositeDataLeaves::~vtkAppendCompositeDataLeaves()
{
  if ( this->AppendUG )
    this->AppendUG->Delete();
  if ( this->AppendPD )
    this->AppendPD->Delete();
}

//----------------------------------------------------------------------------
vtkCompositeDataSet* vtkAppendCompositeDataLeaves::GetInput( int idx )
{
  if ( idx >= this->GetNumberOfInputConnections( 0 ) || idx < 0 )
    {
    return 0;
    }

  return vtkCompositeDataSet::SafeDownCast(
    this->GetExecutive()->GetInputData( 0, idx ) );
}

//----------------------------------------------------------------------------
// Remove a dataset from the list of data to append.
void vtkAppendCompositeDataLeaves::RemoveInput( vtkDataSet* ds )
{
  vtkAlgorithmOutput* algOutput = 0;
  if ( ds )
    {
    algOutput = ds->GetProducerPort();
    }

  this->RemoveInputConnection( 0, algOutput );
}

//----------------------------------------------------------------------------
int vtkAppendCompositeDataLeaves::RequestDataObject(
  vtkInformation*,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector )
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject( 0 );
  if ( ! inInfo )
    {
    return 0;
    }
  vtkCompositeDataSet* input = vtkCompositeDataSet::SafeDownCast(
    inInfo->Get( vtkDataObject::DATA_OBJECT() ) );

  if ( input )
    {
    // for each output
    for ( int i = 0; i < this->GetNumberOfOutputPorts(); ++ i )
      {
      vtkInformation* info = outputVector->GetInformationObject( i );
      vtkCompositeDataSet *output = vtkCompositeDataSet::SafeDownCast(
        info->Get( vtkDataObject::DATA_OBJECT() ) );

      if ( ! output || ! output->IsA( input->GetClassName() ) )
        {
        vtkCompositeDataSet* newOutput = input->NewInstance();
        newOutput->SetPipelineInformation( info );
        newOutput->Delete();
        }
      }
    return 1;
    }
  return 0;
}

//----------------------------------------------------------------------------
// Append data sets into single unstructured grid
int vtkAppendCompositeDataLeaves::RequestData(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector),
  vtkInformationVector* outputVector)
{
  int numInputs = this->GetNumberOfInputConnections( 0 );
  if ( numInputs <= 0 )
    {
    // Fail silently when there are no inputs.
    return 1;
    }

  // get the output info object
  vtkInformation* outInfo = outputVector->GetInformationObject( 0 );

  // get the ouptut
  vtkCompositeDataSet* output = vtkCompositeDataSet::SafeDownCast(
    outInfo->Get( vtkDataObject::DATA_OBJECT() ) );

  vtkDebugMacro(<<"Copying structure to output");

  vtkCompositeDataSet* anInput = vtkCompositeDataSet::SafeDownCast(
    this->GetInput( 0 ) );
  output->CopyStructure( anInput );

  vtkDebugMacro(<<"Appending data together");

  vtkCompositeDataIterator* iter = output->NewIterator();
  iter->VisitOnlyLeavesOn();
  iter->SkipEmptyNodesOff(); // We're iterating over the output, whose leaves are all empty.
  int idx = 0;
  int i;
  static bool first = true;
  for ( iter->InitTraversal(); ! iter->IsDoneWithTraversal(); iter->GoToNextItem(), ++idx )
    {
    // Loop over all inputs at this "spot" in the composite data.
    vtkDataObject* obj = 0;
    for ( i = 0; i < numInputs && ! obj; ++ i )
      {
      obj = this->GetInput( i )->GetDataSet( iter );
      }
    if ( ! obj )
      {
      continue; // no input had a non-NULL dataset
      }
    vtkUnstructuredGrid* ug = vtkUnstructuredGrid::SafeDownCast( obj );
    if ( ug )
      {
      this->AppendUnstructuredGrids( i - 1, numInputs, iter, output );
      continue;
      }
    vtkPolyData* pd = vtkPolyData::SafeDownCast( obj );
    if ( pd )
      {
      this->AppendPolyData( i - 1, numInputs, iter, output );
      continue;
      }
    if ( first )
      {
      first = false;
      vtkWarningMacro(
        << "Input " << i << " was of type \""
        << obj->GetClassName() << "\" which is not handled\n" );
      }
    }
  first = true;
  iter->Delete();
  return 1;
}

//----------------------------------------------------------------------------
int vtkAppendCompositeDataLeaves::FillInputPortInformation( int, vtkInformation* info )
{
  info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet" );
  info->Set( vtkAlgorithm::INPUT_IS_REPEATABLE(), 1 );
  return 1;
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf( os, indent );
  os << indent << "AppendFieldData: " << this->AppendFieldData << "\n";
  os << indent << "AppendUG: " << this->AppendUG << "\n";
  os << indent << "AppendPD: " << this->AppendPD << "\n";
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendUnstructuredGrids(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkCompositeDataSet* output )
{
  if ( this->AppendUG )
    {
    this->AppendUG->Delete();
    }
  this->AppendUG = vtkAppendFilter::New();

  vtkUnstructuredGrid* ug = vtkUnstructuredGrid::New();
  output->SetDataSet( iter, ug );
  ug->Delete();

  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkUnstructuredGrid* iudset = vtkUnstructuredGrid::SafeDownCast( icdset->GetDataSet( iter ) );
      if ( iudset )
        {
        this->AppendUG->AddInput( iudset );
        }
      }
    }
  this->AppendUG->Update();
  ug->ShallowCopy( this->AppendUG->GetOutput() );

  this->AppendFieldDataArrays( i, numInputs, iter, ug );
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendPolyData(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkCompositeDataSet* output )
{
  if ( this->AppendPD )
    {
    this->AppendPD->Delete();
    }
  this->AppendPD = vtkAppendPolyData::New();

  vtkPolyData* pd = vtkPolyData::New();
  output->SetDataSet( iter, pd );
  pd->Delete();

  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkPolyData* ipdset = vtkPolyData::SafeDownCast( icdset->GetDataSet( iter ) );
      if ( ipdset )
        {
        this->AppendPD->AddInput( ipdset );
        }
      }
    }
  this->AppendPD->Update();
  pd->ShallowCopy( this->AppendPD->GetOutput() );

  this->AppendFieldDataArrays( i, numInputs, iter, pd );
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendFieldDataArrays(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkDataSet* odset )
{
  if ( ! this->AppendFieldData )
    return;

  vtkFieldData* ofd = odset->GetFieldData();
  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkDataObject* idobj = icdset->GetDataSet( iter );
      if ( idobj )
        {
        vtkFieldData* ifd = idobj->GetFieldData();
        int numArr = ifd->GetNumberOfArrays();
        for ( int a = 0; a < numArr; ++ a )
          {
          vtkAbstractArray* arr = ifd->GetAbstractArray( a );
          if ( ofd->HasArray( arr->GetName() ) )
            {
            // Do something?
            }
          else
            {
            ofd->AddArray( arr );
            }
          }
        }
      }
    }
}
<commit_msg>PERF: Is there's just 1 input, speed up the appending.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAppendCompositeDataLeaves.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkAppendCompositeDataLeaves.h"

#include "vtkAppendFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataSet.h"
#include "vtkDataSetAttributes.h"
#include "vtkDataSetCollection.h"
#include "vtkExecutive.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkAppendCompositeDataLeaves, "1.3");
vtkStandardNewMacro(vtkAppendCompositeDataLeaves);

//----------------------------------------------------------------------------
vtkAppendCompositeDataLeaves::vtkAppendCompositeDataLeaves()
{
  this->AppendFieldData = 0;
  this->AppendUG = 0;
  this->AppendPD = 0;
}

//----------------------------------------------------------------------------
vtkAppendCompositeDataLeaves::~vtkAppendCompositeDataLeaves()
{
  if ( this->AppendUG )
    this->AppendUG->Delete();
  if ( this->AppendPD )
    this->AppendPD->Delete();
}

//----------------------------------------------------------------------------
vtkCompositeDataSet* vtkAppendCompositeDataLeaves::GetInput( int idx )
{
  if ( idx >= this->GetNumberOfInputConnections( 0 ) || idx < 0 )
    {
    return 0;
    }

  return vtkCompositeDataSet::SafeDownCast(
    this->GetExecutive()->GetInputData( 0, idx ) );
}

//----------------------------------------------------------------------------
// Remove a dataset from the list of data to append.
void vtkAppendCompositeDataLeaves::RemoveInput( vtkDataSet* ds )
{
  vtkAlgorithmOutput* algOutput = 0;
  if ( ds )
    {
    algOutput = ds->GetProducerPort();
    }

  this->RemoveInputConnection( 0, algOutput );
}

//----------------------------------------------------------------------------
int vtkAppendCompositeDataLeaves::RequestDataObject(
  vtkInformation*,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector )
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject( 0 );
  if ( ! inInfo )
    {
    return 0;
    }
  vtkCompositeDataSet* input = vtkCompositeDataSet::SafeDownCast(
    inInfo->Get( vtkDataObject::DATA_OBJECT() ) );

  if ( input )
    {
    // for each output
    for ( int i = 0; i < this->GetNumberOfOutputPorts(); ++ i )
      {
      vtkInformation* info = outputVector->GetInformationObject( i );
      vtkCompositeDataSet *output = vtkCompositeDataSet::SafeDownCast(
        info->Get( vtkDataObject::DATA_OBJECT() ) );

      if ( ! output || ! output->IsA( input->GetClassName() ) )
        {
        vtkCompositeDataSet* newOutput = input->NewInstance();
        newOutput->SetPipelineInformation( info );
        newOutput->Delete();
        }
      }
    return 1;
    }
  return 0;
}

//----------------------------------------------------------------------------
// Append data sets into single unstructured grid
int vtkAppendCompositeDataLeaves::RequestData(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector),
  vtkInformationVector* outputVector)
{
  int numInputs = this->GetNumberOfInputConnections( 0 );
  if ( numInputs <= 0 )
    {
    // Fail silently when there are no inputs.
    return 1;
    }

  // get the output info object
  vtkInformation* outInfo = outputVector->GetInformationObject( 0 );

  // get the ouptut
  vtkCompositeDataSet* output = vtkCompositeDataSet::SafeDownCast(
    outInfo->Get( vtkDataObject::DATA_OBJECT() ) );

  vtkDebugMacro(<<"Copying structure to output");

  vtkCompositeDataSet* anInput = vtkCompositeDataSet::SafeDownCast(
    this->GetInput( 0 ) );

  if (numInputs == 1)
    {
    output->ShallowCopy(anInput);
    return 1;
    }

  output->CopyStructure( anInput );

  vtkDebugMacro(<<"Appending data together");

  vtkCompositeDataIterator* iter = output->NewIterator();
  iter->VisitOnlyLeavesOn();
  iter->SkipEmptyNodesOff(); // We're iterating over the output, whose leaves are all empty.
  int idx = 0;
  int i;
  static bool first = true;
  for ( iter->InitTraversal(); ! iter->IsDoneWithTraversal(); iter->GoToNextItem(), ++idx )
    {
    // Loop over all inputs at this "spot" in the composite data.
    vtkDataObject* obj = 0;
    for ( i = 0; i < numInputs && ! obj; ++ i )
      {
      obj = this->GetInput( i )->GetDataSet( iter );
      }
    if ( ! obj )
      {
      continue; // no input had a non-NULL dataset
      }
    vtkUnstructuredGrid* ug = vtkUnstructuredGrid::SafeDownCast( obj );
    if ( ug )
      {
      this->AppendUnstructuredGrids( i - 1, numInputs, iter, output );
      continue;
      }
    vtkPolyData* pd = vtkPolyData::SafeDownCast( obj );
    if ( pd )
      {
      this->AppendPolyData( i - 1, numInputs, iter, output );
      continue;
      }
    if ( first )
      {
      first = false;
      vtkWarningMacro(
        << "Input " << i << " was of type \""
        << obj->GetClassName() << "\" which is not handled\n" );
      }
    }
  first = true;
  iter->Delete();
  return 1;
}

//----------------------------------------------------------------------------
int vtkAppendCompositeDataLeaves::FillInputPortInformation( int, vtkInformation* info )
{
  info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet" );
  info->Set( vtkAlgorithm::INPUT_IS_REPEATABLE(), 1 );
  return 1;
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf( os, indent );
  os << indent << "AppendFieldData: " << this->AppendFieldData << "\n";
  os << indent << "AppendUG: " << this->AppendUG << "\n";
  os << indent << "AppendPD: " << this->AppendPD << "\n";
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendUnstructuredGrids(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkCompositeDataSet* output )
{
  if ( this->AppendUG )
    {
    this->AppendUG->Delete();
    }
  this->AppendUG = vtkAppendFilter::New();

  vtkUnstructuredGrid* ug = vtkUnstructuredGrid::New();
  output->SetDataSet( iter, ug );
  ug->Delete();

  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkUnstructuredGrid* iudset = vtkUnstructuredGrid::SafeDownCast( icdset->GetDataSet( iter ) );
      if ( iudset )
        {
        this->AppendUG->AddInput( iudset );
        }
      }
    }
  this->AppendUG->Update();
  ug->ShallowCopy( this->AppendUG->GetOutput() );

  this->AppendFieldDataArrays( i, numInputs, iter, ug );
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendPolyData(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkCompositeDataSet* output )
{
  if ( this->AppendPD )
    {
    this->AppendPD->Delete();
    }
  this->AppendPD = vtkAppendPolyData::New();

  vtkPolyData* pd = vtkPolyData::New();
  output->SetDataSet( iter, pd );
  pd->Delete();

  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkPolyData* ipdset = vtkPolyData::SafeDownCast( icdset->GetDataSet( iter ) );
      if ( ipdset )
        {
        this->AppendPD->AddInput( ipdset );
        }
      }
    }
  this->AppendPD->Update();
  pd->ShallowCopy( this->AppendPD->GetOutput() );

  this->AppendFieldDataArrays( i, numInputs, iter, pd );
}

//----------------------------------------------------------------------------
void vtkAppendCompositeDataLeaves::AppendFieldDataArrays(
  int i, int numInputs, vtkCompositeDataIterator* iter, vtkDataSet* odset )
{
  if ( ! this->AppendFieldData )
    return;

  vtkFieldData* ofd = odset->GetFieldData();
  for ( int idx = i; idx < numInputs; ++ idx )
    {
    vtkCompositeDataSet* icdset = this->GetInput( idx );
    if ( icdset )
      {
      vtkDataObject* idobj = icdset->GetDataSet( iter );
      if ( idobj )
        {
        vtkFieldData* ifd = idobj->GetFieldData();
        int numArr = ifd->GetNumberOfArrays();
        for ( int a = 0; a < numArr; ++ a )
          {
          vtkAbstractArray* arr = ifd->GetAbstractArray( a );
          if ( ofd->HasArray( arr->GetName() ) )
            {
            // Do something?
            }
          else
            {
            ofd->AddArray( arr );
            }
          }
        }
      }
    }
}
<|endoftext|>


<commit_before>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#include <IceCandidate.hpp>
#include <webrtcendpoint/kmsicecandidate.h>
#include <IceComponentState.hpp>
#include <SignalHandler.hpp>

#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"

#define FACTORY_NAME "webrtcendpoint"

namespace kurento
{

static const uint DEFAULT_STUN_PORT = 3478;

static const gchar *supported_codecs[] = { "VP8", "opus", "PCMU" };

static void
remove_not_supported_codecs_from_array (GstElement *element, GArray *codecs)
{
  guint i;

  if (codecs == NULL) {
    return;
  }

  for (i = 0; i < codecs->len; i++) {
    GValue *v = &g_array_index (codecs, GValue, i);
    const GstStructure *s;
    const gchar *codec_name;
    gboolean supported = FALSE;
    guint j;

    if (!GST_VALUE_HOLDS_STRUCTURE (v) ) {
      GST_WARNING_OBJECT (element, "Value into array is not a GstStructure");
      continue;
    }

    s = gst_value_get_structure (v);
    codec_name = gst_structure_get_name (s);

    for (j = 0; j < G_N_ELEMENTS (supported_codecs); j++) {
      if (g_str_has_prefix (codec_name, supported_codecs[j]) ) {
        supported = TRUE;
        break;
      }
    }

    if (!supported) {
      GST_INFO_OBJECT (element, "Removing not supported codec '%s'", codec_name);
      g_array_remove_index (codecs, i);
      i--;
    }
  }
}

static void
remove_not_supported_codecs (GstElement *element)
{
  GArray *codecs;

  g_object_get (element, "audio-codecs", &codecs, NULL);
  remove_not_supported_codecs_from_array (element, codecs);

  g_object_get (element, "video-codecs", &codecs, NULL);
  remove_not_supported_codecs_from_array (element, codecs);
}

void WebRtcEndpointImpl::onIceCandidate (KmsIceCandidate *candidate)
{
  try {
    std::string cand_str (kms_ice_candidate_get_candidate (candidate) );
    std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) );
    int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate);
    std::shared_ptr <IceCandidate> cand ( new  IceCandidate
                                          (cand_str, mid_str, sdp_m_line_index) );
    OnIceCandidate event (shared_from_this(), OnIceCandidate::getName(), cand);

    signalOnIceCandidate (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::onIceGatheringDone ()
{
  try {
    OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() );

    signalOnIceGatheringDone (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::onIceComponentStateChanged (guint streamId,
    guint componentId, guint state)
{
  try {
    IceComponentState::type type;

    switch (state) {
    case NICE_COMPONENT_STATE_DISCONNECTED:
      type = IceComponentState::DISCONNECTED;
      break;

    case NICE_COMPONENT_STATE_GATHERING:
      type = IceComponentState::GATHERING;
      break;

    case NICE_COMPONENT_STATE_CONNECTING:
      type = IceComponentState::CONNECTING;
      break;

    case NICE_COMPONENT_STATE_CONNECTED:
      type = IceComponentState::CONNECTED;
      break;

    case NICE_COMPONENT_STATE_READY:
      type = IceComponentState::READY;
      break;

    case NICE_COMPONENT_STATE_FAILED:
      type = IceComponentState::FAILED;
      break;

    default:
      type = IceComponentState::FAILED;
      break;
    }

    IceComponentState *componentState = new IceComponentState (type);
    OnIceComponentStateChanged event (shared_from_this(),
                                      OnIceComponentStateChanged::getName(),
                                      streamId, componentId,  std::shared_ptr<IceComponentState> (componentState) );

    signalOnIceComponentStateChanged (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::postConstructor ()
{
  BaseRtpEndpointImpl::postConstructor ();

  handlerOnIceCandidate = register_signal_handler (G_OBJECT (element),
                          "on-ice-candidate",
                          std::function <void (GstElement *, KmsIceCandidate *) >
                          (std::bind (&WebRtcEndpointImpl::onIceCandidate, this,
                                      std::placeholders::_2) ),
                          std::dynamic_pointer_cast<WebRtcEndpointImpl>
                          (shared_from_this() ) );

  handlerOnIceGatheringDone = register_signal_handler (G_OBJECT (element),
                              "on-ice-gathering-done",
                              std::function <void (GstElement *) >
                              (std::bind (&WebRtcEndpointImpl::onIceGatheringDone, this) ),
                              std::dynamic_pointer_cast<WebRtcEndpointImpl>
                              (shared_from_this() ) );

  handlerOnIceComponentStateChanged = register_signal_handler (G_OBJECT (element),
                                      "on-ice-component-state-changed",
                                      std::function <void (GstElement *, guint, guint, guint) >
                                      (std::bind (&WebRtcEndpointImpl::onIceComponentStateChanged, this,
                                          std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ),
                                      std::dynamic_pointer_cast<WebRtcEndpointImpl>
                                      (shared_from_this() ) );
}

WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
                                        std::shared_ptr<MediaPipeline>
                                        mediaPipeline) : BaseRtpEndpointImpl (conf,
                                              std::dynamic_pointer_cast<MediaObjectImpl>
                                              (mediaPipeline), FACTORY_NAME)
{
  uint stunPort;
  std::string stunAddress;
  std::string turnURL;

  remove_not_supported_codecs (element);

  //set properties
  try {
    stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort");
  } catch (boost::property_tree::ptree_error &e) {
    GST_INFO ("Setting default port %d to stun server",
              DEFAULT_STUN_PORT);
    stunPort = DEFAULT_STUN_PORT;
  }

  if (stunPort != 0) {
    try {
      stunAddress = getConfigValue
                    <std::string, WebRtcEndpoint> ("stunServerAddress");
    } catch (boost::property_tree::ptree_error &e) {
      GST_INFO ("Stun address not found in config, cannot operate behind a NAT" );
    }

    if (!stunAddress.empty() ) {
      GST_INFO ("stun port %d\n", stunPort );
      g_object_set ( G_OBJECT (element), "stun-server-port",
                     stunPort, NULL);

      GST_INFO ("stun address %s\n", stunAddress.c_str() );
      g_object_set ( G_OBJECT (element), "stun-server",
                     stunAddress.c_str(),
                     NULL);
    }
  }

  try {
    turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL");
    GST_INFO ("turn info: %s\n", turnURL.c_str() );
    g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
                   NULL);
  } catch (boost::property_tree::ptree_error &e) {

  }
}

WebRtcEndpointImpl::~WebRtcEndpointImpl()
{
  if (handlerOnIceCandidate > 0) {
    unregister_signal_handler (element, handlerOnIceCandidate);
  }

  if (handlerOnIceGatheringDone > 0) {
    unregister_signal_handler (element, handlerOnIceGatheringDone);
  }

  if (handlerOnIceComponentStateChanged > 0) {
    unregister_signal_handler (element, handlerOnIceComponentStateChanged);
  }
}

std::string
WebRtcEndpointImpl::getStunServerAddress ()
{
  gchar *ret;

  g_object_get ( G_OBJECT (element), "stun-server", &ret, NULL);

  std::string stunServerAddress (ret);
  g_free (ret);

  return stunServerAddress;
}

void
WebRtcEndpointImpl::setStunServerAddress (const std::string &stunServerAddress)
{
  g_object_set ( G_OBJECT (element), "stun-server",
                 stunServerAddress.c_str(),
                 NULL);
}

int
WebRtcEndpointImpl::getStunServerPort ()
{
  int ret;

  g_object_get ( G_OBJECT (element), "stun-server-port", &ret, NULL);

  return ret;
}

void
WebRtcEndpointImpl::setStunServerPort (int stunServerPort)
{
  g_object_set ( G_OBJECT (element), "stun-server-port",
                 stunServerPort, NULL);
}

std::string
WebRtcEndpointImpl::getTurnUrl ()
{
  gchar *ret;

  g_object_get ( G_OBJECT (element), "turn-url", &ret, NULL);

  std::string turnUrl (ret);
  g_free (ret);

  return turnUrl;
}

void
WebRtcEndpointImpl::setTurnUrl (const std::string &turnUrl)
{
  g_object_set ( G_OBJECT (element), "turn-url",
                 turnUrl.c_str(),
                 NULL);
}

void
WebRtcEndpointImpl::gatherCandidates ()
{
  gboolean ret;

  g_signal_emit_by_name (element, "gather-candidates", &ret);

  if (!ret) {
    throw KurentoException (ICE_GATHER_CANDIDATES_ERROR,
                            "Error gathering candidates");
  }
}

void
WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate)
{
  gboolean ret;
  const char *cand_str = candidate->getCandidate().c_str ();
  const char *mid_str = candidate->getSdpMid().c_str ();
  guint8 sdp_m_line_index = candidate->getSdpMLineIndex ();
  KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str,
                          sdp_m_line_index);

  g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret);

  g_object_unref (cand);

  if (!ret) {
    throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate");
  }
}

MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
    &conf, std::shared_ptr<MediaPipeline>
    mediaPipeline) const
{
  return new WebRtcEndpointImpl (conf, mediaPipeline);
}

WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;

WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<commit_msg>WebRtcEndpointImpl: Fix memory leaks in codec garrays<commit_after>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#include <IceCandidate.hpp>
#include <webrtcendpoint/kmsicecandidate.h>
#include <IceComponentState.hpp>
#include <SignalHandler.hpp>

#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"

#define FACTORY_NAME "webrtcendpoint"

namespace kurento
{

static const uint DEFAULT_STUN_PORT = 3478;

static const gchar *supported_codecs[] = { "VP8", "opus", "PCMU" };

static void
remove_not_supported_codecs_from_array (GstElement *element, GArray *codecs)
{
  guint i;

  if (codecs == NULL) {
    return;
  }

  for (i = 0; i < codecs->len; i++) {
    GValue *v = &g_array_index (codecs, GValue, i);
    const GstStructure *s;
    const gchar *codec_name;
    gboolean supported = FALSE;
    guint j;

    if (!GST_VALUE_HOLDS_STRUCTURE (v) ) {
      GST_WARNING_OBJECT (element, "Value into array is not a GstStructure");
      continue;
    }

    s = gst_value_get_structure (v);
    codec_name = gst_structure_get_name (s);

    for (j = 0; j < G_N_ELEMENTS (supported_codecs); j++) {
      if (g_str_has_prefix (codec_name, supported_codecs[j]) ) {
        supported = TRUE;
        break;
      }
    }

    if (!supported) {
      GST_INFO_OBJECT (element, "Removing not supported codec '%s'", codec_name);
      g_array_remove_index (codecs, i);
      i--;
    }
  }
}

static void
remove_not_supported_codecs (GstElement *element)
{
  GArray *codecs;

  g_object_get (element, "audio-codecs", &codecs, NULL);
  remove_not_supported_codecs_from_array (element, codecs);
  g_array_unref (codecs);

  g_object_get (element, "video-codecs", &codecs, NULL);
  remove_not_supported_codecs_from_array (element, codecs);
  g_array_unref (codecs);
}

void WebRtcEndpointImpl::onIceCandidate (KmsIceCandidate *candidate)
{
  try {
    std::string cand_str (kms_ice_candidate_get_candidate (candidate) );
    std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) );
    int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate);
    std::shared_ptr <IceCandidate> cand ( new  IceCandidate
                                          (cand_str, mid_str, sdp_m_line_index) );
    OnIceCandidate event (shared_from_this(), OnIceCandidate::getName(), cand);

    signalOnIceCandidate (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::onIceGatheringDone ()
{
  try {
    OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() );

    signalOnIceGatheringDone (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::onIceComponentStateChanged (guint streamId,
    guint componentId, guint state)
{
  try {
    IceComponentState::type type;

    switch (state) {
    case NICE_COMPONENT_STATE_DISCONNECTED:
      type = IceComponentState::DISCONNECTED;
      break;

    case NICE_COMPONENT_STATE_GATHERING:
      type = IceComponentState::GATHERING;
      break;

    case NICE_COMPONENT_STATE_CONNECTING:
      type = IceComponentState::CONNECTING;
      break;

    case NICE_COMPONENT_STATE_CONNECTED:
      type = IceComponentState::CONNECTED;
      break;

    case NICE_COMPONENT_STATE_READY:
      type = IceComponentState::READY;
      break;

    case NICE_COMPONENT_STATE_FAILED:
      type = IceComponentState::FAILED;
      break;

    default:
      type = IceComponentState::FAILED;
      break;
    }

    IceComponentState *componentState = new IceComponentState (type);
    OnIceComponentStateChanged event (shared_from_this(),
                                      OnIceComponentStateChanged::getName(),
                                      streamId, componentId,  std::shared_ptr<IceComponentState> (componentState) );

    signalOnIceComponentStateChanged (event);
  } catch (std::bad_weak_ptr &e) {
  }
}

void WebRtcEndpointImpl::postConstructor ()
{
  BaseRtpEndpointImpl::postConstructor ();

  handlerOnIceCandidate = register_signal_handler (G_OBJECT (element),
                          "on-ice-candidate",
                          std::function <void (GstElement *, KmsIceCandidate *) >
                          (std::bind (&WebRtcEndpointImpl::onIceCandidate, this,
                                      std::placeholders::_2) ),
                          std::dynamic_pointer_cast<WebRtcEndpointImpl>
                          (shared_from_this() ) );

  handlerOnIceGatheringDone = register_signal_handler (G_OBJECT (element),
                              "on-ice-gathering-done",
                              std::function <void (GstElement *) >
                              (std::bind (&WebRtcEndpointImpl::onIceGatheringDone, this) ),
                              std::dynamic_pointer_cast<WebRtcEndpointImpl>
                              (shared_from_this() ) );

  handlerOnIceComponentStateChanged = register_signal_handler (G_OBJECT (element),
                                      "on-ice-component-state-changed",
                                      std::function <void (GstElement *, guint, guint, guint) >
                                      (std::bind (&WebRtcEndpointImpl::onIceComponentStateChanged, this,
                                          std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ),
                                      std::dynamic_pointer_cast<WebRtcEndpointImpl>
                                      (shared_from_this() ) );
}

WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
                                        std::shared_ptr<MediaPipeline>
                                        mediaPipeline) : BaseRtpEndpointImpl (conf,
                                              std::dynamic_pointer_cast<MediaObjectImpl>
                                              (mediaPipeline), FACTORY_NAME)
{
  uint stunPort;
  std::string stunAddress;
  std::string turnURL;

  remove_not_supported_codecs (element);

  //set properties
  try {
    stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort");
  } catch (boost::property_tree::ptree_error &e) {
    GST_INFO ("Setting default port %d to stun server",
              DEFAULT_STUN_PORT);
    stunPort = DEFAULT_STUN_PORT;
  }

  if (stunPort != 0) {
    try {
      stunAddress = getConfigValue
                    <std::string, WebRtcEndpoint> ("stunServerAddress");
    } catch (boost::property_tree::ptree_error &e) {
      GST_INFO ("Stun address not found in config, cannot operate behind a NAT" );
    }

    if (!stunAddress.empty() ) {
      GST_INFO ("stun port %d\n", stunPort );
      g_object_set ( G_OBJECT (element), "stun-server-port",
                     stunPort, NULL);

      GST_INFO ("stun address %s\n", stunAddress.c_str() );
      g_object_set ( G_OBJECT (element), "stun-server",
                     stunAddress.c_str(),
                     NULL);
    }
  }

  try {
    turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL");
    GST_INFO ("turn info: %s\n", turnURL.c_str() );
    g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
                   NULL);
  } catch (boost::property_tree::ptree_error &e) {

  }
}

WebRtcEndpointImpl::~WebRtcEndpointImpl()
{
  if (handlerOnIceCandidate > 0) {
    unregister_signal_handler (element, handlerOnIceCandidate);
  }

  if (handlerOnIceGatheringDone > 0) {
    unregister_signal_handler (element, handlerOnIceGatheringDone);
  }

  if (handlerOnIceComponentStateChanged > 0) {
    unregister_signal_handler (element, handlerOnIceComponentStateChanged);
  }
}

std::string
WebRtcEndpointImpl::getStunServerAddress ()
{
  gchar *ret;

  g_object_get ( G_OBJECT (element), "stun-server", &ret, NULL);

  std::string stunServerAddress (ret);
  g_free (ret);

  return stunServerAddress;
}

void
WebRtcEndpointImpl::setStunServerAddress (const std::string &stunServerAddress)
{
  g_object_set ( G_OBJECT (element), "stun-server",
                 stunServerAddress.c_str(),
                 NULL);
}

int
WebRtcEndpointImpl::getStunServerPort ()
{
  int ret;

  g_object_get ( G_OBJECT (element), "stun-server-port", &ret, NULL);

  return ret;
}

void
WebRtcEndpointImpl::setStunServerPort (int stunServerPort)
{
  g_object_set ( G_OBJECT (element), "stun-server-port",
                 stunServerPort, NULL);
}

std::string
WebRtcEndpointImpl::getTurnUrl ()
{
  gchar *ret;

  g_object_get ( G_OBJECT (element), "turn-url", &ret, NULL);

  std::string turnUrl (ret);
  g_free (ret);

  return turnUrl;
}

void
WebRtcEndpointImpl::setTurnUrl (const std::string &turnUrl)
{
  g_object_set ( G_OBJECT (element), "turn-url",
                 turnUrl.c_str(),
                 NULL);
}

void
WebRtcEndpointImpl::gatherCandidates ()
{
  gboolean ret;

  g_signal_emit_by_name (element, "gather-candidates", &ret);

  if (!ret) {
    throw KurentoException (ICE_GATHER_CANDIDATES_ERROR,
                            "Error gathering candidates");
  }
}

void
WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate)
{
  gboolean ret;
  const char *cand_str = candidate->getCandidate().c_str ();
  const char *mid_str = candidate->getSdpMid().c_str ();
  guint8 sdp_m_line_index = candidate->getSdpMLineIndex ();
  KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str,
                          sdp_m_line_index);

  g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret);

  g_object_unref (cand);

  if (!ret) {
    throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate");
  }
}

MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
    &conf, std::shared_ptr<MediaPipeline>
    mediaPipeline) const
{
  return new WebRtcEndpointImpl (conf, mediaPipeline);
}

WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;

WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<|endoftext|>


<commit_before>#include "flint.h"
#include "nmod_mat.h"
#include<stdio.h>
#include<time.h>
#include<unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
using namespace std;
#define MMSI 2

size_t aflint_sprintf(char * s, const char * str, ...)
{
   va_list ap;
   size_t len = strlen(str);
   char * str2 = (char *)flint_malloc(len + 1);
   int w1 = 0, w2 = 0;
   void * w3;
   double d;
   ulong wu;
   slong w;
   int args, floating;
   size_t ret;

   /* deal with first substring */
   size_t n = strcspn(str, "%");
   strncpy(str2, str, n);
   str2[n] = '\0';
   ret = sprintf(s, "%s", str2);
   len -= n;
   str += n;

   va_start(ap, str);
   while (len) /* deal with fmt spec prefixed strings */
   {
      n = strcspn(str + 2, "%") + 2; /* be sure to skip a %% */
      strncpy(str2, str, n);
      str2[n] = '\0';
      switch (str[1])
      {
      case 'w':
         if (str[2] == 'x')
         {
            wu = (ulong) va_arg(ap, ulong);
            ret += sprintf(s + ret, WORD_FMT "x", wu);
            ret += sprintf(s + ret, "%s", str2 + 3);
         } else if (str[2] == 'u')
         {
            wu = (ulong) va_arg(ap, ulong);
            ret += sprintf(s + ret, WORD_FMT "u", wu);
            ret += sprintf(s + ret, "%s", str2 + 3);
         } else if (str[2] == 'd')
         {
            w = (slong) va_arg(ap, slong);
            ret += sprintf(s + ret, WORD_FMT "d", w);
            ret += sprintf(s + ret, "%s", str2 + 3);
         } else
         {
            w = (slong) va_arg(ap, slong);
            ret += sprintf(s + ret, WORD_FMT "d", w);
            ret += sprintf(s + ret, "%s", str2 + 2);
         }
         break;
         case '%':
            ret +=sprintf(s+ret,"%s",str2+1);
            break;
      default: /* pass to sprintf */
         args = parse_fmt(&floating, str2);
         if (args)
         {
            if (args == 3)
               w1 = va_arg(ap, int);
            if (args >= 2)
               w2 = va_arg(ap, int);
            if (floating)
            {
               d = va_arg(ap, double);
               if (args == 2)
                  ret += sprintf(s + ret, str2, w2, d);
               else if (args == 3)
                  ret += sprintf(s + ret, str2, w1, w2, d);
               else
                  ret += sprintf(s + ret, str2, d);
            } else
            {
               w3 = va_arg(ap, void *);
               if (args == 2)
                  ret += sprintf(s + ret, str2, w2, w3);
               else if (args == 3)
                  ret += sprintf(s + ret, str2, w1, w2, w3);
               else
                  ret += sprintf(s + ret, str2, w3);
            }
         } else ret += sprintf(s + ret,"%s",str2); /* zero args */
      }

      len -= n;
      str += n;
   }

   va_end(ap);
   flint_free(str2);

   return ret;
}

int main()
{
    nmod_mat_t A,B,C;
    mp_limb_t mod=1000000007;
    nmod_mat_init(A,MMSI,MMSI,mod);
    nmod_mat_init(B,MMSI,MMSI,mod);
    nmod_mat_init(C,MMSI,MMSI,mod);
    flint_rand_t st;
    flint_randinit(st);
    nmod_mat_randfull(A,st);
    nmod_mat_randfull(B,st);
    flint_randclear(st);

    //nmod_mat_print_pretty(A);flint_printf("\n\n");
    //nmod_mat_print_pretty(B);flint_printf("\n\n");
    nmod_mat_mul(B,A,A);
    nmod_mat_mul(C,B,A);
    nmod_mat_print_pretty(C);flint_printf("\n\n");
    //printf("%f\n",mul_time);
    nmod_mat_pow(C,A,3);
    nmod_mat_print_pretty(C);flint_printf("\n\n");
    nmod_mat_entry(C,0,0)=((nmod_mat_entry(A,0,0)*nmod_mat_entry(A,0,0))%1000000007) + ((nmod_mat_entry(A,0,1)*nmod_mat_entry(A,1,0))%1000000007);
    nmod_mat_entry(C,0,0)=nmod_mat_entry(C,0,0)%1000000007;
    nmod_mat_entry(C,0,1)=((nmod_mat_entry(A,0,0)*nmod_mat_entry(A,0,1))%1000000007) + ((nmod_mat_entry(A,0,1)*nmod_mat_entry(A,1,1))%1000000007);
    nmod_mat_entry(C,0,1)=nmod_mat_entry(C,0,1)%1000000007;
    nmod_mat_entry(C,1,0)=((nmod_mat_entry(A,1,0)*nmod_mat_entry(A,0,0))%1000000007) + ((nmod_mat_entry(A,1,1)*nmod_mat_entry(A,1,0))%1000000007);
    nmod_mat_entry(C,1,0)=nmod_mat_entry(C,1,0)%1000000007;
    nmod_mat_entry(C,1,1)=((nmod_mat_entry(A,1,0)*nmod_mat_entry(A,0,1))%1000000007) + ((nmod_mat_entry(A,1,1)*nmod_mat_entry(A,1,1))%1000000007);
    nmod_mat_entry(C,1,1)=nmod_mat_entry(C,1,1)%1000000007;
    nmod_mat_print_pretty(C);flint_printf("\n\n");
    return 0;
}
<commit_msg>Removed junk files<commit_after><|endoftext|>


<commit_before>/**
 * @file		compmanager.cpp
 * @brief		COSSB component manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 21
 * @details
 */

#include "manager.hpp"

namespace cossb {
namespace manager {

component_manager* component_manager::_instance = nullptr;

component_manager* component_manager::get()
{
	if(!_instance)
		_instance = new component_manager;
	return _instance;
}

void component_manager::destroy()
{
	if(_instance)
		delete _instance;
}

types::returntype component_manager::install(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::uninstall(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::run(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::stop(const char* component_name)
{
	return types::returntype::SUCCESS;
}

int component_manager::count()
{
	return 0;
}

} /* namespace manager */
} /* namespace cossb */
<commit_msg>refactor by singleton patter design<commit_after>/**
 * @file		compmanager.cpp
 * @brief		COSSB component manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 21
 * @details
 */

#include "manager.hpp"

namespace cossb {
namespace manager {

types::returntype component_manager::install(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::uninstall(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::run(const char* component_name)
{
	return types::returntype::SUCCESS;
}

types::returntype component_manager::stop(const char* component_name)
{
	return types::returntype::SUCCESS;
}

int component_manager::count()
{
	return 0;
}

} /* namespace manager */
} /* namespace cossb */
<|endoftext|>