<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <cstdlib>

// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
#include <TClonesArray.h>
//#include <Riostream.h>
//#include <TObjectTable.h>

// --- Analysis ---
#include "AliAnalysisTaskCaloTrackCorrelation.h"
#include "AliAnaCaloTrackCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliLog.h"

/// \cond CLASSIMP
ClassImp(AliAnalysisTaskCaloTrackCorrelation) ;
/// \endcond

//________________________________________________________________________
/// Default constructor.
//________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation() :
  AliAnalysisTaskSE(),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName(""),
  fCuts(0x0),
  fFirstEvent(0),
  fLastEvent(0),
  fStoreEventSummary(0)
{
}

//________________________________________________________________________________________
/// Default constructor.
//________________________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation(const char* name) :
  AliAnalysisTaskSE(name),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName(""),
  fCuts(0x0),
  fFirstEvent(0),
  fLastEvent(0),
  fStoreEventSummary(0)
{
  DefineOutput(1, TList::Class());
  DefineOutput(2, TList::Class());  // will contain cuts or local params
}

//_________________________________________________________________________
/// Destructor.
//_________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::~AliAnalysisTaskCaloTrackCorrelation()
{
  if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return;

  if (fOutputContainer)
  {
    fOutputContainer->Clear() ;
    delete fOutputContainer ;
  }

  if (fAna) delete fAna;
}

//_________________________________________________________________
/// Create the output container, recover it from the maker
/// (*AliAnaCaloTrackMaker fAna*) pointer.
//_________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserCreateOutputObjects()
{
  AliDebug(1,"Begin");

  // Get list of aod arrays, add each aod array to analysis frame
  TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches

  AliDebug(1,Form("n AOD branches %d",list->GetEntries()));

  // Put the delta AODs in output file, std or delta
  if((fAna->GetReader())->WriteDeltaAODToFile())
  {
    TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
    for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++)
    {
      TClonesArray * array = (TClonesArray*) list->At(iaod);
      if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
      else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
    }
  }

  // Histograms container
  OpenFile(1);
  fOutputContainer = fAna->GetOutputContainer();

  AliDebug(1,Form("n histograms %d",fOutputContainer->GetEntries()));

  fOutputContainer->SetOwner(kTRUE);

  AliDebug(1,"End");

  PostData(1,fOutputContainer);
}

//___________________________________________________
/// Local Initialization.
/// Call the Init to initialize the configuration of the analysis.
//___________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::LocalInit()
{
  Init();
}

//______________________________________________
/// Analysis configuration, if provided, and initialization.
//______________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Init()
{
  AliDebug(1,"Begin");

  if( fDebug >= 0 )
    (AliAnalysisManager::GetAnalysisManager())->AddClassDebug(this->ClassName(),fDebug);

  // Call configuration file if specified

  if (fConfigName.Length())
  {
    AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data()));
    gROOT->LoadMacro(fConfigName+".C");
    fAna = (AliAnaCaloTrackCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
  }

  if(!fAna)
  {
    AliFatal("Analysis maker pointer not initialized, no analysis specified, STOP!");
    return; // coverity
  }

  // Add different generator particles to PDG Data Base
  // to avoid problems when reading MC generator particles
  AliPDG::AddParticlesToPdgDataBase();

  // Set in the reader the name of the task in case is needed
  (fAna->GetReader())->SetTaskName(GetName());

  // Initialise analysis
  fAna->Init();

  // Delta AOD
  if((fAna->GetReader())->GetDeltaAODFileName()!="")
    AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());

  // Selected Trigger
  if(fAna->GetReader()->IsEventTriggerAtSEOn()) fAna->GetReader()->SetEventTriggerMask(GetCollisionCandidates());

  AliDebug(1,"End");
}

//______________________________________________________________________
/// Execute analysis for current event.
//______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserExec(Option_t */*option*/)
{
  if ( !fAna->IsEventProcessed() ) return;

  if ( (fLastEvent  > 0 && Entry() > fLastEvent )  ||
       (fFirstEvent > 0 && Entry() < fFirstEvent)     ) return ;

  AliDebug(1,Form("Begin event %d", (Int_t) Entry()));

  // Get the type of data, check if type is correct
  Int_t  datatype = fAna->GetReader()->GetDataType();
  if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
     datatype != AliCaloTrackReader::kMC)
  {
    AliError("Wrong type of data");
    return ;
  }

  fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());

  // Process event
  fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());

  PostData(1, fOutputContainer);

  AliDebug(1,"End");

  //gObjectTable->Print();
}

//_______________________________________________________________________
/// Terminate analysis. Do some plots (plotting not used so far).
//_______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Terminate(Option_t */*option*/)
{
  // Get merged histograms from the output container
  // Propagate histagrams to maker
  fAna->Terminate((TList*)GetOutputData(1));

  // Create cuts/param objects and publish to slot
  fCuts = fAna->GetListOfAnalysisCuts();
  fCuts ->SetOwner(kTRUE);

  // Post Data
  PostData(2, fCuts);
}

//__________________________________________________________
/// Put in the output some standard event summary histograms.
//__________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::FinishTaskOutput()
{
  if ( !fStoreEventSummary ) return ;

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();

  AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler());

  if (!inputH) return;

  TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics());
  TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0"));

  if ( histStat )
  {
    if ( histStat == histBin0 ) histBin0 = 0 ;

    histStat  = (TH2F*) histStat->Clone(Form("%s_%s",histStat->GetName(),"CaloTrackCorr"));

    fOutputContainer->Add(histStat);
  }

  if ( histBin0 )
  {
    histBin0  = (TH2F*) histBin0->Clone(Form("%s_%s",histBin0->GetName(),"CaloTrackCorr"));

    fOutputContainer->Add(histBin0);
  }
}

<commit_msg>add debug for event number and check event selection number<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <cstdlib>

// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
#include <TClonesArray.h>
//#include <Riostream.h>
//#include <TObjectTable.h>

// --- Analysis ---
#include "AliAnalysisTaskCaloTrackCorrelation.h"
#include "AliAnaCaloTrackCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliAODInputHandler.h"
#include "AliLog.h"

/// \cond CLASSIMP
ClassImp(AliAnalysisTaskCaloTrackCorrelation) ;
/// \endcond

//________________________________________________________________________
/// Default constructor.
//________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation() :
  AliAnalysisTaskSE(),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName(""),
  fCuts(0x0),
  fFirstEvent(0),
  fLastEvent(0),
  fStoreEventSummary(0)
{
}

//________________________________________________________________________________________
/// Default constructor.
//________________________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::AliAnalysisTaskCaloTrackCorrelation(const char* name) :
  AliAnalysisTaskSE(name),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName(""),
  fCuts(0x0),
  fFirstEvent(0),
  fLastEvent(0),
  fStoreEventSummary(0)
{
  DefineOutput(1, TList::Class());
  DefineOutput(2, TList::Class());  // will contain cuts or local params
}

//_________________________________________________________________________
/// Destructor.
//_________________________________________________________________________
AliAnalysisTaskCaloTrackCorrelation::~AliAnalysisTaskCaloTrackCorrelation()
{
  if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return;

  if (fOutputContainer)
  {
    fOutputContainer->Clear() ;
    delete fOutputContainer ;
  }

  if (fAna) delete fAna;
}

//_________________________________________________________________
/// Create the output container, recover it from the maker
/// (*AliAnaCaloTrackMaker fAna*) pointer.
//_________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserCreateOutputObjects()
{
  AliDebug(1,"Begin");

  // Get list of aod arrays, add each aod array to analysis frame
  TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches

  AliDebug(1,Form("n AOD branches %d",list->GetEntries()));

  // Put the delta AODs in output file, std or delta
  if((fAna->GetReader())->WriteDeltaAODToFile())
  {
    TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
    for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++)
    {
      TClonesArray * array = (TClonesArray*) list->At(iaod);
      if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
      else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
    }
  }

  // Histograms container
  OpenFile(1);
  fOutputContainer = fAna->GetOutputContainer();

  AliDebug(1,Form("n histograms %d",fOutputContainer->GetEntries()));

  fOutputContainer->SetOwner(kTRUE);

  AliDebug(1,"End");

  PostData(1,fOutputContainer);
}

//___________________________________________________
/// Local Initialization.
/// Call the Init to initialize the configuration of the analysis.
//___________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::LocalInit()
{
  Init();
}

//______________________________________________
/// Analysis configuration, if provided, and initialization.
//______________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Init()
{
  AliDebug(1,"Begin");

  if( fDebug >= 0 )
    (AliAnalysisManager::GetAnalysisManager())->AddClassDebug(this->ClassName(),fDebug);

  // Call configuration file if specified

  if (fConfigName.Length())
  {
    AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data()));
    gROOT->LoadMacro(fConfigName+".C");
    fAna = (AliAnaCaloTrackCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
  }

  if(!fAna)
  {
    AliFatal("Analysis maker pointer not initialized, no analysis specified, STOP!");
    return; // coverity
  }

  // Add different generator particles to PDG Data Base
  // to avoid problems when reading MC generator particles
  AliPDG::AddParticlesToPdgDataBase();

  // Set in the reader the name of the task in case is needed
  (fAna->GetReader())->SetTaskName(GetName());

  // Initialise analysis
  fAna->Init();

  // Delta AOD
  if((fAna->GetReader())->GetDeltaAODFileName()!="")
    AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());

  // Selected Trigger
  if(fAna->GetReader()->IsEventTriggerAtSEOn()) fAna->GetReader()->SetEventTriggerMask(GetCollisionCandidates());

  AliDebug(1,"End");
}

//______________________________________________________________________
/// Execute analysis for current event.
//______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::UserExec(Option_t */*option*/)
{
  if ( !fAna->IsEventProcessed() ) return;

  Int_t eventN = Entry();

  // Entry() does not work for AODs
  if ( eventN <= 0 )
  {
    AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>
    ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());

    if ( aodIH ) eventN = aodIH->GetReadEntry();
  }

  if ( (fLastEvent  > 0 && eventN > fLastEvent )  ||
       (fFirstEvent > 0 && eventN < fFirstEvent)     ) return ;

  AliDebug(1,Form("Begin: Event %d - Entry %d - (First,Last)=(%d,%d)",
                  eventN, (Int_t) Entry(), fFirstEvent, fLastEvent));

  //printf("AliAnalysisTaskCaloTrackCorrelation::UserExec() - Event %d - Entry %d - (First,Last)=(%d,%d) \n",
  //       eventN, (Int_t) Entry(), fFirstEvent, fLastEvent);

  // Get the type of data, check if type is correct
  Int_t  datatype = fAna->GetReader()->GetDataType();
  if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
     datatype != AliCaloTrackReader::kMC)
  {
    AliError("Wrong type of data");
    return ;
  }

  fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());

  // Process event
  fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());

  PostData(1, fOutputContainer);

  AliDebug(1,"End");

  //gObjectTable->Print();
}

//_______________________________________________________________________
/// Terminate analysis. Do some plots (plotting not used so far).
//_______________________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::Terminate(Option_t */*option*/)
{
  // Get merged histograms from the output container
  // Propagate histagrams to maker
  fAna->Terminate((TList*)GetOutputData(1));

  // Create cuts/param objects and publish to slot
  fCuts = fAna->GetListOfAnalysisCuts();
  fCuts ->SetOwner(kTRUE);

  // Post Data
  PostData(2, fCuts);
}

//__________________________________________________________
/// Put in the output some standard event summary histograms.
//__________________________________________________________
void AliAnalysisTaskCaloTrackCorrelation::FinishTaskOutput()
{
  if ( !fStoreEventSummary ) return ;

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();

  AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler());

  if (!inputH) return;

  TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics());
  TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0"));

  if ( histStat )
  {
    if ( histStat == histBin0 ) histBin0 = 0 ;

    histStat  = (TH2F*) histStat->Clone(Form("%s_%s",histStat->GetName(),"CaloTrackCorr"));

    fOutputContainer->Add(histStat);
  }

  if ( histBin0 )
  {
    histBin0  = (TH2F*) histBin0->Clone(Form("%s_%s",histBin0->GetName(),"CaloTrackCorr"));

    fOutputContainer->Add(histBin0);
  }
}

<|endoftext|>


<commit_before>
#include "XXX/kernel.h"
#include "XXX/topic.h"
#include "XXX/wamp_session.h"
#include "XXX/wamp_connector.h"
#include "XXX/websocket_protocol.h"
#include "XXX/rawsocket_protocol.h"

#include <iostream>

using namespace XXX;

struct timeout_error : public std::runtime_error
{
  timeout_error()
    : std::runtime_error("timeout_error"){}

};

void make_connection()
{
  auto __logger = logger::stdlog(std::cout,
                                 logger::levels_upto(logger::eError), 0);

  std::unique_ptr<kernel> the_kernel( new XXX::kernel({}, __logger) );
  the_kernel->start();

  std::promise<void> promise_on_close;

  auto wconn = wamp_connector::create(
    the_kernel.get(),
    "10.0.0.0", "55555",
    false,
    [&promise_on_close](XXX::session_handle, bool is_open){
      if (!is_open)
        promise_on_close.set_value();
    }
    );

  auto connect_future = wconn->get_future();
  auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));

  if (connect_status == std::future_status::timeout)
  {
    throw timeout_error();
  }
  else
  {
    throw std::runtime_error("call should have timed-out");
  }

}

int run_test()
{
  try
  {
    make_connection();
  }
  catch (timeout_error&)
  {
    // OK, this is what we expected
    return 0;
  }

  return 1; // unexpected
}

int main()
{
  try
  {
    for (int i =0; i < 100; i++)
    {
      std::cout << "."<< std::flush;
      run_test();
    }
    return 0;
  }
  catch (std::exception& e)
  {
    std::cerr << "error: " << e.what() << std::endl;
    return 1;
  }
}
<commit_msg>additional test<commit_after>#include "XXX/kernel.h"
#include "XXX/topic.h"
#include "XXX/wamp_session.h"
#include "XXX/wamp_connector.h"
#include "XXX/websocket_protocol.h"
#include "XXX/rawsocket_protocol.h"

#include <iostream>

using namespace XXX;

enum test_outcome
{
  e_expected,
  e_unexpected
};

test_outcome throw_on_invalid_address()
{
  kernel the_kernel( {}, logger::nolog() );
  the_kernel.start();

  auto wconn = wamp_connector::create(
    &the_kernel,
    "0.42.42.42", /* Invalid argument */
    "55555",
    false,
    [](XXX::session_handle, bool){});

  auto connect_future = wconn->get_future();
  auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));

  std::shared_ptr<wamp_session> session;

  if (connect_status == std::future_status::ready)
    try
    {
      session = connect_future.get();
    }
    catch (std::exception& e)
    {
      return e_expected;
    }

  return e_unexpected;
}

test_outcome timeout_for_unreachable_connect()
{
  std::unique_ptr<kernel> the_kernel( new XXX::kernel({}, logger::nolog() ) );
  the_kernel->start();

  auto wconn = wamp_connector::create(
    the_kernel.get(),
    "10.255.255.1", "55555",
    false,
    [](XXX::session_handle, bool){});

  auto connect_future = wconn->get_future();

  auto connect_status = connect_future.wait_for(std::chrono::milliseconds(50));

  if (connect_status == std::future_status::timeout)
    return e_expected;

  return e_unexpected;
}

#define TEST( X )                                       \
  if ( X () != e_expected)                              \
  {                                                     \
    std::cout << "FAIL for:  " << #X << std::endl;      \
    result |= 1;                                        \
  }

/* Note, these tests will only succeed if the system has access to a network. */

int main()
{
  int result = 0;

  for (int i =0; i < 20; i++)
  {
    std::cout << "."<< std::flush;
    TEST( throw_on_invalid_address );
    TEST( timeout_for_unreachable_connect );
  }

  /* We let any uncaught exceptions (which are not expected) to terminate main,
   * and cause test failure. */
  return result;
}
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "geo_location.h"

using vespalib::geo::ZCurve;

namespace search::common {

namespace {

ZCurve::BoundingBox to_z(GeoLocation::Box box) {
    return ZCurve::BoundingBox(box.x.low, box.x.high,
                               box.y.low, box.y.high);
}

GeoLocation::Box
adjust_bounding_box(GeoLocation::Box orig, GeoLocation::Point point, uint32_t radius, GeoLocation::Aspect x_aspect)
{
    if (radius == GeoLocation::radius_inf) {
        // only happens if GeoLocation is explicitly constructed with "infinite" radius
        return orig;
    }
    uint32_t maxdx = radius;
    if (x_aspect.active()) {
        // x_aspect is a 32-bit fixed-point number in range [0,1]
        // so this implements maxdx = ceil(radius/x_aspect)
        uint64_t maxdx2 = ((static_cast<uint64_t>(radius) << 32) + 0xffffffffu) / x_aspect.multiplier;
        if (maxdx2 >= 0xffffffffu) {
            maxdx = 0xffffffffu;
        } else {
            maxdx = static_cast<uint32_t>(maxdx2);
        }
    }
    // implied limits from radius and point:
    int64_t implied_max_x = int64_t(point.x) + int64_t(maxdx);
    int64_t implied_min_x = int64_t(point.x) - int64_t(maxdx);

    int64_t implied_max_y = int64_t(point.y) + int64_t(radius);
    int64_t implied_min_y = int64_t(point.y) - int64_t(radius);

    int32_t max_x = orig.x.high;
    int32_t min_x = orig.x.low;

    int32_t max_y = orig.y.high;
    int32_t min_y = orig.y.low;

    if (implied_max_x < max_x) max_x = implied_max_x;
    if (implied_min_x > min_x) min_x = implied_min_x;

    if (implied_max_y < max_y) max_y = implied_max_y;
    if (implied_min_y > min_y) min_y = implied_min_y;

    return GeoLocation::Box{GeoLocation::Range{min_x, max_x},
                            GeoLocation::Range{min_y, max_y}};
}

} // namespace <unnamed>

GeoLocation::GeoLocation()
  : has_point(false),
    point{0, 0},
    radius(radius_inf),
    x_aspect(),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p, Aspect xa)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(xa),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p, uint32_t r)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(),
    bounding_box(adjust_bounding_box(no_box, p, r, Aspect())),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Point p, uint32_t r, Aspect xa)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(xa),
    bounding_box(adjust_bounding_box(no_box, p, r, xa)),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b)
  : has_point(false),
    point{0, 0},
    radius(radius_inf),
    x_aspect(),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, Aspect xa)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(xa),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, uint32_t r)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(),
    bounding_box(adjust_bounding_box(b, p, r, Aspect())),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, uint32_t r, Aspect xa)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(xa),
    bounding_box(adjust_bounding_box(b, p, r, xa)),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

uint64_t GeoLocation::sq_distance_to(Point p) const {
    if (has_point) {
        uint64_t dx = (p.x > point.x) ? (p.x - point.x) : (point.x - p.x);
        if (x_aspect.active()) {
            // x_aspect is a 32-bit fixed-point number in range [0,1]
            // this implements dx = (dx * x_aspect)
            dx = (dx * x_aspect.multiplier) >> 32;
        }
        uint64_t dy = (p.y > point.y) ? (p.y - point.y) : (point.y - p.y);
        return dx*dx + dy*dy;
    }
    return 0;
}

bool GeoLocation::inside_limit(Point p) const {
    if (p.x < bounding_box.x.low) return false;
    if (p.x > bounding_box.x.high) return false;

    if (p.y < bounding_box.y.low) return false;
    if (p.y > bounding_box.y.high) return false;

    uint64_t sq_dist = sq_distance_to(p);
    return sq_dist <= _sq_radius;
}

} // namespace search::common
<commit_msg>fix undefined behavior in geo distance<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "geo_location.h"

using vespalib::geo::ZCurve;

namespace search::common {

namespace {

uint64_t abs_diff(int32_t a, int32_t b) {
    return (a > b)
        ? (int64_t(a) - int64_t(b))
        : (int64_t(b) - int64_t(a));
}

ZCurve::BoundingBox to_z(GeoLocation::Box box) {
    return ZCurve::BoundingBox(box.x.low, box.x.high,
                               box.y.low, box.y.high);
}

GeoLocation::Box
adjust_bounding_box(GeoLocation::Box orig, GeoLocation::Point point, uint32_t radius, GeoLocation::Aspect x_aspect)
{
    if (radius == GeoLocation::radius_inf) {
        // only happens if GeoLocation is explicitly constructed with "infinite" radius
        return orig;
    }
    uint32_t maxdx = radius;
    if (x_aspect.active()) {
        // x_aspect is a 32-bit fixed-point number in range [0,1]
        // so this implements maxdx = ceil(radius/x_aspect)
        uint64_t maxdx2 = ((static_cast<uint64_t>(radius) << 32) + 0xffffffffu) / x_aspect.multiplier;
        if (maxdx2 >= 0xffffffffu) {
            maxdx = 0xffffffffu;
        } else {
            maxdx = static_cast<uint32_t>(maxdx2);
        }
    }
    // implied limits from radius and point:
    int64_t implied_max_x = int64_t(point.x) + int64_t(maxdx);
    int64_t implied_min_x = int64_t(point.x) - int64_t(maxdx);

    int64_t implied_max_y = int64_t(point.y) + int64_t(radius);
    int64_t implied_min_y = int64_t(point.y) - int64_t(radius);

    int32_t max_x = orig.x.high;
    int32_t min_x = orig.x.low;

    int32_t max_y = orig.y.high;
    int32_t min_y = orig.y.low;

    if (implied_max_x < max_x) max_x = implied_max_x;
    if (implied_min_x > min_x) min_x = implied_min_x;

    if (implied_max_y < max_y) max_y = implied_max_y;
    if (implied_min_y > min_y) min_y = implied_min_y;

    return GeoLocation::Box{GeoLocation::Range{min_x, max_x},
                            GeoLocation::Range{min_y, max_y}};
}

} // namespace <unnamed>

GeoLocation::GeoLocation()
  : has_point(false),
    point{0, 0},
    radius(radius_inf),
    x_aspect(),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p, Aspect xa)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(xa),
    bounding_box(no_box),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(no_box))
{}

GeoLocation::GeoLocation(Point p, uint32_t r)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(),
    bounding_box(adjust_bounding_box(no_box, p, r, Aspect())),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Point p, uint32_t r, Aspect xa)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(xa),
    bounding_box(adjust_bounding_box(no_box, p, r, xa)),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b)
  : has_point(false),
    point{0, 0},
    radius(radius_inf),
    x_aspect(),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, Aspect xa)
  : has_point(true),
    point(p),
    radius(radius_inf),
    x_aspect(xa),
    bounding_box(b),
    _sq_radius(sq_radius_inf),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, uint32_t r)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(),
    bounding_box(adjust_bounding_box(b, p, r, Aspect())),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

GeoLocation::GeoLocation(Box b, Point p, uint32_t r, Aspect xa)
  : has_point(true),
    point(p),
    radius(r),
    x_aspect(xa),
    bounding_box(adjust_bounding_box(b, p, r, xa)),
    _sq_radius(uint64_t(r) * uint64_t(r)),
    _z_bounding_box(to_z(bounding_box))
{}

uint64_t GeoLocation::sq_distance_to(Point p) const {
    if (has_point) {
        uint64_t dx = abs_diff(p.x, point.x);
        if (x_aspect.active()) {
            // x_aspect is a 32-bit fixed-point number in range [0,1]
            // this implements dx = (dx * x_aspect)
            dx = (dx * x_aspect.multiplier) >> 32;
        }
        uint64_t dy = abs_diff(p.y, point.y);
        return dx*dx + dy*dy;
    }
    return 0;
}

bool GeoLocation::inside_limit(Point p) const {
    if (p.x < bounding_box.x.low) return false;
    if (p.x > bounding_box.x.high) return false;

    if (p.y < bounding_box.y.low) return false;
    if (p.y > bounding_box.y.high) return false;

    uint64_t sq_dist = sq_distance_to(p);
    return sq_dist <= _sq_radius;
}

} // namespace search::common
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/span.hpp>
#include <type_traits>
#include <iterator>

namespace agency
{
namespace experimental
{

// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<typename Container::value_type> all(Container& c)
{
  return span<typename Container::value_type>(c);
}

// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<const typename Container::value_type> all(const Container& c)
{
  return span<const typename Container::value_type>(c);
}

template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<T,N> all(array<T,N>& a)
{
  return span<T,N>(a);
}

template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<const T,N> all(const array<T,N>& a)
{
  return span<const T,N>(a);
}

// spans are already views, so don't wrap them
// XXX maybe should put this in span.hpp
template<class ElementType, std::ptrdiff_t Extent>
__AGENCY_ANNOTATION
span<ElementType,Extent> all(span<ElementType,Extent> s)
{
  return s;
}

template<class Iterator, class Sentinel = Iterator>
class range_view
{
  public:
    using iterator = Iterator;
    using sentinel = Sentinel;

    __AGENCY_ANNOTATION
    range_view(iterator begin, sentinel end)
      : begin_(begin),
        end_(end)
    {}

    __AGENCY_ANNOTATION
    iterator begin() const
    {
      return begin_;
    }

    __AGENCY_ANNOTATION
    sentinel end() const
    {
      return end_;
    }

    // "drops" the first n elements of the range by advancing the begin iterator n times
    __AGENCY_ANNOTATION
    void drop(typename std::iterator_traits<iterator>::difference_type n)
    {
      begin_ += n;
    }

  private:
    iterator begin_;
    sentinel end_;
};

// range_views are already views, so don't wrap them
template<class Iterator, class Sentinel>
__AGENCY_ANNOTATION
range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v)
{
  return v;
}

namespace detail
{

template<class Range>
using range_iterator_t = decltype(std::declval<Range*>()->begin());

template<class Range>
using range_sentinel_t = decltype(std::declval<Range*>()->end());

template<class Range>
using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>;

template<class Range>
using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>;

template<class Range>
using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type;

template<class Range>
using range_value_t = typename std::iterator_traits<range_iterator_t<Range>>::value_type;

} // end detail

template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
  make_range_view(Range&& rng)
{
  return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end());
}

// create a view of the given range and drop the first n elements from the view
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
  drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n)
{
  auto result = make_range_view(rng);
  result.drop(n);
  return result;
}

} // end experimental
} // end agency

<commit_msg>Add experimental::detail::decay_range_difference_t<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/span.hpp>
#include <type_traits>
#include <iterator>

namespace agency
{
namespace experimental
{

// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<typename Container::value_type> all(Container& c)
{
  return span<typename Container::value_type>(c);
}

// XXX this is only valid for contiguous containers
template<class Container>
__AGENCY_ANNOTATION
span<const typename Container::value_type> all(const Container& c)
{
  return span<const typename Container::value_type>(c);
}

template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<T,N> all(array<T,N>& a)
{
  return span<T,N>(a);
}

template<class T, std::size_t N>
__AGENCY_ANNOTATION
span<const T,N> all(const array<T,N>& a)
{
  return span<const T,N>(a);
}

// spans are already views, so don't wrap them
// XXX maybe should put this in span.hpp
template<class ElementType, std::ptrdiff_t Extent>
__AGENCY_ANNOTATION
span<ElementType,Extent> all(span<ElementType,Extent> s)
{
  return s;
}

template<class Iterator, class Sentinel = Iterator>
class range_view
{
  public:
    using iterator = Iterator;
    using sentinel = Sentinel;

    __AGENCY_ANNOTATION
    range_view(iterator begin, sentinel end)
      : begin_(begin),
        end_(end)
    {}

    __AGENCY_ANNOTATION
    iterator begin() const
    {
      return begin_;
    }

    __AGENCY_ANNOTATION
    sentinel end() const
    {
      return end_;
    }

    // "drops" the first n elements of the range by advancing the begin iterator n times
    __AGENCY_ANNOTATION
    void drop(typename std::iterator_traits<iterator>::difference_type n)
    {
      begin_ += n;
    }

  private:
    iterator begin_;
    sentinel end_;
};

// range_views are already views, so don't wrap them
template<class Iterator, class Sentinel>
__AGENCY_ANNOTATION
range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v)
{
  return v;
}

namespace detail
{

template<class Range>
using range_iterator_t = decltype(std::declval<Range*>()->begin());

template<class Range>
using range_sentinel_t = decltype(std::declval<Range*>()->end());

template<class Range>
using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type;

template<class Range>
using range_value_t = typename std::iterator_traits<range_iterator_t<Range>>::value_type;

template<class Range>
using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>;

template<class Range>
using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>;

template<class Range>
using decay_range_difference_t = range_difference_t<typename std::decay<Range>::type>;

} // end detail

template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
  make_range_view(Range&& rng)
{
  return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end());
}

// create a view of the given range and drop the first n elements from the view
template<class Range>
__AGENCY_ANNOTATION
range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>
  drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n)
{
  auto result = make_range_view(rng);
  result.drop(n);
  return result;
}

} // end experimental
} // end agency

<|endoftext|>


<commit_before>#include<iostream.h>
#include<conio.h>
#include<dos.h>
char s[3][3]={"   ","   ","   "};
char p1[15],p2[15]="COMPUTER";
<commit_msg>Create board<commit_after>#include<iostream.h>
#include<conio.h>
#include<dos.h>
char s[3][3]={"123","456","789"};
char p1[15],p2[15]="COMPUTER";

void board()
{
	clrscr();
	cout<<"The block # sequence is as follows:-\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				     "<<s[0][0]<<"     |     "<<s[0][1]<<"     |     "<<s[0][2]<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				___________|___________|___________"<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				     "<<s[1][0]<<"     |     "<<s[1][1]<<"     |     "<<s[1][2]<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				___________|___________|___________"<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				     "<<s[2][0]<<"     |     "<<s[2][1]<<"     |     "<<s[2][2]<<"\n";
	cout<<"				           |           |      "<<"\n";
	cout<<"				           |           |      "<<"\n\n\n\n\n\n";
}

void main()
{
	board();
	getch();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import "SynchronousEventBeat.h"

namespace facebook {
namespace react {

SynchronousEventBeat::SynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void SynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  assert(delegate == this);
  lockExecutorAndBeat();
}

void SynchronousEventBeat::induce() const {
  if (!this->isRequested_) {
    return;
  }

  if (uiRunLoopObserver_->isOnRunLoopThread()) {
    this->lockExecutorAndBeat();
  }
}

void SynchronousEventBeat::lockExecutorAndBeat() const {
  if (!this->isRequested_) {
    return;
  }

  executeSynchronouslyOnSameThread_CAN_DEADLOCK(
      runtimeExecutor_, [this](jsi::Runtime &runtime) { beat(runtime); });
}

} // namespace react
} // namespace facebook
<commit_msg>Fabric: Replace #import statement in SynchronousEventBeat (#29885)<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "SynchronousEventBeat.h"

namespace facebook {
namespace react {

SynchronousEventBeat::SynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void SynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  assert(delegate == this);
  lockExecutorAndBeat();
}

void SynchronousEventBeat::induce() const {
  if (!this->isRequested_) {
    return;
  }

  if (uiRunLoopObserver_->isOnRunLoopThread()) {
    this->lockExecutorAndBeat();
  }
}

void SynchronousEventBeat::lockExecutorAndBeat() const {
  if (!this->isRequested_) {
    return;
  }

  executeSynchronouslyOnSameThread_CAN_DEADLOCK(
      runtimeExecutor_, [this](jsi::Runtime &runtime) { beat(runtime); });
}

} // namespace react
} // namespace facebook
<|endoftext|>


<commit_before>#ifndef _RATIONAL_H
#define _RATIONAL_H

#include <cmath>
#include <cstddef>
#include <iosfwd>
#include <stdexcept>
#include <type_traits>
#include <limits>

#ifndef RATIONAL_NCONSTEXPR
#define CONSTEXPR constexpr
#else
#define CONSTEXPR /* not supported */
#endif

namespace rational {

    struct NoReduceTag {};

    struct DivideByZeroException : public std::runtime_error {
        DivideByZeroException() noexcept :
            runtime_error("Division by zero is undefined.")
        {  }
    };

    struct OverflowException : public std::runtime_error {
        OverflowException() noexcept :
            runtime_error("Arithmetic operation resulted in an overflow.")
        {  }
    };

    template<class T>
    CONSTEXPR T cpow(const T base, unsigned const exponent) noexcept
    {
        return (exponent == 0) ? 1 : (base * pow(base, exponent-1));
    }

    template<class T>
    CONSTEXPR unsigned pow10_cap(T x) noexcept
    {
        unsigned pow10 = 0;
        x = x > T(0) ? x : -x;
        do {
            ++pow10;
            x /= 10;
        } while(x > 1);
        return pow10;
    }

    template<class T>
    T gcd(T a, T b) noexcept {
        if(a < T(0)) a = -a;
        if(b < T(0)) b = -b;
        while(b != T(0)) {
            a %= b;
            if(a == T(0)) {
                return b;
            }
            b %= a;
        }
        return a;
    }

    template<class T>
    class Ratio {
    public:

        static_assert(std::is_integral<T>::value, "Ratio<T>: T must meet the requirements of Integral");

        CONSTEXPR Ratio() noexcept :
            numer_(0),
            denom_(1)
        {  }

        template<class U>
        CONSTEXPR Ratio(const U u) noexcept :
            Ratio(T(u), T(1), NoReduceTag())
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::Ratio<U>(const U): U must meet the requirements of Convertible to T.");
        }

        Ratio(const float u, const unsigned prec) :
            Ratio(static_cast<std::ptrdiff_t>(u * cpow(10, prec)), cpow(10, prec))
        {
            if((u > 0 && u > this->numer_)
                || (u < 0 && u < this->numer_)) {
                throw OverflowException();
            }
        }

        Ratio(const T numer, const T denom) noexcept :
            numer_(numer),
            denom_(denom)
        {
            if(denom == T(0)) {
                throw DivideByZeroException();
            }
            Ratio<T> ret(numer, denom, NoReduceTag());
            ret.reduce();
            *this = ret;
        }

        CONSTEXPR Ratio(const T numer, const T denom, NoReduceTag) noexcept :
            numer_(numer),
            denom_(denom)
        {  }

        CONSTEXPR Ratio(const Ratio<T>& rat) noexcept :
            numer_(rat.numer_),
            denom_(rat.denom_)
        {  }

        CONSTEXPR Ratio& operator=(const Ratio<T>& rat) noexcept
        {
            this->numer_ = rat.numer_;
            this->denom_ = rat.denom_;
            return *this;
        }

        template<class U>
        CONSTEXPR Ratio(const Ratio<U>& rat) noexcept :
            numer_(rat.numer_),
            denom_(rat.denom_)
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::Ratio<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
        }

        template<class U>
        Ratio& operator=(const Ratio<U>& rat) noexcept
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::operator=<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
            this->numer_ = rat.numer_;
            this->denom_ = rat.denom_;
            return *this;
        }

        CONSTEXPR T to_integer() const noexcept
        {
            return (this->numer_ / this->denom_);
        }

        template<class Float = float>
        CONSTEXPR Float to_float() const noexcept
        {
            static_assert(std::is_constructible<Float, T>::value,
                "Ratio<T>::to_floating<Float>(): T must meet the requirements of Convertible to Float.");
            return Float(Float(this->numer_) / Float(this->denom_));
        }

        const T& numer() const noexcept
        {
            return this->numer_;
        }

        const T& denom() const noexcept
        {
            return this->denom_;
        }

        bool is_integer() const noexcept
        {
            return this->denom_ == T(1);
        }

        void reduce() noexcept
        {
            T g = gcd(this->numer_, this->denom_);

            this->numer_ = this->numer_ / g;
            this->denom_ = this->denom_ / g;

            if(this->denom_ < T(0)) {
                this->numer_ = T(0) - this->numer_;
                this->denom_ = T(0) - this->denom_;
            }
        }

        Ratio<T> reduced() const noexcept
        {
            Ratio<T> ret(*this);
            ret.reduce();
            return ret;
        }

        Ratio<T> floor() const noexcept
        {
            if(*this < Ratio<T>(0)) {
                T one (1);
                return Ratio<T>((this->numer_ - this->denom_ + one) / this->denom_);
            } else {
                return Ratio<T>(this->numer_ / this->denom_);
            }
        }

        Ratio<T> ceil() const noexcept
        {
            if(*this < Ratio<T>(0)) {
                return Ratio<T>(this->numer_ / this->denom_);
            } else {
                T one (1);
                return Ratio<T>((this->numer_ + this->denom_ - one) / this->denom_);
            }
        }

        Ratio<T> round() const noexcept
        {
            const Ratio<T> zero(0);
            const T one(1);
            const T two(one + one);

            Ratio<T> fractional = this->fract();
            if(fractional < zero) {
                fractional = zero - fractional;
            }

            const bool half_or_larger;
            if(fractional.denom() % 2 == 0) {
                half_or_larger = fractional.numer_ >= fractional.denom_ / two;
            } else {
                half_or_larger = fractional.numer_ >= (fractional.denom_ / two) + one;
            }

            if(half_or_larger) {
                Ratio<T> one(1);
                if(*this > Ratio<T>(0)) {
                    return this->trunc() + one;
                } else {
                    return this->trunc() - one;
                }
            } else {
                return this->trunc();
            }
        }

        Ratio<T> trunc() const noexcept
        {
            return Ratio<T>(this->numer_ / this->denom_);
        }

        Ratio<T> fract() const noexcept
        {
            return Ratio<T>(this->numer_ % this->denom_, this->denom_, NoReduceTag());
        }

        Ratio<T> pow(const Ratio<T>& r, int expon) const noexcept
        {
            if(expon == 0) {
                return Ratio<T>(1);
            } else if(expon < 0) {
                return std::pow(recip(r), -expon);
            } else {
                return Ratio<T>(std::pow(r.numer(), expon), std::pow(r.numer(), expon));
            }
        }

        bool is_zero() const noexcept
        {
            return (this->numer_ == 0);
        }

        bool is_positive() const noexcept
        {
            return (this->numer_ > 0);
        }

        bool is_negative() const noexcept
        {
            return (this->numer_ < 0);
        }

        static CONSTEXPR Ratio<T> zero() noexcept
        {
            return Ratio<T>(0, 1, NoReduceTag());
        }

        static CONSTEXPR Ratio<T> one() noexcept
        {
            return Ratio<T>(1, 1, NoReduceTag());
        }

        static CONSTEXPR Ratio<T> pi() noexcept
        {
            return Ratio<T>(6283, 2000, NoReduceTag());
        }

        Ratio<T> abs() const noexcept
        {
            return (this->is_positive() || this->is_zero() ? *this : -*this);
        }

        Ratio<T> abs_sub(const Ratio<T>& rhs) const noexcept
        {
            return abs(*this - rhs);
        }

        T signum() const noexcept
        {
            if(this->is_zero()) {
                return T(0);
            } else if(this->is_positive()) {
                return T(1);
            } else {
                return T(-1);
            }
        }

        template<class U>
        explicit CONSTEXPR operator Ratio<U>() const noexcept
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::operator Ratio<U>(): T must meet the requirements of ImplicitlyConvertible to U.");
            return Ratio<U>(U(this->numer_), U(this->denom_), NoReduceTag());
        }

        template<class U>
        friend class Ratio;

    private:

        T numer_;
        T denom_;

    };

    template<class T>
    Ratio<T> make_ratio(const T& num) noexcept
    {
        return Ratio<T>(num);
    }

    template<class T>
    Ratio<T> make_ratio(const T& numer, const T& denom) noexcept
    {
        return Ratio<T>(numer, denom);
    }

    template<class T>
    Ratio<T> operator+(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) + (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator-(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) - (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator%(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) % (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator*(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator/(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return make_ratio((lhs.numer() * rhs.denom()), (lhs.denom() * rhs.numer()));
    }

    template<class T>
    Ratio<T> operator+=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs + rhs;
    }

    template<class T>
    Ratio<T> operator-=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs - rhs;
    }

    template<class T>
    Ratio<T> operator*=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs * rhs;
    }

    template<class T>
    Ratio<T> operator/=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs / rhs;
    }

    template<class T>
    Ratio<T> operator%=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs % rhs;
    }

    template<class T>
    Ratio<T> operator+(const Ratio<T>& rat) noexcept
    {
        return Ratio<T>(rat);
    }

    template<class T>
    Ratio<T> operator-(const Ratio<T>& rat) noexcept
    {
        return Ratio<T>(-rat.numer(), rat.denom(), NoReduceTag());
    }

    template<class T>
    bool operator==(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (lhs.numer() * lhs.denom()) == (rhs.numer() * rhs.denom());
    }

    template<class T>
    bool operator!=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs == rhs);
    }

    template<class T>
    bool operator>(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (lhs.numer() * lhs.denom()) > (rhs.numer() * rhs.denom());
    }

    template<class T>
    bool operator<(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (rhs > lhs);
    }

    template<class T>
    bool operator<=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs > rhs);
    }

    template<class T>
    bool operator>=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs < rhs);
    }

    template<class T>
    Ratio<T>& operator++(Ratio<T>& rat) noexcept
    {
        return rat = rat + Ratio<T>(1);;
    }

    template<class T>
    Ratio<T>& operator--(Ratio<T>& rat) noexcept
    {
        return rat = rat - Ratio<T>(1);
    }

    template<class T>
    Ratio<T> operator++(Ratio<T>& rat, int) noexcept
    {
        Ratio<T> cpy = rat;
        ++rat;
        return cpy;
    }

    template<class T>
    Ratio<T> operator--(Ratio<T>& rat, int) noexcept
    {
        Ratio<T> cpy = rat;
        --rat;
        return cpy;
    }

    typedef Ratio<std::ptrdiff_t> Rational;
    typedef Ratio<std::int32_t> Rational32;
    typedef Ratio<std::int64_t> Rational64;

    namespace literals {

        CONSTEXPR Rational operator"" _m(const unsigned long long int n) noexcept
        {
            return Rational(n, 1, NoReduceTag());
        }

        CONSTEXPR Rational operator"" _M(const unsigned long long int n) noexcept
        {
            return Rational(n, 1, NoReduceTag());
        }

    } // namespace literals

    template<class T>
    std::ostream& operator<<(std::ostream& os, Ratio<T> x)
    {
        return os << x.numer() << '/' << x.denom();
    }

    template<class T>
    std::istream& operator>>(std::istream& is, Ratio<T>& x)
    {
        T numer;
        T denom;
        std::scanf("%ld/%ld", &numer, &denom);
        x = Ratio<T>(numer, denom);
        return is;
    }

} // namespace rational

#endif<commit_msg>Changed Ratio<T>(float val, unsigned int prec) to from_float and renamed literal overloads to _r and _R respectively.<commit_after>#ifndef _RATIONAL_H
#define _RATIONAL_H

#include <cmath>
#include <cstddef>
#include <iosfwd>
#include <stdexcept>
#include <type_traits>
#include <limits>

#ifndef RATIONAL_NCONSTEXPR
#define CONSTEXPR constexpr
#else
#define CONSTEXPR /* not supported */
#endif

namespace rational {

    struct NoReduceTag {};

    struct DivideByZeroException : public std::runtime_error {
        DivideByZeroException() noexcept :
            runtime_error("Division by zero is undefined.")
        {  }
    };

    struct OverflowException : public std::runtime_error {
        OverflowException() noexcept :
            runtime_error("Arithmetic operation resulted in an overflow.")
        {  }
    };

    template<class T>
    CONSTEXPR T cpow(const T base, unsigned const exponent) noexcept
    {
        return (exponent == 0) ? 1 : (base * pow(base, exponent-1));
    }

    template<class T>
    CONSTEXPR unsigned pow10_cap(T x) noexcept
    {
        unsigned pow10 = 0;
        x = x > T(0) ? x : -x;
        do {
            ++pow10;
            x /= 10;
        } while(x > 1);
        return pow10;
    }

    template<class T>
    T gcd(T a, T b) noexcept {
        if(a < T(0)) a = -a;
        if(b < T(0)) b = -b;
        while(b != T(0)) {
            a %= b;
            if(a == T(0)) {
                return b;
            }
            b %= a;
        }
        return a;
    }

    template<class T>
    class Ratio {
    public:

        static_assert(std::is_integral<T>::value, "Ratio<T>: T must meet the requirements of Integral");

        CONSTEXPR Ratio() noexcept :
            numer_(0),
            denom_(1)
        {  }

        template<class U>
        CONSTEXPR Ratio(const U& u) noexcept :
            Ratio(T(u), T(1), NoReduceTag())
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::Ratio<U>(const U): U must meet the requirements of Convertible to T.");
        }

        Ratio(const T& numer, const T& denom) noexcept :
            numer_(numer),
            denom_(denom)
        {
            if(denom == T(0)) {
                throw DivideByZeroException();
            }
            Ratio<T> ret(numer, denom, NoReduceTag());
            ret.reduce();
            *this = ret;
        }

        CONSTEXPR Ratio(const T& numer, const T& denom, NoReduceTag) noexcept :
            numer_(numer),
            denom_(denom)
        {  }

        CONSTEXPR Ratio(const Ratio<T>& rat) noexcept :
            numer_(rat.numer_),
            denom_(rat.denom_)
        {  }

        CONSTEXPR Ratio& operator=(const Ratio<T>& rat) noexcept
        {
            this->numer_ = rat.numer_;
            this->denom_ = rat.denom_;
            return *this;
        }

        template<class U>
        CONSTEXPR Ratio(const Ratio<U>& rat) noexcept :
            numer_(rat.numer_),
            denom_(rat.denom_)
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::Ratio<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
        }

        template<class U>
        Ratio& operator=(const Ratio<U>& rat) noexcept
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::operator=<U>(const Ratio<U>&): U must meet the requirements of ImplicitlyConvertible to T.");
            this->numer_ = rat.numer_;
            this->denom_ = rat.denom_;
            return *this;
        }

        CONSTEXPR T to_integer() const noexcept
        {
            return (this->numer_ / this->denom_);
        }

        template<class Float = float>
        CONSTEXPR Float to_float() const noexcept
        {
            static_assert(std::is_constructible<Float, T>::value,
                "Ratio<T>::to_floating<Float>(): T must meet the requirements of Convertible to Float.");
            return Float(Float(this->numer_) / Float(this->denom_));
        }

        template<class Float = float>
        Ratio from_float(const Float u&, const unsigned prec)
        {
            Ratio rat (T(u * cpow(10, prec)), T(cpow(10, prec)));
            if((u > 0 && u > rat.numer_)
                || (u < 0 && u < rat.numer_)) {
                throw OverflowException();
            }
            return rat;
        }

        const T& numer() const noexcept
        {
            return this->numer_;
        }

        const T& denom() const noexcept
        {
            return this->denom_;
        }

        bool is_integer() const noexcept
        {
            return this->denom_ == T(1);
        }

        void reduce() noexcept
        {
            T g = gcd(this->numer_, this->denom_);

            this->numer_ = this->numer_ / g;
            this->denom_ = this->denom_ / g;

            if(this->denom_ < T(0)) {
                this->numer_ = T(0) - this->numer_;
                this->denom_ = T(0) - this->denom_;
            }
        }

        Ratio<T> reduced() const noexcept
        {
            Ratio<T> ret(*this);
            ret.reduce();
            return ret;
        }

        Ratio<T> floor() const noexcept
        {
            if(*this < Ratio<T>(0)) {
                T one (1);
                return Ratio<T>((this->numer_ - this->denom_ + one) / this->denom_);
            } else {
                return Ratio<T>(this->numer_ / this->denom_);
            }
        }

        Ratio<T> ceil() const noexcept
        {
            if(*this < Ratio<T>(0)) {
                return Ratio<T>(this->numer_ / this->denom_);
            } else {
                T one (1);
                return Ratio<T>((this->numer_ + this->denom_ - one) / this->denom_);
            }
        }

        Ratio<T> round() const noexcept
        {
            const Ratio<T> zero(0);
            const T one(1);
            const T two(one + one);

            Ratio<T> fractional = this->fract();
            if(fractional < zero) {
                fractional = zero - fractional;
            }

            const bool half_or_larger;
            if(fractional.denom() % 2 == 0) {
                half_or_larger = fractional.numer_ >= fractional.denom_ / two;
            } else {
                half_or_larger = fractional.numer_ >= (fractional.denom_ / two) + one;
            }

            if(half_or_larger) {
                Ratio<T> one(1);
                if(*this > Ratio<T>(0)) {
                    return this->trunc() + one;
                } else {
                    return this->trunc() - one;
                }
            } else {
                return this->trunc();
            }
        }

        Ratio<T> trunc() const noexcept
        {
            return Ratio<T>(this->numer_ / this->denom_);
        }

        Ratio<T> fract() const noexcept
        {
            return Ratio<T>(this->numer_ % this->denom_, this->denom_, NoReduceTag());
        }

        Ratio<T> pow(const Ratio<T>& r, int expon) const noexcept
        {
            if(expon == 0) {
                return Ratio<T>(1);
            } else if(expon < 0) {
                return std::pow(recip(r), -expon);
            } else {
                return Ratio<T>(std::pow(r.numer(), expon), std::pow(r.numer(), expon));
            }
        }

        bool is_zero() const noexcept
        {
            return (this->numer_ == 0);
        }

        bool is_positive() const noexcept
        {
            return (this->numer_ > 0);
        }

        bool is_negative() const noexcept
        {
            return (this->numer_ < 0);
        }

        static CONSTEXPR Ratio<T> zero() noexcept
        {
            return Ratio<T>(0, 1, NoReduceTag());
        }

        static CONSTEXPR Ratio<T> one() noexcept
        {
            return Ratio<T>(1, 1, NoReduceTag());
        }

        static CONSTEXPR Ratio<T> pi() noexcept
        {
            return Ratio<T>(6283, 2000, NoReduceTag());
        }

        Ratio<T> abs() const noexcept
        {
            return (this->is_positive() || this->is_zero() ? *this : -*this);
        }

        Ratio<T> abs_sub(const Ratio<T>& rhs) const noexcept
        {
            return abs(*this - rhs);
        }

        T signum() const noexcept
        {
            if(this->is_zero()) {
                return T(0);
            } else if(this->is_positive()) {
                return T(1);
            } else {
                return T(-1);
            }
        }

        template<class U>
        explicit CONSTEXPR operator Ratio<U>() const noexcept
        {
            static_assert(std::is_convertible<U, T>::value,
                "Ratio<T>::operator Ratio<U>(): T must meet the requirements of ImplicitlyConvertible to U.");
            return Ratio<U>(U(this->numer_), U(this->denom_), NoReduceTag());
        }

        template<class U>
        friend class Ratio;

    private:

        T numer_;
        T denom_;

    };

    template<class T>
    Ratio<T> make_ratio(const T& num) noexcept
    {
        return Ratio<T>(num);
    }

    template<class T>
    Ratio<T> make_ratio(const T& numer, const T& denom) noexcept
    {
        return Ratio<T>(numer, denom);
    }

    template<class T>
    Ratio<T> operator+(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) + (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator-(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) - (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator%(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.denom()) % (lhs.denom() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator*(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return Ratio<T>((lhs.numer() * rhs.numer()), (lhs.denom() * rhs.denom()));
    }

    template<class T>
    Ratio<T> operator/(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return make_ratio((lhs.numer() * rhs.denom()), (lhs.denom() * rhs.numer()));
    }

    template<class T>
    Ratio<T> operator+=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs + rhs;
    }

    template<class T>
    Ratio<T> operator-=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs - rhs;
    }

    template<class T>
    Ratio<T> operator*=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs * rhs;
    }

    template<class T>
    Ratio<T> operator/=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs / rhs;
    }

    template<class T>
    Ratio<T> operator%=(Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return lhs = lhs % rhs;
    }

    template<class T>
    Ratio<T> operator+(const Ratio<T>& rat) noexcept
    {
        return Ratio<T>(rat);
    }

    template<class T>
    Ratio<T> operator-(const Ratio<T>& rat) noexcept
    {
        return Ratio<T>(-rat.numer(), rat.denom(), NoReduceTag());
    }

    template<class T>
    bool operator==(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (lhs.numer() * lhs.denom()) == (rhs.numer() * rhs.denom());
    }

    template<class T>
    bool operator!=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs == rhs);
    }

    template<class T>
    bool operator>(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (lhs.numer() * lhs.denom()) > (rhs.numer() * rhs.denom());
    }

    template<class T>
    bool operator<(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return (rhs > lhs);
    }

    template<class T>
    bool operator<=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs > rhs);
    }

    template<class T>
    bool operator>=(const Ratio<T>& lhs, const Ratio<T>& rhs) noexcept
    {
        return !(lhs < rhs);
    }

    template<class T>
    Ratio<T>& operator++(Ratio<T>& rat) noexcept
    {
        return rat = rat + Ratio<T>(1);;
    }

    template<class T>
    Ratio<T>& operator--(Ratio<T>& rat) noexcept
    {
        return rat = rat - Ratio<T>(1);
    }

    template<class T>
    Ratio<T> operator++(Ratio<T>& rat, int) noexcept
    {
        Ratio<T> cpy = rat;
        ++rat;
        return cpy;
    }

    template<class T>
    Ratio<T> operator--(Ratio<T>& rat, int) noexcept
    {
        Ratio<T> cpy = rat;
        --rat;
        return cpy;
    }

    typedef Ratio<std::ptrdiff_t> Rational;
    typedef Ratio<std::int32_t> Rational32;
    typedef Ratio<std::int64_t> Rational64;

    namespace literals {

        CONSTEXPR Rational operator"" _r(const unsigned long long int n) noexcept
        {
            return Rational(n, 1, NoReduceTag());
        }

        CONSTEXPR Rational operator"" _R(const unsigned long long int n) noexcept
        {
            return Rational(n, 1, NoReduceTag());
        }

    } // namespace literals

    template<class T>
    std::ostream& operator<<(std::ostream& os, Ratio<T> x)
    {
        return os << x.numer() << '/' << x.denom();
    }

    template<class T>
    std::istream& operator>>(std::istream& is, Ratio<T>& x)
    {
        T numer;
        T denom;
        std::scanf("%ld/%ld", &numer, &denom);
        x = Ratio<T>(numer, denom);
        return is;
    }

} // namespace rational

#endif<|endoftext|>


<commit_before>#include "cnn/devices.h"

#include <iostream>

#include "cnn/cuda.h"

using namespace std;

namespace cnn {

Device::~Device() {}

#if HAVE_CUDA
Device_GPU::Device_GPU(int mb, int device_id) :
    Device(DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) {
  CUDA_CHECK(cudaSetDevice(device_id));
  CUBLAS_CHECK(cublasCreate(&cublas_handle));
  CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE));
  kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float));
  kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float));
  kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float));
  float minusone = -1;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice));
  float one = 1;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice));
  float zero = 0;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice));

  // this is the big memory allocation

  size_t byte_count = (size_t)mb << 20;
  fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
  dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
  ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters

  //fxs = new AlignedMemoryPool(mb << 20, mem); // memory for node values
  //dEdfs = new AlignedMemoryPool(mb << 20, mem); // memory for node gradients
  //ps = new AlignedMemoryPool(mb << 20, mem); // memory for parameters
}

Device_GPU::~Device_GPU() {}
#endif

// TODO we should be able to configure this carefully with a configuration
// script
// CPU -- 0 params
//     -- 50mb fxs
//     -- 50mb dEdfx
Device_CPU::Device_CPU(int mb, bool shared) :
    Device(DeviceType::CPU, &cpu_mem), shmem(mem) {
  if (shared) shmem = new SharedAllocator();
  kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float));
  *kSCALAR_MINUSONE = -1;
  kSCALAR_ONE = (float*) mem->malloc(sizeof(float));
  *kSCALAR_ONE = 1;
  kSCALAR_ZERO = (float*) mem->malloc(sizeof(float));
  *kSCALAR_ZERO = 0;

  // this is the big memory allocation: the pools

  size_t byte_count = (size_t)mb << 20;
  fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
  dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
  ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters
  //fxs = new AlignedMemoryPool(mb << 20, mem); // memory for node values
  //dEdfs = new AlignedMemoryPool(mb << 20, mem); // memory for node gradients
  //ps = new AlignedMemoryPool(mb << 20, shmem); // memory for parameters
}

Device_CPU::~Device_CPU() {}

} // namespace cnn
<commit_msg>Removed commented out lines<commit_after>#include "cnn/devices.h"

#include <iostream>

#include "cnn/cuda.h"

using namespace std;

namespace cnn {

Device::~Device() {}

#if HAVE_CUDA
Device_GPU::Device_GPU(int mb, int device_id) :
    Device(DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) {
  CUDA_CHECK(cudaSetDevice(device_id));
  CUBLAS_CHECK(cublasCreate(&cublas_handle));
  CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE));
  kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float));
  kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float));
  kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float));
  float minusone = -1;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice));
  float one = 1;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice));
  float zero = 0;
  CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice));

  // this is the big memory allocation

  size_t byte_count = (size_t)mb << 20;
  fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
  dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
  ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters

}

Device_GPU::~Device_GPU() {}
#endif

// TODO we should be able to configure this carefully with a configuration
// script
// CPU -- 0 params
//     -- 50mb fxs
//     -- 50mb dEdfx
Device_CPU::Device_CPU(int mb, bool shared) :
    Device(DeviceType::CPU, &cpu_mem), shmem(mem) {
  if (shared) shmem = new SharedAllocator();
  kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float));
  *kSCALAR_MINUSONE = -1;
  kSCALAR_ONE = (float*) mem->malloc(sizeof(float));
  *kSCALAR_ONE = 1;
  kSCALAR_ZERO = (float*) mem->malloc(sizeof(float));
  *kSCALAR_ZERO = 0;

  // this is the big memory allocation: the pools

  size_t byte_count = (size_t)mb << 20;
  fxs = new AlignedMemoryPool(byte_count, mem); // memory for node values
  dEdfs = new AlignedMemoryPool(byte_count, mem); // memory for node gradients
  ps = new AlignedMemoryPool(byte_count, mem); // memory for parameters

}

Device_CPU::~Device_CPU() {}

} // namespace cnn
<|endoftext|>


<commit_before>#ifndef UNIT_CONFIG_HPP_
#define UNIT_CONFIG_HPP_

namespace unit_config {

const float DT = 0.001;

const double PI = 3.14159265358979323846;

// Maximum angular position in the roll and pitch axes (rad)
const float MAX_PITCH_ROLL_POS = 30.0 * PI / 180.0;

// Maximum angular velocity in the roll and pitch axes (rad/s)
const float MAX_PITCH_ROLL_VEL = 100.0 * PI / 180.0;

// Maximum angular acceleration (rad/s^2)
const float MAX_PITCH_ROLL_ACC = 4.0;   // TODO: calculate properly

// Sensor offsets
const float GYR_X_OFFSET  = 0.0;
const float GYR_Y_OFFSET  = 0.0;
const float GYR_Z_OFFSET  = 0.0;
const float ACC_X_OFFSET  = 0.000;
const float ACC_Y_OFFSET  = 0.012;
const float ACC_Z_OFFSET  = -0.035;
const float ACCH_X_OFFSET = 0.0;
const float ACCH_Y_OFFSET = 0.0;
const float ACCH_Z_OFFSET = 0.0;

// Initial angular position controller gains
const float ANGPOS_X_KP = 1.0;
const float ANGPOS_X_KI = 0.0;
const float ANGPOS_X_KD = 0.0;
const float ANGPOS_Y_KP = 1.0;
const float ANGPOS_Y_KI = 0.0;
const float ANGPOS_Y_KD = 0.0;
const float ANGPOS_Z_KP = 1.0;
const float ANGPOS_Z_KI = 0.0;
const float ANGPOS_Z_KD = 0.0;

// Initial angular velocity controller gains
const float ANGVEL_X_KP = 1.0;
const float ANGVEL_X_KI = 0.0;
const float ANGVEL_X_KD = 0.0;
const float ANGVEL_Y_KP = 1.0;
const float ANGVEL_Y_KI = 0.0;
const float ANGVEL_Y_KD = 0.0;
const float ANGVEL_Z_KP = 1.0;
const float ANGVEL_Z_KI = 0.0;
const float ANGVEL_Z_KD = 0.0;

// Initial angular acceleration controller gains
const float ANGACC_X_KP = 1.0;
const float ANGACC_X_KI = 0.0;
const float ANGACC_X_KD = 0.0;
const float ANGACC_Y_KP = 1.0;
const float ANGACC_Y_KI = 0.0;
const float ANGACC_Y_KD = 0.0;
const float ANGACC_Z_KP = 1.0;
const float ANGACC_Z_KI = 0.0;
const float ANGACC_Z_KD = 0.0;

}

#endif // UNIT_CONFIG_HPP_
<commit_msg>Calibrate celestep2 accel.<commit_after>#ifndef UNIT_CONFIG_HPP_
#define UNIT_CONFIG_HPP_

namespace unit_config {

const float DT = 0.001;

const double PI = 3.14159265358979323846;

// Maximum angular position in the roll and pitch axes (rad)
const float MAX_PITCH_ROLL_POS = 30.0 * PI / 180.0;

// Maximum angular velocity in the roll and pitch axes (rad/s)
const float MAX_PITCH_ROLL_VEL = 100.0 * PI / 180.0;

// Maximum angular acceleration (rad/s^2)
const float MAX_PITCH_ROLL_ACC = 4.0;   // TODO: calculate properly

// Sensor offsets
const float GYR_X_OFFSET  = 0.0;
const float GYR_Y_OFFSET  = 0.0;
const float GYR_Z_OFFSET  = 0.0;
const float ACC_X_OFFSET  =  0.011;
const float ACC_Y_OFFSET  = -0.018;
const float ACC_Z_OFFSET  = -0.240;
const float ACCH_X_OFFSET = 0.0;
const float ACCH_Y_OFFSET = 0.0;
const float ACCH_Z_OFFSET = 0.0;

// Initial angular position controller gains
const float ANGPOS_X_KP = 1.0;
const float ANGPOS_X_KI = 0.0;
const float ANGPOS_X_KD = 0.0;
const float ANGPOS_Y_KP = 1.0;
const float ANGPOS_Y_KI = 0.0;
const float ANGPOS_Y_KD = 0.0;
const float ANGPOS_Z_KP = 1.0;
const float ANGPOS_Z_KI = 0.0;
const float ANGPOS_Z_KD = 0.0;

// Initial angular velocity controller gains
const float ANGVEL_X_KP = 1.0;
const float ANGVEL_X_KI = 0.0;
const float ANGVEL_X_KD = 0.0;
const float ANGVEL_Y_KP = 1.0;
const float ANGVEL_Y_KI = 0.0;
const float ANGVEL_Y_KD = 0.0;
const float ANGVEL_Z_KP = 1.0;
const float ANGVEL_Z_KI = 0.0;
const float ANGVEL_Z_KD = 0.0;

// Initial angular acceleration controller gains
const float ANGACC_X_KP = 1.0;
const float ANGACC_X_KI = 0.0;
const float ANGACC_X_KD = 0.0;
const float ANGACC_Y_KP = 1.0;
const float ANGACC_Y_KI = 0.0;
const float ANGACC_Y_KD = 0.0;
const float ANGACC_Z_KP = 1.0;
const float ANGACC_Z_KI = 0.0;
const float ANGACC_Z_KD = 0.0;

}

#endif // UNIT_CONFIG_HPP_
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Mustafa Serdar Sanli
// Copyright (c) 2015 Markus Kuhn
//
// 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.

// Tests cases for
// "UTF-8 decoder capability and stress test"
// authored by Markus Kuhn
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
//
// a copy of the file can be found under tests/doc/

#include <iostream>

#include "lib/Common.hpp"

#define CATCH_CONFIG_MAIN
#include "third_party/catch.hpp"

using namespace std;

#define PARSE(data) ParseJsonString(reinterpret_cast<const char*>(data), \
                                    reinterpret_cast<const char*>(data) + sizeof(data) )

string ParseJsonString(const char *beg, const char *end)
{
	string out;

	QuantumJsonImpl__::Parser<const char *> p(beg, end);
	p.ParseValueInto(out);
	if (p.errorCode != QuantumJsonImpl__::ErrorCode::NoError)
	{
		throw p.errorCode;
	}
	return out;
}

TEST_CASE("Case 1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == u8"κόσμε" );
}

TEST_CASE("Case 2.1.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x00,
	'"', };

	// ErrorCode::ControlCharacterInString;
	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 2.1.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xc2, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u0080" );
}

TEST_CASE("Case 2.1.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xe0, 0xa0, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u0800" );
}

TEST_CASE("Case 2.1.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf0, 0x90, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00010000" );
}

TEST_CASE("Case 2.1.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf8, 0x88, 0x80, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00200000" );
}

TEST_CASE("Case 2.1.6", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfc, 0x84, 0x80, 0x80, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U04000000" );
}

TEST_CASE("Case 2.2.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x7f,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u007f" );
}

TEST_CASE("Case 2.2.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xdf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u07ff" );
}

TEST_CASE("Case 2.2.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xef, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\uffff" );
}

TEST_CASE("Case 2.2.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf7, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U001fffff" );
}

TEST_CASE("Case 2.2.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfb, 0xbf, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U03ffffff" );
}

TEST_CASE("Case 2.2.6", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U7fffffff" );
}

TEST_CASE("Case 2.3.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xed, 0x9f, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ud7ff" );
}

TEST_CASE("Case 2.3.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xee, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ue000" );
}

TEST_CASE("Case 2.3.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xef, 0xbf, 0xbd,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ufffd" );
}

TEST_CASE("Case 2.3.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf4, 0x8f, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U0010FFFF" );
}

TEST_CASE("Case 2.3.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf4, 0x90, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00110000" );
}

// TODO Add case 3.1.1
// TODO Add case 3.1.2
// TODO Add case 3.1.3
// TODO Add case 3.1.4
// TODO Add case 3.1.5
// TODO Add case 3.1.6
// TODO Add case 3.1.7
// TODO Add case 3.1.8
// TODO Add case 3.1.9
// TODO Add case 3.2.1
// TODO Add case 3.2.2
// TODO Add case 3.2.3
// TODO Add case 3.2.4
// TODO Add case 3.2.5
// TODO Add case 3.3.1
// TODO Add case 3.3.2
// TODO Add case 3.3.3
// TODO Add case 3.3.4
// TODO Add case 3.3.5
// TODO Add case 3.3.6
// TODO Add case 3.3.7
// TODO Add case 3.3.8
// TODO Add case 3.3.9
// TODO Add case 3.3.10
// TODO Add case 3.4
// TODO Add case 3.5.1
// TODO Add case 3.5.2
// TODO Add case 3.5.3
// TODO Add case 4.1.1
// TODO Add case 4.1.2
// TODO Add case 4.1.3
// TODO Add case 4.1.4
// TODO Add case 4.1.5
// TODO Add case 4.2.1
// TODO Add case 4.2.2
// TODO Add case 4.2.3
// TODO Add case 4.2.4
// TODO Add case 4.2.5
// TODO Add case 4.3.1
// TODO Add case 4.3.2
// TODO Add case 4.3.3
// TODO Add case 4.3.4
// TODO Add case 4.3.5
// TODO Add case 5.1.1
// TODO Add case 5.1.2
// TODO Add case 5.1.3
// TODO Add case 5.1.4
// TODO Add case 5.1.5
// TODO Add case 5.1.6
// TODO Add case 5.1.7
// TODO Add case 5.2.1
// TODO Add case 5.2.2
// TODO Add case 5.2.3
// TODO Add case 5.2.4
// TODO Add case 5.2.5
// TODO Add case 5.2.6
// TODO Add case 5.2.7
// TODO Add case 5.2.8
// TODO Add case 5.3.1
// TODO Add case 5.3.2
// TODO Add case 5.3.3
// TODO Add case 5.3.4
<commit_msg>Add cases 3.1.x<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Mustafa Serdar Sanli
// Copyright (c) 2015 Markus Kuhn
//
// 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.

// Tests cases for
// "UTF-8 decoder capability and stress test"
// authored by Markus Kuhn
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
//
// a copy of the file can be found under tests/doc/

#include <iostream>

#include "lib/Common.hpp"

#define CATCH_CONFIG_MAIN
#include "third_party/catch.hpp"

using namespace std;

#define PARSE(data) ParseJsonString(reinterpret_cast<const char*>(data), \
                                    reinterpret_cast<const char*>(data) + sizeof(data) )

string ParseJsonString(const char *beg, const char *end)
{
	string out;

	QuantumJsonImpl__::Parser<const char *> p(beg, end);
	p.ParseValueInto(out);
	if (p.errorCode != QuantumJsonImpl__::ErrorCode::NoError)
	{
		throw p.errorCode;
	}
	return out;
}

TEST_CASE("Case 1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == u8"κόσμε" );
}

TEST_CASE("Case 2.1.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x00,
	'"', };

	// ErrorCode::ControlCharacterInString;
	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 2.1.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xc2, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u0080" );
}

TEST_CASE("Case 2.1.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xe0, 0xa0, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u0800" );
}

TEST_CASE("Case 2.1.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf0, 0x90, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00010000" );
}

TEST_CASE("Case 2.1.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf8, 0x88, 0x80, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00200000" );
}

TEST_CASE("Case 2.1.6", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfc, 0x84, 0x80, 0x80, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U04000000" );
}

TEST_CASE("Case 2.2.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x7f,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u007f" );
}

TEST_CASE("Case 2.2.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xdf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\u07ff" );
}

TEST_CASE("Case 2.2.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xef, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\uffff" );
}

TEST_CASE("Case 2.2.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf7, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U001fffff" );
}

TEST_CASE("Case 2.2.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfb, 0xbf, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U03ffffff" );
}

TEST_CASE("Case 2.2.6", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U7fffffff" );
}

TEST_CASE("Case 2.3.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xed, 0x9f, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ud7ff" );
}

TEST_CASE("Case 2.3.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xee, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ue000" );
}

TEST_CASE("Case 2.3.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xef, 0xbf, 0xbd,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\ufffd" );
}

TEST_CASE("Case 2.3.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf4, 0x8f, 0xbf, 0xbf,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U0010FFFF" );
}

TEST_CASE("Case 2.3.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xf4, 0x90, 0x80, 0x80,
	'"', };

	string out = PARSE(input);
	REQUIRE( out == "\U00110000" );
}

TEST_CASE("Case 3.1.1", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.2", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0xbf,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.3", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.4", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf, 0x80,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.5", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf, 0x80, 0xbf,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.6", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf, 0x80, 0xbf, 0x80,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.7", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf, 0x80, 0xbf, 0x80, 0xbf,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.8", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0xbf, 0x80, 0xbf, 0x80, 0xbf, 0x80,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

TEST_CASE("Case 3.1.9", "[utf8,decoder]")
{
	unsigned char input[] = { '"',
	    0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
	    0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
	    0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
	    0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
	    0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
	    0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
	    0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
	    0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
	'"', };

	REQUIRE_THROWS_AS( PARSE(input), QuantumJsonImpl__::ErrorCode );
}

// TODO Add case 3.2.1
// TODO Add case 3.2.2
// TODO Add case 3.2.3
// TODO Add case 3.2.4
// TODO Add case 3.2.5
// TODO Add case 3.3.1
// TODO Add case 3.3.2
// TODO Add case 3.3.3
// TODO Add case 3.3.4
// TODO Add case 3.3.5
// TODO Add case 3.3.6
// TODO Add case 3.3.7
// TODO Add case 3.3.8
// TODO Add case 3.3.9
// TODO Add case 3.3.10
// TODO Add case 3.4
// TODO Add case 3.5.1
// TODO Add case 3.5.2
// TODO Add case 3.5.3
// TODO Add case 4.1.1
// TODO Add case 4.1.2
// TODO Add case 4.1.3
// TODO Add case 4.1.4
// TODO Add case 4.1.5
// TODO Add case 4.2.1
// TODO Add case 4.2.2
// TODO Add case 4.2.3
// TODO Add case 4.2.4
// TODO Add case 4.2.5
// TODO Add case 4.3.1
// TODO Add case 4.3.2
// TODO Add case 4.3.3
// TODO Add case 4.3.4
// TODO Add case 4.3.5
// TODO Add case 5.1.1
// TODO Add case 5.1.2
// TODO Add case 5.1.3
// TODO Add case 5.1.4
// TODO Add case 5.1.5
// TODO Add case 5.1.6
// TODO Add case 5.1.7
// TODO Add case 5.2.1
// TODO Add case 5.2.2
// TODO Add case 5.2.3
// TODO Add case 5.2.4
// TODO Add case 5.2.5
// TODO Add case 5.2.6
// TODO Add case 5.2.7
// TODO Add case 5.2.8
// TODO Add case 5.3.1
// TODO Add case 5.3.2
// TODO Add case 5.3.3
// TODO Add case 5.3.4
<|endoftext|>


<commit_before><commit_msg>coverity#705773 Resource leak<commit_after><|endoftext|>